diff --git a/.github/workflows/exakat.yml b/.github/workflows/exakat.yml new file mode 100644 index 00000000000..861f6ccd4b0 --- /dev/null +++ b/.github/workflows/exakat.yml @@ -0,0 +1,17 @@ +# See syntax file on https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions +name: "Exakat analysis" + +on: + schedule: + - cron: "0 20 * * *" + +jobs: + exakat: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Exakat + uses: docker://exakat/exakat-ga + with: + ignore_rules: 'Classes/UseInstanceof,Performances/PrePostIncrement,Functions/WrongNumberOfArguments,Variables/UndefinedVariable,Classes/DontUnsetProperties,Classes/NonPpp,Classes/StaticMethodsCalledFromObject,Classes/UseClassOperator,Functions/UsesDefaultArguments,Php/NoClassInGlobal,Php/ShouldUseCoalesce,Structures/MergeIfThen,Structures/ElseIfElseif,Structures/RepeatedPrint,Structures/UselessParenthesis,Structures/SwitchWithoutDefault,Structures/ShouldMakeTernary,Structures/UseConstant' + ignore_dirs: '/htdocs/includes,/htdocs/build,/htdocs/dev,/htdocs/doc,/htdocs/scripts,/htdocs/test' \ No newline at end of file diff --git a/.github/workflows/stale-issues-safe.yml b/.github/workflows/stale-issues-safe.yml index ed37c9aadc2..844b19c7a3f 100644 --- a/.github/workflows/stale-issues-safe.yml +++ b/.github/workflows/stale-issues-safe.yml @@ -14,11 +14,11 @@ jobs: - uses: Dolibarr/stale@staleunstale with: repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-message: 'This issue is stale because it has been open 1 year with no activity. If this is a bug, please comment to confirm it is still present on latest stable version. if this is a feature request, please comment to notify the request is still relevant and not yet covered by latest stable version. This issue may be closed automatically by stale bot in 15 days (you should still be able to re-open it if required).' + stale-message: 'This issue is stale because it has been open 1 year with no activity. If this is a bug, please comment to confirm it is still present on latest stable version. if this is a feature request, please comment to notify the request is still relevant and not yet covered by latest stable version. This issue may be closed automatically by stale bot in 10 days (you should still be able to re-open it if required).' stale-label: 'Issue Stale (automatic label)' exempt-labels: 'Priority High / Blocking,Priority Top Strategic,Priority Medium,Hacktoberfest,good first issue,Bug Security (CVE),Analysis of PR in progres' days-before-stale: 365 - days-before-close: 15 + days-before-close: 10 operations-per-run: 100 dry-run: false \ No newline at end of file diff --git a/.gitignore b/.gitignore index 30151359365..b49fdf8dc86 100644 --- a/.gitignore +++ b/.gitignore @@ -36,8 +36,21 @@ htdocs/includes/jakub-onderka/ htdocs/includes/phpdocumentor/ htdocs/includes/phpspec/ htdocs/includes/phpunit/ +htdocs/includes/php-parallel-lint/ htdocs/includes/sebastian/ htdocs/includes/squizlabs/ -htdocs/includes/symfony/ htdocs/includes/webmozart/ htdocs/.well-known/apple-developer-merchantid-domain-association + +# Node Modules +build/yarn-error.log +build/node_modules/ +node_modules/ + +#yarn +yarn.lock + +#package-lock +package-lock.json + +doc/install.lock diff --git a/.travis.yml b/.travis.yml index ca9641ce63e..16d3403f554 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,8 @@ os: linux dist: xenial #dist: bionic -sudo: required +# Deprecated: The key sudo has no effect anymore. +#sudo: required language: php @@ -119,24 +120,18 @@ install: echo - | - echo "Installing Composer dependencies (PHP Unit, Parallel Lint & PHP CodeSniffer" - if [ "$TRAVIS_PHP_VERSION" = '5.4' ] || [ "$TRAVIS_PHP_VERSION" = '5.5' ]; then - composer -n require phpunit/phpunit ^4 \ - jakub-onderka/php-parallel-lint ^0 \ - jakub-onderka/php-console-highlighter ^0 \ - squizlabs/php_codesniffer ^3 - fi + echo "Installing Composer dependencies - PHP Unit, Parallel Lint, PHP CodeSniffer - for $TRAVIS_PHP_VERSION" if [ "$TRAVIS_PHP_VERSION" = '5.6' ] || [ "$TRAVIS_PHP_VERSION" = '7.0' ] || [ "$TRAVIS_PHP_VERSION" = '7.1' ] \ [ "$TRAVIS_PHP_VERSION" = '7.2' ] || [ "$TRAVIS_PHP_VERSION" = '7.3' ] || [ "$TRAVIS_PHP_VERSION" = '7.4' ]; then composer -n require phpunit/phpunit ^5 \ - jakub-onderka/php-parallel-lint ^0 \ - jakub-onderka/php-console-highlighter ^0 \ + php-parallel-lint/php-parallel-lint ^0 \ + php-parallel-lint/php-console-highlighter ^0 \ squizlabs/php_codesniffer ^3 fi if [ "$TRAVIS_PHP_VERSION" = 'nightly' ]; then composer -n require --ignore-platform-reqs phpunit/phpunit ^5 \ - jakub-onderka/php-parallel-lint ^0 \ - jakub-onderka/php-console-highlighter ^0 \ + php-parallel-lint/php-parallel-lint ^1 \ + php-parallel-lint/php-console-highlighter ^0 \ squizlabs/php_codesniffer ^3 fi echo @@ -283,7 +278,11 @@ script: # Ensure we catch errors set -e #parallel-lint --exclude htdocs/includes --blame . - parallel-lint --exclude dev/namespacemig --exclude htdocs/includes/myclabs --exclude htdocs/includes/webmozart --exclude htdocs/includes/phpspec --exclude dev/initdata/dbf/includes --exclude htdocs/includes/sabre --exclude htdocs/includes/phpoffice/phpexcel/Classes/PHPExcel/Shared --exclude htdocs/includes/phpoffice/PhpSpreadsheet --exclude htdocs/includes/sebastian --exclude htdocs/includes/squizlabs/php_codesniffer --exclude htdocs/includes/jakub-onderka --exclude htdocs/includes/mike42/escpos-php/example --exclude htdocs/includes/phpunit/ --exclude htdocs/includes/composer/autoload_static.php --blame . + parallel-lint --exclude dev/namespacemig --exclude htdocs/includes/composer --exclude htdocs/includes/myclabs --exclude htdocs/includes/phpspec --exclude dev/initdata/dbf/includes \ + --exclude htdocs/includes/sabre --exclude htdocs/includes/phpoffice/phpexcel --exclude htdocs/includes/phpoffice/PhpSpreadsheet --exclude htdocs/includes/sebastian \ + --exclude htdocs/includes/squizlabs/php_codesniffer --exclude htdocs/includes/jakub-onderka --exclude htdocs/includes/php-parallel-lint --exclude htdocs/includes/symfony \ + --exclude htdocs/includes/mike42/escpos-php/example --exclude htdocs/includes/maximebf \ + --exclude htdocs/includes/phpunit/ --exclude htdocs/includes/tecnickcom/tcpdf/include/barcodes --exclude htdocs/includes/webmozart --blame . set +e echo diff --git a/COPYRIGHT b/COPYRIGHT index 251ad7f2fe4..d8cefedcd65 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -21,7 +21,7 @@ Mobiledetect 2.8.34 MIT License Yes NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package) PEAR Mail_MIME 1.8.9 BSD Yes NuSoap dependency ParseDown 1.6 MIT License Yes Markdown parser -PHPDebugBar 1.15.0 MIT License Yes Used only by the module "debugbar" for developers +PHPDebugBar 1.15.1 MIT License Yes Used only by the module "debugbar" for developers PHPExcel 1.8.1 LGPL-2.1+ Yes Read/Write XLS files, read ODS files PHPSpreadSheet ? LGPL-2.1+ Yes Read/Write XLS files, read ODS files php-iban 1.4.7 LGPL-3+ Yes Parse and validate IBAN (and IIBAN) bank account information in PHP diff --git a/ChangeLog b/ChangeLog index 58513986a1e..60aa376f96d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -2,17 +2,75 @@ English Dolibarr ChangeLog -------------------------------------------------------------- + ***** ChangeLog for 13.0.0 compared to 12.0.0 ***** For users: -NEW: Add module Credit transfer SEPA to manage payment of supplier using bank credit transfer SEPA files +NEW: Add module "Credit transfer SEPA" to manage payment of vendors using bank credit transfer SEPA files. +NEW: Module Reception (for a more accurate management of your receptions) moved from experimental to stable. WARNING: Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: -* Properties ->contactid has been renamed into ->contact_id - +* Properties ->contactid have been renamed into ->contact_id +* Properties ->titre have been renamed into ->title +* Property $paiementid in API 'api_supplier_invoices.php' has been renamed into into $payment_mode_id (english) +* The deprecated subsitution key __SIGNATURE__ has been removed. Replace with __USER_SIGNATURE__ if you used the old syntax in + your email templates. +* The hidden option HOLIDAY_MORE_PUBLIC_HOLIDAYS has been removed. Use instead the dictionary table if you need to define custom + days of holiday. +* Property 'num_paiement' has been renamed 'num_payment' everywhere for better code consistency. +* If you build a class that implement CommonObject to use the incoterm properties or methods (->fk_incoterm, ->label_incoterm, ->location_incoterm), + you must now also include declaration of the Trait 'CommonIncoterm' in your class. All incoterm functions were moved into this Trait. +* The GETPOST(..., 'alpha') has now the same behaviour than GETPOST(..., 'alphanohtml') so no html will be allowed. Use GETPOST(..., 'restricthtml') to accept HTML. +* If you have links in your code with '&action=delete' as a parameter, you must also add '&token='.newToken() as another parameter to avoid CSRF protection errors. +* The API addPayment for api_invoice has evolved to accept amount into a foreign currency. You must provide array(amount=>X,mutlicurrency_ammount=>Y) instead of amount. +* The method select_thirdparty(), deprecated since 3.8, into html.form.class.php has been removed. +***** ChangeLog for 12.0.3 compared to 12.0.2 ***** +FIX: 10.0 - when the mime file name is different from the filesystem name, the attachment name should be the mime filename +FIX: 11.0 - expenses lines overlapping the total amounts frame +FIX: 12.0 - round value of virtual stock on product stock reassort list +FIX: #14469 +FIX: #14474 Error when deleting +FIX: #14530 +FIX: #14703 +FIX: - Accountancy balance Error SQL on entity +FIX: Bad number of subscription (forgotten when member was resiliated) +FIX: bad route url to delete subproduct with API +FIX: Category for suplements not saved +FIX: Compatibility with modules without document generation +FIX: Cron load lang +FIX: CSS +FIX: Error management. Do no try to approve PO if validation fails. +FIX: expenses lines overlapping the frame for total amounts. +FIX: Filter in "billed" of orders was not saved +FIX: infinite fetch object linked loop +FIX: Intervention lose html tags when updating +FIX: JS CRASH - bad usage of moreparam +FIX: lang fr retained warranty +FIX: Look and feel v12: First tab must be name of object +FIX: missing entity check +FIX: missing param for hook +FIX: Missing transaction on PO actions +FIX: MySql Strict mode +FIX: param entity in html form file +FIX: Problems on FEC format +FIX: round stock value on product list +FIX: - Send mail from contact : select mail model +FIX: set sales representatives on create company card +FIX: Setup of stock increase/decrease +FIX: sign of amount with credit note and multicurrencies +FIX: Static property called as non static +FIX: task leftmenu +FIX: title button attribute id empty +FIX: unit price divided by quantity when accepting supplier price proposal +FIX: Update extrafields on line only if it is supported +FIX: Update line of BOM +FIX: using decimal on stock correction +FIX: Visualization rights correction on last modified contacts box +FIX: Wrong redirection +FIX: Yogosha report 4425 (backport) ***** ChangeLog for 12.0.2 compared to 12.0.1 ***** FIX: computation of the bottom margin of returns NaN because body is not loaded yet @@ -340,14 +398,14 @@ Following changes may create regressions for some external modules, but were nec WARNING FOR DOLIWAMP USERS ONLY: -Only people that installed Dolibarr using the all-in-one autoinstaller for Windows called "DoliWAMP" are concerned by the following warnings: +Only people that installed Dolibarr using the all-in-one auto-installer for Windows called "DoliWAMP" are concerned by the following warnings: -* DoliWAMP autoinstaller for Windows is not more available on 32bits systems. Use standard package if you need to use such architecture. -* It is not possible to migrate from an installation done with the old DoliWAMP autoinstaller for Windows by using this new one. You must make a backup - of your database, make a fresh installation using the new installer and reload. -* Don't forget that DoliWAMP is a good solution to make a quick test of Dolibarr on your local computer but was never recommanded as a production - solution on a local desktop since a desktop computer has not a backup and security policy as good as on a server (when there is one). - DoliWAMP remains a solution for fast test or demo purposes. +* DoliWAMP auto-installer for Windows is no more available on 32 bits systems. Use standard package if you need to use such architecture. +* It is not possible to migrate from an installation done with the old DoliWAMP auto-installer for Windows by using this new one. + You must make a backup of your database, make a fresh installation using the new installer and reload your backup. + Don't forget that DoliWAMP is a good solution to make a quick test of Dolibarr on your local computer but is not recommended as a production + solution on a local desktop since a local desktop computer has often no backup and security policy, or not as good as on a server (when there is one). + DoliWAMP remains a solution for fast test or demo purposes. Prefer using standard packages for production. ***** ChangeLog for 11.0.5 compared to 11.0.4 ***** diff --git a/README.md b/README.md index fa5326079ec..648d5ef003d 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,15 @@ ![Downloads per day](https://img.shields.io/sourceforge/dw/dolibarr.svg) ![Build status](https://img.shields.io/travis/Dolibarr/dolibarr/develop.svg) -Dolibarr ERP & CRM is a modern software package to manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda…). +Dolibarr ERP & CRM is a modern software package that helps manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda…). -It's an Open Source Software (written in PHP language) designed for small, medium or large companies, foundations and freelancers. +It's an Open Source Software suite (written in PHP with optional JavaScript enhancements) designed for small, medium or large companies, foundations and freelancers. -You can freely use, study, modify or distribute it according to its Free Software licence. +You can freely use, study, modify or distribute it according to its licence. -You can use it as a standalone application or as a web application to be able to access it from the Internet or a LAN. +You can use it as a standalone application or as a web application to access it from the Internet or a LAN. + +Dolibarr has a large community ready to help you, free forums and [oficially preferred partners ready to offer commercial support should you need it](https://partners.dolibarr.org) ![ScreenShot](https://www.dolibarr.org/images/dolibarr_screenshot1_1920x1080.jpg) @@ -27,19 +29,23 @@ Other licenses apply for some included dependencies. See [COPYRIGHT](https://git If you have low technical skills and you're looking to install Dolibarr ERP/CRM in just a few clicks, you can use one of the packaged versions: -- [DoliWamp for Windows](https://wiki.dolibarr.org/index.php/Dolibarr_for_Windows_(DoliWamp) -- [DoliDeb for Debian](https://wiki.dolibarr.org/index.php/Dolibarr_for_Ubuntu_or_Debian +- [DoliWamp for Windows](https://wiki.dolibarr.org/index.php/Dolibarr_for_Windows_DoliWamp) +- [DoliDeb for Debian](https://wiki.dolibarr.org/index.php/Dolibarr_for_Ubuntu_or_Debian) - DoliRpm for Redhat, Fedora, OpenSuse, Mandriva or Mageia Releases can be downloaded from [official website](https://www.dolibarr.org/). ### Advanced setup -You can use a Web server and a supported database (MariaDB, MySQL or PostgreSQL) to install the standard version. +You can use a web server and a supported database (MariaDB, MySQL or PostgreSQL) to install the standard version. + +On GNU/Linux, first check if your distribution has already packaged Dolibarr. + +#### Generic install steps: - Check that your installed PHP version is supported [see PHP support](https://wiki.dolibarr.org/index.php/Versions). -- Uncompress the downloaded .zip archive to copy the "dolibarr/htdocs" directory and all its files inside your web server root or get the files directly from GitHub (recommanded if you known git): +- Uncompress the downloaded .zip archive to copy the "dolibarr/htdocs" directory and all its files inside your web server root or get the files directly from GitHub (recommanded if you know git as it makes it easier if you want to upgrade later): `git clone https://github.com/dolibarr/dolibarr -b x.y` (where x.y is main version like 3.6, 9.0, ...) @@ -70,13 +76,13 @@ If you don't have time to install it yourself, you can try some commercial 'read ## UPGRADING -- At first make a backup of your Dolibarr files & than see https://wiki.dolibarr.org/index.php/Installation_-_Upgrade#Upgrade_Dolibarr +Dolibarr supports upgrading usually wihtout the need for any (commercial) support (depending on if you use any commercial extensions) and supports upgrading all the way from any version after 2.8 without breakage. This is unique in the ERP ecosystem and a benefit our users highly appreciate! + +- At first make a backup of your Dolibarr files & than [see](https://wiki.dolibarr.org/index.php/Installation_-_Upgrade#Upgrade_Dolibarr) - Check that your installed PHP version is supported by the new version [see PHP support](./doc/phpmatrix.md). - Overwrite all old files from 'dolibarr' directory with files provided into the new version's package. -- At first next access, Dolibarr will redirect your to the "install/" page to follow the upgrade process. -  If an `install.lock` file exists to lock any other upgrade process, the application will ask you to remove the file manually (you should find the `install.lock` file into the directory used to store generated and uploaded documents, in most cases, it is the directory called "*documents*"). - -*Note: migration process can be safely done multiple times by calling the `/install/index.php` page* +- At first next access, Dolibarr will redirect you to the "install/" page to follow the upgrade process. +  If an `install.lock` file exists to lock any other upgrade process, the application will ask you to remove the file manually (you should find the `install.lock` file in the directory used to store generated and uploaded documents, in most cases, it is the directory called "*documents*"). ## WHAT'S NEW @@ -139,7 +145,7 @@ See the [ChangeLog](https://github.com/Dolibarr/dolibarr/blob/develop/ChangeLog) - Highly customizable: enable only the modules you need, add user personalized fields, choose your skin, several menu managers (can be used by internal users as a back-office with a particular menu, or by external users as a front-office with another one) - APIs -- An easy to understand, maintain and develop code (PHP with no heavy framework; trigger and hook architecture) +- Code that is easy to understand, maintain and develop (PHP with no heavy framework; trigger and hook architecture) - Support a lot of country specific features: - Spanish Tax RE and ISPF - French NPR VAT rate (VAT called "Non Perçue Récupérable" for DOM-TOM) @@ -149,7 +155,7 @@ See the [ChangeLog](https://github.com/Dolibarr/dolibarr/blob/develop/ChangeLog) - Compatible with [European directives](http://europa.eu/legislation_summaries/taxation/l31057_en.htm) (2006/112/CE ... 2010/45/UE) - Compatible with European GDPR rules - ... -- PDF or ODT generation for invoice, proposals, orders... +- Flexible PDF & ODT generation for invoices, proposals, orders... - … ### System Environment / Requirements @@ -167,12 +173,12 @@ These are features that Dolibarr does **not** yet fully support: - Tasks dependencies in projects - Payroll module -- No native embedded Webmail +- No native embedded Webmail, but you can send email to contacts in Dolibarr with e.g. offers, invoices, etc. - Dolibarr can't do coffee (yet) ## DOCUMENTATION -Administrator, user, developer and translator's documentations are available along with other community resources on the [Wiki](https://wiki.dolibarr.org). +Administrator, user, developer and translator's documentations are available along with other community resources in the [Wiki](https://wiki.dolibarr.org). ## CONTRIBUTING @@ -182,7 +188,7 @@ This project exists thanks to all the people who contribute. [[Contribute](https ## CREDITS -Dolibarr is the work of many contributors over the years and uses some fine libraries. +Dolibarr is the work of many contributors over the years and uses some fine PHP libraries. See [COPYRIGHT](https://github.com/Dolibarr/dolibarr/blob/develop/COPYRIGHT) file. diff --git a/SECURITY.md b/SECURITY.md index e5493805733..56e1da679ed 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,13 +1,115 @@ # Security Policy -## Supported Versions +This file contains some policies about the security reports on Dolibarr ERP CRM project, one of the most popular Open Source ERP and CRM in the world. + +## Supported Versions for security reports + +| Version | Supported | +| --------- | ------------------ | +| <= 9.0.* | :x: | +| >= 10.0.* | :white_check_mark: | -| Version | Supported | -| -------- | ------------------ | -| <= 8.0.* | :x: | -| >= 9.0.* | :white_check_mark: | ## Reporting a Vulnerability To report a vulnerability, please send an email to security@dolibarr.org In most cases, after fixing the security, we make an answer by email to say the issue has been fixed. + + +## Hunting vulnerabilities on Dolibarr + +We believe that future of software is online SaaS. This means software are more and more critical and no technology is perfect. Working with skilled security researchers is crucial in identifying weaknesses in our technology. + +If you believe you've found a security bug in our service, we are happy to work with you to resolve the issue promptly and ensure you are fairly rewarded for your discovery. + +Any type of denial of service attacks is strictly forbidden, as well as any interference with network equipment and Dolibarr infrastructure. + +We recommand to install Dolibarr ERP CRM on you own server (as most Open Source software, download and use is free: https://www.dolibarr.org/download) to get access on every side of application. + +### User Agent + +If you try to find bug on Dolibarr, we recommend to append to your user-agent header the following value: '-BugHunting-dolibarr'. + +### Account access + +You can install the web application yourself on your own platform/server so you get full access to application and sources. Download the zip of the files to put into your own web server virtual host from https://www.dolibarr.org/download + + +## Eligibility and Responsible Disclosure + +We are happy to thank everyone who submits valid reports which help us improve the security of Dolibarr however, only those that meet the following eligibility requirements may receive a monetary reward: + +You must be the first reporter of a vulnerability. + +The vulnerability must be a qualifying vulnerability (see below) + +Any vulnerability found must be reported no later than 24 hours after discovery + +You must send a clear textual description of the report along with steps to reproduce the issue, include attachments such as screenshots or proof of concept code as necessary. + +You must avoid tests that could cause degradation or interruption of our service (refrain from using automated tools, and limit yourself about requests per second), that's why we recommand to install softwate on your own platform. + +You must not leak, manipulate, or destroy any user data. + +You must not be a former or current employee of Dolibarr or one of its contractor. + +Reports about vulnerabilities are examined by our security analysts. + +Our analysis is always based on worst case exploitation of the vulnerability, as is the reward we pay. + +No vulnerability disclosure, including partial is allowed for the moment. + + +## Scope for qualified vulnerabilities + +ONLY vulnerabilities discovered, when the following setup on test platform is used, are accepted: + +* $dolibarr_main_prod must be set to 1 into conf.php +* $dolibarr_nocsrfcheck must be kept to the value 0 into conf.php (this is the default value) +* $dolibarr_main_force_https must be set to something else than 0. +* The constant MAIN_SECURITY_CSRF_WITH_TOKEN must be set to 1 into backoffice menu Home - Setup - Other (this protection should be enabled soon by default) +* The module DebugBar must NOT be enabled (by default, this module is not enabled. This is a developer tool) +* The module ModuleBuilder must NOT be enabled (by default, this module is not enabled. This is a developer tool) +* ONLY security reports on modules provided by default and with the "stable" status are allowed (troubles into "experimental", "developement" or external modules are not accepted). +* The root of web server must link to htdocs and the documents directory must be outside of the web server root (this is the default when using the default installer but may differs with external installer). +* The web server setup must be done so only the documents directory is in write mode. The root directory called htdocs must be readonly. +* CSRF attacks are accepted for all when using a POST URL, but are accepted only for creating or updating data resctricted to the admin user when using GET URL. +* Ability for a high level user to edit web site pages in the CMS by including javascript is an expected feature. + +Scope is the web application (back office) and the APIs. + + +## Qualifying vulnerabilities for Bug bounty programs +* Remote code execution (RCE) +* Local files access and manipulation (LFI, RFI, XXE, SSRF, XSPA) +* Code injections (HTML, JS, SQL, PHP, ...) +* Cross-Site Scripting (XSS) +* Cross-Site Requests Forgery (CSRF) with real security impact +* Open redirect +* Broken authentication & session management +* Insecure direct object references +* CORS with real security impact +* Horizontal and vertical privilege escalation +* "HTTP Host Header" XSS +* Software version disclosure (for non admin users only) +* Stack traces or path disclosure (for non admin users only) + + +## Non-qualifying vulnerabilities for Bug bounty programs, but qualified for reporting +* "Self" XSS +* SSL/TLS best practices +* Denial of Service attacks +* Clickjacking/UI redressing +* Physical or social engineering attempts or issues that require physical access to a victim’s computer/device +* Presence of autocomplete attribute on web forms +* Vulnerabilities affecting outdated browsers or platforms +* Logout and other instances of low-severity Cross-Site Request Forgery +* Missing cookie flags +* Missing security-related HTTP headers which do not lead directly to a vulnerability +* Reports from automated web vulnerability scanners (Acunetix, Vega, etc.) that have not been validated +* Invalid or missing SPF (Sender Policy Framework) records (Incomplete or missing SPF/DKIM/DMARC) +* Reports on features flagged as "experimental" or "development" +* Software version or private IP disclosure when logged user is admin +* Stack traces or path disclosure when logged user is admin +* Any vulnerabilities due to a configuration different than the one defined into chapter "Scope for qualified vulnerabilities". + diff --git a/build/README b/build/README index 67ceb05c8d2..f7e8ebfe60b 100644 --- a/build/README +++ b/build/README @@ -19,30 +19,34 @@ Note: Prerequisites to build autoexe DoliWamp package: > Launch "wine cmd" to check a drive Z: pointing to / exists. > Install InnoSetup For example by running isetup-5.3.9.exe (http://www.jrsoftware.org) -> Install WampServer into "C:\Program Files\Wamp" - For example by running wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe (http://www.wampserver.com) -> Install WampServer addon to have versions: Mysql5.0.45 - For example by running WampServer2-MYSQL5045.exe (http://www.wampserver.com) -> To build from Windows (running from makepack-dolibarr.pl script is however - recommanded), open file build/exe/doliwamp.iss and click on button "Compile". - The .exe file will be build into directory build. +> Install WampServer into "C:\wamp64" to have Apache, PHP and MariaDB + For example by running wampserver3.2.0_x64.exe (http://www.wampserver.com). See file build/exe/doliwamp.iss to know the doliwamp version currently setup. > Add path to ISCC into PATH windows var: Launch wine cmd, then regedit and add entry int HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment\PATH +> To build manually the .exe from Windows (running from makepack-dolibarr.pl script is however recommanded), + open file build/exe/doliwamp.iss and click on button "Compile". + The .exe file will be build into directory build. + + - To build a theme package, launch the script > perl makepack-dolibarrtheme.pl + + - To build a package for a module, launch the script > perl makepack-dolibarrmodule.pl + + - To build developper documentation, launch the script > perl dolibarr-doxygen-build.pl + Note: -The build directory and all its contents is absolutely not required to make -Dolibarr working. It is here only to build Dolibarr packages, and those -generated packages will not contains this "build" directory. +The build directory and all its contents is absolutely not required to make Dolibarr working. +It is here only to build Dolibarr packages, and those generated packages will not contains this "build" directory. You can find in "build", following sub-directories: @@ -59,6 +63,9 @@ To build Mac OS package (not ready yet). * doap: To build Doap descriptor to promote/describe Dolibarr releases. +* docker: +To deploy Dolibarr with docker. + * doxygen: Dir with config file to build doxygen documentation. @@ -66,12 +73,12 @@ Dir with config file to build doxygen documentation. To build exe package for Windows that distribute Dolibarr sources or to build the complete DoliWamp package. +* gource: +To build the video of history of git changes. + * launchpad: Doc file to explain how to use launchpad. -* live: -Doc file to explain how to create a demo live CD. - * obs: Doc file to explain how to push release onto OBS. @@ -90,5 +97,8 @@ To build Redhat, Opensuse or Mandriva package. * tgz: To build a tgz package. +* travis-ci: +Used by travis to make CI. + * zip: To build a zip package. diff --git a/build/docker/Dockerfile b/build/docker/Dockerfile index 9264eed5ef2..2be287c2db9 100644 --- a/build/docker/Dockerfile +++ b/build/docker/Dockerfile @@ -1,38 +1,50 @@ -FROM php:7.2-apache +FROM php:7.3-apache -ENV HOST_USER_ID 33 ENV PHP_INI_DATE_TIMEZONE 'UTC' +ENV PHP_INI_MEMORY_LIMIT 256M -RUN apt-get update && apt-get install -y libpng16-16 libpng-dev libjpeg62-turbo libjpeg62-turbo-dev libldap2-dev zlib1g-dev libicu-dev g++\ - && rm -rf /var/lib/apt/lists/* \ - && docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \ - && docker-php-ext-install gd \ - && docker-php-ext-install zip \ - && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \ - && docker-php-ext-install ldap \ - && docker-php-ext-install mysqli \ - && docker-php-ext-install calendar \ - && docker-php-ext-configure intl \ - && docker-php-ext-install intl \ - && apt-get autoremove --purge -y libpng-dev libjpeg62-turbo-dev libldap2-dev zlib1g-dev libicu-dev g++ +RUN apt-get update -y \ + && apt-get install -y --no-install-recommends \ + libfreetype6-dev \ + libjpeg62-turbo-dev \ + libjpeg62-turbo \ + libpng-dev \ + libpng16-16 \ + libldap2-dev \ + libxml2-dev \ + libzip-dev \ + zlib1g-dev \ + libicu-dev \ + g++ \ + default-mysql-client \ + unzip \ + curl \ + apt-utils \ + && apt-get autoremove -y \ + && rm -rf /var/lib/apt/lists/* \ + && docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \ + && docker-php-ext-install -j$(nproc) calendar intl mysqli pdo_mysql gd soap zip \ + && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \ + && docker-php-ext-install -j$(nproc) ldap && \ + mv ${PHP_INI_DIR}/php.ini-development ${PHP_INI_DIR}/php.ini RUN mkdir /var/documents -RUN chown www-data /var/documents +RUN chown www-data:www-data /var/documents COPY docker-run.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/docker-run.sh RUN pecl install xdebug && docker-php-ext-enable xdebug -RUN echo 'zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20151012/xdebug.so"' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_autostart=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_enable=1' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.default_enable=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_host=docker.host' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_port=9000' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_connect_back=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.profiler_enable=0' >> /usr/local/etc/php/php.ini -RUN echo 'xdebug.remote_log="/tmp/xdebug.log"' >> /usr/local/etc/php/php.ini -RUN echo '172.17.0.1 docker.host' >> /etc/hosts +RUN echo 'zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20180731/xdebug.so"' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_autostart=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_enable=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.default_enable=1' >> ${PHP_INI_DIR}/php.ini +#RUN echo 'xdebug.remote_host=docker.host' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_port=9000' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_connect_back=1' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.profiler_enable=0' >> ${PHP_INI_DIR}/php.ini +RUN echo 'xdebug.remote_log="/tmp/xdebug.log"' >> ${PHP_INI_DIR}/php.ini +#RUN echo '172.17.0.1 docker.host' >> /etc/hosts EXPOSE 80 diff --git a/build/docker/README.md b/build/docker/README.md index 616cbd8fa78..2fd278a531f 100644 --- a/build/docker/README.md +++ b/build/docker/README.md @@ -1,6 +1,8 @@ # How to use it ? The docker-compose.yml file is used to build and run Dolibarr in the current workspace. +This docker image intended for developpement usage. +For production usage you should consider other contributor reference like https://hub.docker.com/r/tuxgasy/dolibarr Before build/run, define the variable HOST_USER_ID as following: @@ -26,3 +28,4 @@ The URL to go to PhpMyAdmin is (login/password is root/root) : Setup the database connection during the installation process, please use mariad b (name of the database container) as database host. +Setup documents folder, during the installation process, to /var/documents diff --git a/build/docker/docker-compose.yml b/build/docker/docker-compose.yml index cc839810e7f..efdc95d2858 100644 --- a/build/docker/docker-compose.yml +++ b/build/docker/docker-compose.yml @@ -1,32 +1,51 @@ -mariadb: - build: mariadb - environment: - MYSQL_ROOT_PASSWORD: root - MYSQL_DATABASE: dolibarr +version: '3' -phpmyadmin: - image: phpmyadmin/phpmyadmin - environment: - PMA_HOST: mariadb - links: - - mariadb - ports: - - "8080:80" +networks: + internal-pod: + internal: true + external-pod: + internal: false -web: - build: . - environment: - HOST_USER_ID: $HOST_USER_ID - volumes: - - ../../htdocs:/var/www/html - links: - - mariadb - - mail - ports: - - "80:80" +services: + mariadb: + image: mariadb:latest + environment: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: dolibarr + networks: + - internal-pod -mail: - image: maildev/maildev - ports: - - "8081:80" - - "25:25" \ No newline at end of file + phpmyadmin: + image: phpmyadmin/phpmyadmin + environment: + PMA_HOST: mariadb + depends_on: + - mariadb + ports: + - "8080:80" + networks: + - internal-pod + - external-pod + + web: + build: . + environment: + HOST_USER_ID: $HOST_USER_ID + volumes: + - ../../htdocs:/var/www/html/ + - ../../documents:/var/documents + ports: + - "80:80" + - "9000:9000" + depends_on: + - mariadb + - mail + networks: + - internal-pod + - external-pod + + mail: + image: maildev/maildev + ports: + - "8081:80" + - "25:25" diff --git a/build/docker/docker-run.sh b/build/docker/docker-run.sh index df7272c317d..e57d9adfad0 100644 --- a/build/docker/docker-run.sh +++ b/build/docker/docker-run.sh @@ -1,15 +1,21 @@ #!/bin/bash -usermod -u $HOST_USER_ID www-data -groupmod -g $HOST_USER_ID www-data +usermod -u ${HOST_USER_ID} www-data +groupmod -g ${HOST_USER_ID} www-data chgrp -hR www-data /var/www/html chmod g+rwx /var/www/html/conf +if [ ! -d /var/documents ]; then + echo "[docker-run] => create volume directory /var/documents ..." + mkdir -p /var/documents +fi +echo "[docker-run] => Set Permission to www-data for /var/documents" +chown -R www-data:www-data /var/documents + if [ ! -f /usr/local/etc/php/php.ini ]; then cat < /usr/local/etc/php/php.ini date.timezone = $PHP_INI_DATE_TIMEZONE -display_errors = On EOF fi diff --git a/build/exe/doliwamp/README.md b/build/exe/doliwamp/README.md index 87d3371f9bb..be8cf1f3ac5 100644 --- a/build/exe/doliwamp/README.md +++ b/build/exe/doliwamp/README.md @@ -5,6 +5,7 @@ It's a dedicated Dolibarr version for Windows newbies with no technical knowledg This directory contains files used by *makepack-dolibarr.pl* script to build the all-in-on .EXE package DoliWamp, ready to be distributed (for Windows). +The build of .exe files need to have some windows executable files already installed (Apache, MariaDb). The package to install to get this files are defined into the file *doliwamp.iss* (searhc line starting with "; Value OK:") If you have technical knowledge in web administration and plan to share your server instance (Apache, Mysql or PHP) with other projects than Dolibarr or want to use Dolibarr other components (PostgreSQL), you should not use this assistant and make a manual installation of Dolibarr on your existing server by downloading the standard package (.tgz or .zip file). diff --git a/build/exe/doliwamp/doliwamp.iss b/build/exe/doliwamp/doliwamp.iss index 4a6dca3af01..ed8e07d7468 100644 --- a/build/exe/doliwamp/doliwamp.iss +++ b/build/exe/doliwamp/doliwamp.iss @@ -104,8 +104,8 @@ Source: "build\exe\doliwamp\UsedPort.exe"; DestDir: "{app}\"; Flags: ignoreversi ; Value OK: apache 2.2.6, php 5.2.5 (5.2.11, 5.3.0 and 5.3.1 fails if php_exif, php_pgsql, php_zip is on), mysql 5.0.45 ; Value OK: apache 2.2.11, php 5.3.0 (if no php_exif, php_pgsql, php_zip), mysql 5.0.45 ; Value OK: apache 2.4.9, php 5.5.12, mysql 5.0.45 instead of 5.6.17 (wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe) -; Value To test: apache 2.4.41, php 7.3.12, mariadb10.4.10 (wampserver3.2.0_x64.exe) -Source: "C:\Program Files\Wamp\apps\phpmyadmin4.1.14\*.*"; DestDir: "{app}\apps\phpmyadmin4.1.14"; Flags: ignoreversion recursesubdirs; Excludes: "config.inc.php,wampserver.conf,*.log,*_log,darkblue_orange" +; Value OK: apache 2.4.41, php 7.3.12, mariadb10.4.10 (wampserver3.2.0_x64.exe) +Source: "C:\wamp64\apps\phpmyadmin4.9.2\*.*"; DestDir: "{app}\apps\phpmyadmin4.9.2"; Flags: ignoreversion recursesubdirs; Excludes: "config.inc.php,wampserver.conf,*.log,*_log,darkblue_orange" ;Source: "C:\Program Files\Wamp\bin\apache\apache2.4.9\*.*"; DestDir: "{app}\bin\apache\apache2.4.9"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,httpd.conf,wampserver.conf,*.log,*_log" Source: "C:\wamp64\bin\apache\apache2.4.41\*.*"; DestDir: "{app}\bin\apache\apache2.4.41"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,httpd.conf,wampserver.conf,*.log,*_log" ;Source: "C:\Program Files\Wamp\bin\php\php5.5.12\*.*"; DestDir: "{app}\bin\php\php5.5.12"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,phpForApache.ini,wampserver.conf,*.log,*_log" diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 24b32dcff91..85212d9c5ba 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -620,6 +620,9 @@ if ($nboftargetok) { $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/autoload.php`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/theme/common/octicons/LICENSE`; } diff --git a/build/pdf/README.txt b/build/pdf/README.txt index 2335ff4b7f7..7a5424ca3d5 100644 --- a/build/pdf/README.txt +++ b/build/pdf/README.txt @@ -1,9 +1,10 @@ -To make htmldoc working from wiki.dolibarr.org, them must be modified to have +To make htmldoc working from wiki.dolibarr.org, the wiki must be modified to have -$_SERVER["HTTP_USER_AGENT"] is "HTMLDOC/x.y.z" -$_COOKIE["htmldoc"] may also be defined if set on command line. - -To disable part, add -class="htmldoc-ignore" with css +To disable part of content, add: +class="htmldoc-ignore" +with css .htmldoc-ignore { display: none; } +Note: +$_SERVER["HTTP_USER_AGENT"] is "HTMLDOC/x.y.z" +$_COOKIE["htmldoc"] may also be defined if set on command line. diff --git a/build/sitemap/urllist-wiki.txt b/build/sitemap/urllist-wiki.txt index ae13bb96d87..2a70e61f146 100644 --- a/build/sitemap/urllist-wiki.txt +++ b/build/sitemap/urllist-wiki.txt @@ -1 +1 @@ -http://wiki.dolibarr.org/ +https://wiki.dolibarr.org/ diff --git a/composer.json b/composer.json index d26bbb05ad9..9fede994525 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "vendor-dir" : "htdocs/includes" }, "require" : { - "php" : ">=5.5.0", + "php" : ">=5.6.0", "ext-curl" : "*", "ckeditor/ckeditor" : "4.12.1", "mike42/escpos-php" : "2.2", @@ -33,11 +33,13 @@ "restler/framework" : "3.0.0-RC6", "tecnickcom/tcpdf" : "6.3.2", "nnnick/chartjs" : "^2.9", - "stripe/stripe-php" : "6.43.1" + "stripe/stripe-php" : "6.43.1", + "maximebf/debugbar" : "1.15.1", + "symfony/var-dumper": "3" }, "require-dev" : { - "jakub-onderka/php-parallel-lint" : "^0", - "jakub-onderka/php-console-highlighter" : "^0", + "php-parallel-lint/php-parallel-lint" : "^0", + "php-parallel-lint/php-console-highlighter" : "^0", "phpunit/phpunit" : "^4", "squizlabs/php_codesniffer" : "^2", "phpunit/phpunit-selenium" : "^2" diff --git a/composer.lock b/composer.lock index 09c71674512..5afe0ca34f2 100644 --- a/composer.lock +++ b/composer.lock @@ -1,10 +1,10 @@ { "_readme": [ "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "17e906996157e8a94564f686a6096dc5", + "content-hash": "1dbd2d05cc0836acfca5988f29005cf2", "packages": [ { "name": "ckeditor/ckeditor", @@ -47,6 +47,67 @@ ], "time": "2019-06-28T10:41:23+00:00" }, + { + "name": "maximebf/debugbar", + "version": "v1.15.1", + "source": { + "type": "git", + "url": "https://github.com/maximebf/php-debugbar.git", + "reference": "6c4277f6117e4864966c9cb58fb835cee8c74a1e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maximebf/php-debugbar/zipball/6c4277f6117e4864966c9cb58fb835cee8c74a1e", + "reference": "6c4277f6117e4864966c9cb58fb835cee8c74a1e", + "shasum": "" + }, + "require": { + "php": ">=5.6", + "psr/log": "^1.0", + "symfony/var-dumper": "^2.6|^3|^4" + }, + "require-dev": { + "phpunit/phpunit": "^5" + }, + "suggest": { + "kriswallsmith/assetic": "The best way to manage assets", + "monolog/monolog": "Log using Monolog", + "predis/predis": "Redis storage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.15-dev" + } + }, + "autoload": { + "psr-4": { + "DebugBar\\": "src/DebugBar/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Maxime Bouroumeau-Fuseau", + "email": "maxime.bouroumeau@gmail.com", + "homepage": "http://maximebf.com" + }, + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "description": "Debug bar in the browser for php application", + "homepage": "https://github.com/maximebf/php-debugbar", + "keywords": [ + "debug", + "debugbar" + ], + "time": "2019-09-24T14:55:42+00:00" + }, { "name": "mike42/escpos-php", "version": "v2.2", @@ -253,6 +314,53 @@ "abandoned": "phpoffice/phpspreadsheet", "time": "2015-05-01T07:00:55+00:00" }, + { + "name": "psr/log", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2020-03-23T09:12:05+00:00" + }, { "name": "restler/framework", "version": "3.0.0-RC6", @@ -260,12 +368,12 @@ "source": { "type": "git", "url": "https://github.com/Luracast/Restler-Framework.git", - "reference": "0f6b0f26152f83e43a2a86820206c455095fb2b0" + "reference": "d52e61600d153bca60a287c35141c5c01863127b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Luracast/Restler-Framework/zipball/0f6b0f26152f83e43a2a86820206c455095fb2b0", - "reference": "0f6b0f26152f83e43a2a86820206c455095fb2b0", + "url": "https://api.github.com/repos/Luracast/Restler-Framework/zipball/d52e61600d153bca60a287c35141c5c01863127b", + "reference": "d52e61600d153bca60a287c35141c5c01863127b", "shasum": "" }, "require": { @@ -312,7 +420,7 @@ "rest", "server" ], - "time": "2019-05-12T15:15:11+00:00" + "time": "2020-02-13T16:05:12+00:00" }, { "name": "stripe/stripe-php", @@ -370,6 +478,146 @@ ], "time": "2019-08-29T16:56:12+00:00" }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.18.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/a6977d63bf9a0ad4c65cd352709e230876f9904a", + "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-07-14T12:35:20+00:00" + }, + { + "name": "symfony/var-dumper", + "version": "v3.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "737e07704cca83f9dd0af926d45ce27eedc25657" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/737e07704cca83f9dd0af926d45ce27eedc25657", + "reference": "737e07704cca83f9dd0af926d45ce27eedc25657", + "shasum": "" + }, + "require": { + "php": ">=5.5.9", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "twig/twig": "~1.20|~2.0" + }, + "suggest": { + "ext-symfony_debug": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony mechanism for exploring and dumping PHP variables", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "time": "2015-11-18T13:48:51+00:00" + }, { "name": "tecnickcom/tcpdf", "version": "6.3.2", @@ -489,16 +737,16 @@ "time": "2015-06-14T21:17:01+00:00" }, { - "name": "jakub-onderka/php-console-color", + "name": "php-parallel-lint/php-console-color", "version": "v0.2", "source": { "type": "git", - "url": "https://github.com/JakubOnderka/PHP-Console-Color.git", + "url": "https://github.com/php-parallel-lint/PHP-Console-Color.git", "reference": "d5deaecff52a0d61ccb613bb3804088da0307191" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/JakubOnderka/PHP-Console-Color/zipball/d5deaecff52a0d61ccb613bb3804088da0307191", + "url": "https://api.github.com/repos/php-parallel-lint/PHP-Console-Color/zipball/d5deaecff52a0d61ccb613bb3804088da0307191", "reference": "d5deaecff52a0d61ccb613bb3804088da0307191", "shasum": "" }, @@ -531,28 +779,31 @@ "time": "2018-09-29T17:23:10+00:00" }, { - "name": "jakub-onderka/php-console-highlighter", - "version": "v0.4", + "name": "php-parallel-lint/php-console-highlighter", + "version": "v0.5", "source": { "type": "git", - "url": "https://github.com/JakubOnderka/PHP-Console-Highlighter.git", - "reference": "9f7a229a69d52506914b4bc61bfdb199d90c5547" + "url": "https://github.com/php-parallel-lint/PHP-Console-Highlighter.git", + "reference": "21bf002f077b177f056d8cb455c5ed573adfdbb8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/JakubOnderka/PHP-Console-Highlighter/zipball/9f7a229a69d52506914b4bc61bfdb199d90c5547", - "reference": "9f7a229a69d52506914b4bc61bfdb199d90c5547", + "url": "https://api.github.com/repos/php-parallel-lint/PHP-Console-Highlighter/zipball/21bf002f077b177f056d8cb455c5ed573adfdbb8", + "reference": "21bf002f077b177f056d8cb455c5ed573adfdbb8", "shasum": "" }, "require": { "ext-tokenizer": "*", - "jakub-onderka/php-console-color": "~0.2", - "php": ">=5.4.0" + "php": ">=5.4.0", + "php-parallel-lint/php-console-color": "~0.2" + }, + "replace": { + "jakub-onderka/php-console-highlighter": "*" }, "require-dev": { - "jakub-onderka/php-code-style": "~1.0", - "jakub-onderka/php-parallel-lint": "~1.0", - "jakub-onderka/php-var-dump-check": "~0.1", + "php-parallel-lint/php-code-style": "~1.0", + "php-parallel-lint/php-parallel-lint": "~1.0", + "php-parallel-lint/php-var-dump-check": "~0.1", "phpunit/phpunit": "~4.0", "squizlabs/php_codesniffer": "~1.5" }, @@ -574,19 +825,19 @@ } ], "description": "Highlight PHP code in terminal", - "time": "2018-09-29T18:48:56+00:00" + "time": "2020-05-13T07:37:49+00:00" }, { - "name": "jakub-onderka/php-parallel-lint", + "name": "php-parallel-lint/php-parallel-lint", "version": "v0.9.2", "source": { "type": "git", - "url": "https://github.com/JakubOnderka/PHP-Parallel-Lint.git", + "url": "https://github.com/php-parallel-lint/PHP-Parallel-Lint.git", "reference": "2ead2e4043ab125bee9554f356e0a86742c2d4fa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/JakubOnderka/PHP-Parallel-Lint/zipball/2ead2e4043ab125bee9554f356e0a86742c2d4fa", + "url": "https://api.github.com/repos/php-parallel-lint/PHP-Parallel-Lint/zipball/2ead2e4043ab125bee9554f356e0a86742c2d4fa", "reference": "2ead2e4043ab125bee9554f356e0a86742c2d4fa", "shasum": "" }, @@ -1082,6 +1333,7 @@ "keywords": [ "tokenizer" ], + "abandoned": true, "time": "2017-12-04T08:55:13+00:00" }, { @@ -1785,6 +2037,159 @@ ], "time": "2019-08-06T08:03:45+00:00" }, + { + "name": "symfony/polyfill-php72", + "version": "v1.18.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "639447d008615574653fb3bc60d1986d7172eaae" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/639447d008615574653fb3bc60d1986d7172eaae", + "reference": "639447d008615574653fb3bc60d1986d7172eaae", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-07-14T12:35:20+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.18.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/d87d5766cbf48d72388a9f6b85f280c8ad51f981", + "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981", + "shasum": "" + }, + "require": { + "php": ">=7.0.8" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-07-14T12:35:20+00:00" + }, { "name": "symfony/yaml", "version": "v3.4.32", @@ -1903,8 +2308,9 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=5.5.0", + "php": ">=5.6.0", "ext-curl": "*" }, - "platform-dev": [] + "platform-dev": [], + "plugin-api-version": "1.1.0" } diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 3c7ff061e49..5f09d9536be 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -28,19 +28,6 @@ With -DEBUGBAR: ---------- - -Move - this.options = { - bodyMarginBottom: true, - bodyMarginBottomHeight: parseInt($('body').css('margin-bottom')), - }; -few line lower in the - initialize: function() { - - - ESCPOS: ------- Replace diff --git a/dev/examples/mail/source_email_ticket_1_to_create.txt b/dev/examples/mail/source_email_ticket_1_to_create.txt new file mode 100644 index 00000000000..94d4cb620b9 --- /dev/null +++ b/dev/examples/mail/source_email_ticket_1_to_create.txt @@ -0,0 +1,89 @@ +Delivered-To: testldrdev@gmail.com +Received: by 2002:a2e:9b9a:0:0:0:0:0 with SMTP id z26csp1425223lji; + Thu, 20 Aug 2020 08:29:02 -0700 (PDT) +X-Received: by 2002:a05:620a:1292:: with SMTP id w18mr2938234qki.158.1597937342304; + Thu, 20 Aug 2020 08:29:02 -0700 (PDT) +ARC-Seal: i=1; a=rsa-sha256; t=1597937342; cv=none; + d=google.com; s=arc-20160816; + b=FhT/+rJ/zNYgVQ5Nt/rLZJycGd/Ntkhm6LwI16YUfmEmxeGrP/cXXQULrqQ1LhBr9B + oRKweltTdnpyA14gm0kzbs1vUkf5HxLUuGk8IqqJWAPMUZoN8oUPkzq2BuKNQGxPiE+y + Hsg/fnYp8WzcAlZOLsEP2kcFIdA95Dyy5LkM8HgphI1jSS1d6gkx6nDGIMIpDD9D+w4X + ISxRUXp5JlDwFCUMOPoAvHIBUdJ3jpLsjesbMEnU4ssFqhxU21pBq+Fc+csSPeY5DL0M + HR1o+ChEAXIdDOrDqa0ohHfqR216juGCzH8YuEQ88LT0Qbst9IkOYWiAQv4TIh7vHtvQ + TMvA== +ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; + h=to:subject:message-id:date:from:mime-version:dkim-signature; + bh=sojOjnIKAXmsZ9zvMk5MGvY3qyOaFgnpRe6YPMYutOI=; + b=CRlrRPfoGkfmz6iXKy4HdxKQ4SeJTiIxjC2jNkgQPSnIDFJgDkJcwASJVpcjTmlVmH + Z9WnHKVUPRIHGDEoMRlx6eUx9QfelWqPYu3BBQGFry9sgth0BR/1s6tmQ+P+bAj23ryo + aL3UkF6KCSx4GhEk3MfHA5Ex81YDFHvHL3BZ2kb3XCVSlPiBq2szw1ETmRAsDdS5Gbu+ + ZlzBbl4pRtUWgi1fB5H4Wcv7e90F4Et1SBP8IKSCa23qu2nV9xefgjfMw2ndxCj1zgCL + c3l7Ul6pw32nqf6+vxfZTstwIwgu6dXZXCHDqJqesI2g8RGxeba+LfKZEDpBuSeINS9r + GMvw== +ARC-Authentication-Results: i=1; mx.google.com; + dkim=pass header.i=@destailleur.fr header.s=google header.b=IPMz90Yj; + spf=pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) smtp.mailfrom=contact@destailleur.fr; + dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=destailleur.fr +Return-Path: +Received: from mail-sor-f41.google.com (mail-sor-f41.google.com. [209.85.220.41]) + by mx.google.com with SMTPS id w14sor2138230qtb.9.2020.08.20.08.29.00 + for + (Google Transport Security); + Thu, 20 Aug 2020 08:29:01 -0700 (PDT) +Received-SPF: pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) client-ip=209.85.220.41; +Authentication-Results: mx.google.com; + dkim=pass header.i=@destailleur.fr header.s=google header.b=IPMz90Yj; + spf=pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) smtp.mailfrom=contact@destailleur.fr; + dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=destailleur.fr +DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; + d=destailleur.fr; s=google; + h=mime-version:from:date:message-id:subject:to; + bh=sojOjnIKAXmsZ9zvMk5MGvY3qyOaFgnpRe6YPMYutOI=; + b=IPMz90Yjw1Mf57/rYWUYGtpc+IazEWcy6/bqxf1j0h6rxDH/wjhxsCWzfARgqqlfVj + ACg4IbPpZZlKFIYDSCbfMlWF65rbKfNre56HldfQgy0Tq3LC434zHz2ZZMOVCM52w3J9 + VGBpASUlSL1o+YRmzOpRtHVu7I9aNwGxHuA070Yka8XLV76vV3P0vdL8PcoHq0jUUEoi + +dCZ9NCPuAFtGK2IavNoM2qQrLdfYIi+RwgWBtqjTwzyvDEJR+p5fIPK142ynMbHgWYO + RVtMqAgxjvL4sfyKZ5KuzKXkQNM3zyzMinWK89scBl+QLFCcWA4Qqc0dJjqLCBhh8lmq + n67g== +X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; + d=1e100.net; s=20161025; + h=x-gm-message-state:mime-version:from:date:message-id:subject:to; + bh=sojOjnIKAXmsZ9zvMk5MGvY3qyOaFgnpRe6YPMYutOI=; + b=H0GsrFAi9JmRTKQ2budtDeLBqCaTisHKYCVVziyxmv+/tIcrSZBA4tdKwm+wR80r50 + zMJXmyVS2DMDWfnIlOv39wcwQjYN3WK1aRJfV0bVuEWrQuzt5MMWbskf6xbzo201nhr9 + ZlqATsEV7v1u5EHmfYwRhR8+AOmENdnm0g9RXPJVrFS58WNEJUSotS5Y5rZPjnT943y0 + 62Kf4Bd6uWvXhPFXWQoZLtWrPpkbcYPWIBmpftKhD0PD9c6rKaVduV0WhbigYsDoxb3F + iIafGPOyq91hiHR2gTLHiMmTDm+IDQ4n6gSkS7HKpZlLQhHoBMnpqJZYoxMJTxdpAbSy + mY+A== +X-Gm-Message-State: AOAM5325RcN4/ThWbYCO3vWRMFFBrfzJUHC1bd1Z9VB3/2Q3RuF9lmIJ +SjshEErhK68Of2pHDZQ3aPU4rzDfV8ozbvRsgChdfZg8aA= +X-Google-Smtp-Source: ABdhPJxUOUdurKEQfLldtiQGRkgC/h8gKQG1zhS+8k93p6N1SsOn517+GeRyT3E+/Uw536pmReO29la3EIAS6VT33SE= +X-Received: by 2002:aed:3e8e:: with SMTP id n14mr3191190qtf.67.1597937340509; Thu, 20 Aug 2020 08:29:00 -0700 (PDT) +MIME-Version: 1.0 +From: John Tester +Date: Thu, 20 Aug 2020 17:28:34 +0200 +Message-ID: +Subject: Support besoin +To: testldrdev@gmail.com +Content-Type: multipart/alternative; boundary="0000000000008e099705ad50c772" + +--0000000000008e099705ad50c772 +Content-Type: text/plain; charset="UTF-8" + +adfsdfsdfds + +-- +Laurent. +------------------------------------------------------------------------------------ +Twitter: https://www.twitter.com/eldy10 + +--0000000000008e099705ad50c772 +Content-Type: text/html; charset="UTF-8" +Content-Transfer-Encoding: quoted-printable + +
adfsdfsdfds

--
Laur= +ent.
-------------------------------------------------------------------= +-----------------
Twitter: https://www.twitter.com/eldy10
+ +--0000000000008e099705ad50c772-- diff --git a/dev/examples/mail/source_email_ticket_2_answer_from_ticket.txt b/dev/examples/mail/source_email_ticket_2_answer_from_ticket.txt new file mode 100644 index 00000000000..350b9a93cad --- /dev/null +++ b/dev/examples/mail/source_email_ticket_2_answer_from_ticket.txt @@ -0,0 +1,57 @@ +Return-Path: +Received: from smtp.gmail.com ([2a01:e0a:7e:4ae0:329c:23ff:feb8:dc8d]) + by smtp.gmail.com with ESMTPSA id 32sm5811196wrh.18.2020.08.20.09.31.37 + for + (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); + Thu, 20 Aug 2020 09:31:37 -0700 (PDT) +From: testldrdev@gmail.com +X-Google-Original-From: +To: customer@customercompany.fr +Subject: [MyBigCompany - Ticket #TS2008-0040] Nouveau message +Date: Thu, 20 Aug 2020 18:31:37 +0200 +Message-ID: <1597941097.SMTPs-dolibarr-tic58@83b5bc91f83a56e458db71e0adac2b62> +References: <1597941097.SMTPs-dolibarr-tic58@83b5bc91f83a56e458db71e0adac2b62> +X-Dolibarr-TRACKID: tic58@83b5bc91f83a56e458db71e0adac2b62 +X-RemoteAddr: 127.0.0.1 +X-Mailer: Dolibarr version 13.0.0-alpha (using SMTPs Mailer) +X-Dolibarr-Option: MAIN_MAIL_USE_MULTI_PART +Mime-Version: 1.0 +Content-Type: multipart/mixed; boundary="multipart_x.1597941097.x_boundary" +Content-Transfer-Encoding: 8bit + +--multipart_x.1597941097.x_boundary +Content-Type: multipart/alternative; boundary="mul_872cdd6a64216735955664484832b075" + +--mul_872cdd6a64216735955664484832b075 +Content-Type: text/plain; charset=UTF-8 + +Bonjour + + +Une nouvelle réponse a été ajoutée à un ticket que vous suivez. Voici +le message :PredefinedMailContentTicket_send + + +Vous pouvez voir la progression du ticket en cliquant sur le lien +ci-dessus. : fr5uw2yospypn2rz + Cordialement, + +-- +--mul_872cdd6a64216735955664484832b075 +Content-Type: text/html; charset=UTF-8 + +Bonjour
+ +
+Une nouvelle réponse a été ajoutée à un ticket que vous suivez. Voici +le message :PredefinedMailContentTicket_send
+
+
+Vous pouvez voir la progression du ticket en cliquant sur le lien +ci-dessus. : fr5uw2yospypn2rz
+
Cordialement,
+
+-- +--mul_872cdd6a64216735955664484832b075-- +--multipart_x.1597941097.x_boundary-- diff --git a/dev/examples/mail/source_email_ticket_3_answer_from_mailer.txt b/dev/examples/mail/source_email_ticket_3_answer_from_mailer.txt new file mode 100644 index 00000000000..6c2ac1bb2af --- /dev/null +++ b/dev/examples/mail/source_email_ticket_3_answer_from_mailer.txt @@ -0,0 +1,48 @@ +MIME-Version: 1.0 +Date: Thu, 20 Aug 2020 18:34:01 +0200 +References: +In-Reply-To: +Message-ID: +Subject: Re: Support besoin +From: John Tester +To: John Tester +Content-Type: multipart/alternative; boundary="0000000000001620dd05ad51b075" + +--0000000000001620dd05ad51b075 +Content-Type: text/plain; charset="UTF-8" +Content-Transfer-Encoding: quoted-printable + +Merci pour votre question. +Voici la rep. + +Le jeu. 20 ao=C3=BBt 2020 =C3=A0 17:29, John Tester +a =C3=A9crit : + +> adfsdfsdfds +> +> -- +> Laurent. +> +> -------------------------------------------------------------------------= +----------- +> Twitter: https://www.twitter.com/eldy10 +> + +--0000000000001620dd05ad51b075 +Content-Type: text/html; charset="UTF-8" +Content-Transfer-Encoding: quoted-printable + +
Merci pour votre question.
Voici la rep.
Le=C2=A0= +jeu. 20 ao=C3=BBt 2020 =C3=A0=C2=A017:29, John Tester <customer@customercompany.fr> a =C3=A9c= +rit=C2=A0:
adfsdfsdfds

--
Laurent.
----------------------------------------------------------= +--------------------------
Twitter: https://www.twitter.com/eldy10
+
+ +--0000000000001620dd05ad51b075-- diff --git a/dev/examples/mail/source_email_ticket_4_answer_of_answer_from_mailer.txt b/dev/examples/mail/source_email_ticket_4_answer_of_answer_from_mailer.txt new file mode 100644 index 00000000000..314e9cda20f --- /dev/null +++ b/dev/examples/mail/source_email_ticket_4_answer_of_answer_from_mailer.txt @@ -0,0 +1,134 @@ +Delivered-To: testldrdev@gmail.com +Received: by 2002:a2e:9b9a:0:0:0:0:0 with SMTP id z26csp1483607lji; + Thu, 20 Aug 2020 09:56:03 -0700 (PDT) +X-Received: by 2002:ac8:3868:: with SMTP id r37mr3301993qtb.95.1597942563252; + Thu, 20 Aug 2020 09:56:03 -0700 (PDT) +ARC-Seal: i=1; a=rsa-sha256; t=1597942563; cv=none; + d=google.com; s=arc-20160816; + b=skUGL+keim3FdNXfKGgQokCfj85gnhYhuLbMM61qY5W6ixSH9s8I6uoNh3gzVy89XM + NGbZiajjDiPMBryl87PhD+ACBjv8WoZAQiojAga0ELPPmVDnhrtWKANLbRrkUI3Xtfoj + b1o2iHP2Q12Vqs6xiAy86yxURlIKGM3tw91WryWiIPiAL7bRZPn49N3XbO2ULE0QKTBq + BI5YnOxt9NfTj0xhKaLLIJ9M1qa4e1QyOHl56WuEv3Gx6uHDAQDYz+C5G0VgdjBvwRzH + pJaiAulc1uW/V9TcRMwvwIWtI7eWygvU2PiuI/c05G1KVKibAubHE55IjOJCn2O2UaH4 + WMNQ== +ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; + h=to:subject:message-id:date:from:in-reply-to:references:mime-version + :dkim-signature; + bh=j6+rsx5MBsg1/s7LIIfByV7u0jGK09n72bnK4XcN6ZQ=; + b=Ps5kk+tBGQzMP6ugDCwKf4hzn8fn3DU4AFz1dJvkHdDestLZWN99Qtr6iNMdslsHJm + ov378c+8oCfcV7shyBYjlAFfikFi7o4RM/evh3yqqjAnhyVfcYH7c9cexVvDo/AXUAZ7 + N7Mh7EOvyDXXsaHK2l89XiAxZx/hZh/O+/HR2EoVEGre1eYRYwI/aEfPN8d4/fL2VtCD + 0wzAwnUrINuXmcaUDT30Twjk9kwGjjTsM6Z531vKM6L3y48a7f3GTE7V+vo2QxHdUT54 + fQVue9OO7b4VKTEj/x/dmNr+92sHRAMMS7dj/VXMmzM+WttUCAPNxZ27/bvt4bBc5oBp + QPEA== +ARC-Authentication-Results: i=1; mx.google.com; + dkim=pass header.i=@destailleur.fr header.s=google header.b=SEYSmxbT; + spf=pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) smtp.mailfrom=contact@destailleur.fr; + dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=destailleur.fr +Return-Path: +Received: from mail-sor-f41.google.com (mail-sor-f41.google.com. [209.85.220.41]) + by mx.google.com with SMTPS id q3sor2285165qtn.34.2020.08.20.09.56.02 + for + (Google Transport Security); + Thu, 20 Aug 2020 09:56:03 -0700 (PDT) +Received-SPF: pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) client-ip=209.85.220.41; +Authentication-Results: mx.google.com; + dkim=pass header.i=@destailleur.fr header.s=google header.b=SEYSmxbT; + spf=pass (google.com: domain of contact@destailleur.fr designates 209.85.220.41 as permitted sender) smtp.mailfrom=contact@destailleur.fr; + dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=destailleur.fr +DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; + d=destailleur.fr; s=google; + h=mime-version:references:in-reply-to:from:date:message-id:subject:to; + bh=j6+rsx5MBsg1/s7LIIfByV7u0jGK09n72bnK4XcN6ZQ=; + b=SEYSmxbTKCuc1baQZzjIJwm7WXvgjt/nEGhMLqWxQCU3beM3qhH8wYlSeMyB8Z/9pi + tszZFZhZ3cjnIbbJnjzsMYJgBnYbkf6hz14+BsFwyPU030EkDjJy2i3DSXzYK7A+GbBn + G9I9foG/4+pcx0LnFsjchGsRhLFkTKJIsP2SVfOx0wlim3WHMIqIXvKsxY05PoPyf8Tp + IwQi7iNl/+nTyjNHl2DQh+ty3CRTmUw9uEbY+jRRvIg5i/7cfREekK98d7qi/5HQycr6 + aptRDdCVHXpe47q+c7OPiMEEQWs+mFJhBqPXIlU54fwFApEEnLn/jwGbrPsrPYJaswgI + vd/g== +X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; + d=1e100.net; s=20161025; + h=x-gm-message-state:mime-version:references:in-reply-to:from:date + :message-id:subject:to; + bh=j6+rsx5MBsg1/s7LIIfByV7u0jGK09n72bnK4XcN6ZQ=; + b=M6a4k1gKc4e7TwKncuNPy0b3KxutR1FLFJGWxd4NyW84b7f3LfIR94IeInLQIWmY8C + Ddus0upZJI4+NN9XBGvXCdsiiYlwFGBJRWwjv82XFKVAKL5DD94RJNQZJUiE39hgJ2aa + 6V9gasiP+nUAX4ZV9bZmw21CgKEZrZVXh5unmW2ABrfcx8lHjp/DUw5XEkym1J92Wo1l + g0H3XrC2FL+aQuj+WpCynMNkY9ljw71oqyv3SP9pjnVNHArAdZiPMHkNxiuPdq7q41fg + eIbdRCQXYZL5O48QsjDdiXwaQzx+NcYtrKAH0RIVD1lG6zc9pxqDJsbGxP9VLs8jGDTT + mSdQ== +X-Gm-Message-State: AOAM532LuATWDKbo1HImMWshHVqb0kC0isehf3owfYUKq5J68o3juKbm kCgUMt25A2C7QoNMDXcjfJyteBNQD7ZhSh3yeYTGoLSvsD4= +X-Google-Smtp-Source: ABdhPJyQYCpCHSwA87x030i8YChySZqcNXxT1qVlZyEA+XM6DTyPZusa8gtbDUVcMyx7Jma/7toh+4EEE2bWg0bG+2E= +X-Received: by 2002:aed:3e8e:: with SMTP id n14mr3547383qtf.67.1597942562373; Thu, 20 Aug 2020 09:56:02 -0700 (PDT) +MIME-Version: 1.0 +References: +In-Reply-To: +From: John Tester +Date: Thu, 20 Aug 2020 18:55:36 +0200 +Message-ID: +Subject: Re: Support besoin +To: John Tester +Content-Type: multipart/alternative; boundary="000000000000cd54be05ad51fe67" + +--000000000000cd54be05ad51fe67 +Content-Type: text/plain; charset="UTF-8" +Content-Transfer-Encoding: quoted-printable + +Merci + +Le jeu. 20 ao=C3=BBt 2020 =C3=A0 18:34, John Tester a +=C3=A9crit : + +> Merci pour votre question. +> Voici la rep. +> +> Le jeu. 20 ao=C3=BBt 2020 =C3=A0 17:29, John Tester +> a =C3=A9crit : +> +>> adfsdfsdfds +>> +>> -- +>> Laurent. +>> +>> ------------------------------------------------------------------------= +------------ +>> Twitter: https://www.twitter.com/eldy10 +>> +> + +--=20 +Laurent. +---------------------------------------------------------------------------= +--------- +Twitter: https://www.twitter.com/eldy10 + +--000000000000cd54be05ad51fe67 +Content-Type: text/html; charset="UTF-8" +Content-Transfer-Encoding: quoted-printable + +
Merci

Le=C2=A0jeu. 20 ao=C3=BBt 2020 =C3=A0=C2=A018:34, Lau= +rent Destailleur <testldrdev@gma= +il.com> a =C3=A9crit=C2=A0:
Merci pour votre question.
Voici la= + rep.

Le=C2=A0jeu. 20 ao=C3=BBt 2020 =C3=A0=C2=A017:29, Laurent Destai= +lleur <laure= +nt@destailleur.fr> a =C3=A9crit=C2=A0:
adfsdfsdfds

--
Laurent.
-----------------------= +-------------------------------------------------------------
Twitter: <= +a href=3D"https://www.twitter.com/eldy10" target=3D"_blank">https://www.twi= +tter.com/eldy10
+
+


--
Laurent.
------------------------------------= +------------------------------------------------
Twitter: https://www.twitter.com/eldy= +10
+ +--000000000000cd54be05ad51fe67-- \ No newline at end of file diff --git a/dev/initdata/purge-data.php b/dev/initdata/purge-data.php index 183140af202..e6a67aa73c8 100755 --- a/dev/initdata/purge-data.php +++ b/dev/initdata/purge-data.php @@ -26,7 +26,7 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); -$path=dirname(__FILE__).'/'; +$path=__DIR__.'/'; // Test si mode batch if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdemo/initdemo.sh b/dev/initdemo/initdemo.sh index 7fd9eb551d4..1b32161b44b 100755 --- a/dev/initdemo/initdemo.sh +++ b/dev/initdemo/initdemo.sh @@ -69,6 +69,7 @@ then 255) exit;; esac + rm $fichtemp # ----------------------------- database name DIALOG=${DIALOG=dialog} @@ -86,6 +87,7 @@ then 255) exit;; esac + rm $fichtemp # ---------------------------- database port DIALOG=${DIALOG=dialog} @@ -104,6 +106,7 @@ then 255) exit;; esac + rm $fichtemp # ---------------------------- compte admin mysql DIALOG=${DIALOG=dialog} @@ -122,6 +125,7 @@ then 255) exit;; esac + rm $fichtemp # ---------------------------- mot de passe admin mysql DIALOG=${DIALOG=dialog} @@ -140,6 +144,7 @@ then 255) exit;; esac + rm $fichtemp export documentdir=`cat $mydir/../../htdocs/conf/conf.php | grep '^\$dolibarr_main_data_root' | sed -e 's/$dolibarr_main_data_root=//' | sed -e 's/;//' | sed -e "s/'//g" | sed -e 's/"//g' ` diff --git a/dev/initdemo/initdemopassword.sh b/dev/initdemo/initdemopassword.sh new file mode 100755 index 00000000000..d5aa9c1ef0e --- /dev/null +++ b/dev/initdemo/initdemopassword.sh @@ -0,0 +1,166 @@ +#!/bin/sh +#------------------------------------------------------ +# Script to reinit admin password. +# Note: "dialog" tool need to be available if no parameter provided. +# +# Laurent Destailleur - eldy@users.sourceforge.net +#------------------------------------------------------ +# Usage: initdemopassword.sh confirm +# usage: initdemopassword.sh confirm base port login pass +#------------------------------------------------------ + + +export mydir=`echo "$0" | sed -e 's/initdemopassword.sh//'`; +if [ "x$mydir" = 'x' -o "x$mydir" = 'x./' ] +then + export mydir="." +fi +export id=`id -u`; + + +# ----------------------------- check if root +if [ "x$id" != "x0" -a "x$id" != "x1001" ] +then + echo "Script must be ran as root" + exit +fi + + +# ----------------------------- command line params +confirm=$1; +base=$2; +port=$3; +demologin=$4; +demopass=$5; + +# ----------------------------- check params +if [ "x$confirm" != "xconfirm" ] +then + echo "----- $0 -----" + echo "Usage: initdemopassword.sh confirm [base port login pass]" + exit +fi + + +# ----------------------------- if no params on command line +if [ "x$demopass" = "x" ] +then + export dumpfile=`ls -v $mydir/mysqldump_dolibarr_*.sql | tail -n 1` + export dumpfile=`basename $dumpfile` + + # ----------------------------- database name + DIALOG=${DIALOG=dialog} + DIALOG="$DIALOG --ascii-lines" + fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ + trap "rm -f $fichtemp" 0 1 2 5 15 + $DIALOG --title "Init Dolibarr with demo values" --clear \ + --inputbox "Mysql database name :" 16 55 dolibarrdemo 2> $fichtemp + valret=$? + case $valret in + 0) + base=`cat $fichtemp`;; + 1) + exit;; + 255) + exit;; + esac + rm $fichtemp + + # ---------------------------- database port + DIALOG=${DIALOG=dialog} + fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ + trap "rm -f $fichtemp" 0 1 2 5 15 + $DIALOG --title "Init Dolibarr with demo values" --clear \ + --inputbox "Mysql port (ex: 3306):" 16 55 3306 2> $fichtemp + + valret=$? + + case $valret in + 0) + port=`cat $fichtemp`;; + 1) + exit;; + 255) + exit;; + esac + rm $fichtemp + + + # ----------------------------- demo login + DIALOG=${DIALOG=dialog} + DIALOG="$DIALOG --ascii-lines" + fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ + trap "rm -f $fichtemp" 0 1 2 5 15 + $DIALOG --title "Reset login password" --clear \ + --inputbox "Login to reset :" 16 55 dolibarrdemologin 2> $fichtemp + valret=$? + case $valret in + 0) + demologin=`cat $fichtemp`;; + 1) + exit;; + 255) + exit;; + esac + rm fichtemp + + # ----------------------------- demo pass + DIALOG=${DIALOG=dialog} + DIALOG="$DIALOG --ascii-lines" + fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ + trap "rm -f $fichtemp" 0 1 2 5 15 + $DIALOG --title "Reset login password" --clear \ + --inputbox "Pass to set :" 16 55 dolibarrdemopass 2> $fichtemp + valret=$? + case $valret in + 0) + demopass=`cat $fichtemp`;; + 1) + exit;; + 255) + exit;; + esac + rm fichtemp + + + export documentdir=`cat $mydir/../../htdocs/conf/conf.php | grep '^\$dolibarr_main_data_root' | sed -e 's/$dolibarr_main_data_root=//' | sed -e 's/;//' | sed -e "s/'//g" | sed -e 's/"//g' ` + + + # ---------------------------- confirmation + DIALOG=${DIALOG=dialog} + $DIALOG --title "Init demo login with demo values" --clear \ + --yesno "Do you confirm ? \n Mysql database : '$base' \n Mysql port : '$port' \n Demo login: '$demologin' \n Demo password : '$demopass'" 15 55 + + case $? in + 0) echo "Ok, start process...";; + 1) exit;; + 255) exit;; + esac + +fi + + +# ---------------------------- run sql file +if [ "x$passwd" != "x" ] +then + export passwd="-p$passwd" +fi +#echo "mysql -P$port -u$admin $passwd $base < $mydir/$dumpfile" +#mysql -P$port -u$admin $passwd $base < $mydir/$dumpfile +echo "echo \"UPDATE llx_user SET pass_crypted = MD5('$demopass') WHERE login = '$demologin';\" | mysql -P$port $base" +echo "UPDATE llx_user SET pass_crypted = MD5('$demopass') WHERE login = '$demologin';" | mysql -P$port $base +export res=$? + +if [ $res -ne 0 ]; then + echo "Error to execute sql with mysql -P$port -u$admin -p***** $base" + exit +fi + + +if [ "x$res" = "x0" ] +then + echo "Success, file successfully loaded." +else + echo "Error, load failed." +fi +echo diff --git a/dev/initdemo/mysqldump_dolibarr_12.0.0.sql b/dev/initdemo/mysqldump_dolibarr_12.0.0.sql index 25663fa6991..3cc1db1cf34 100644 --- a/dev/initdemo/mysqldump_dolibarr_12.0.0.sql +++ b/dev/initdemo/mysqldump_dolibarr_12.0.0.sql @@ -1326,7 +1326,7 @@ CREATE TABLE `llx_boxes_def` ( LOCK TABLES `llx_boxes_def` WRITE; /*!40000 ALTER TABLE `llx_boxes_def` DISABLE KEYS */; -INSERT INTO `llx_boxes_def` VALUES (188,'box_services_vendus.php',1,'2013-08-05 20:40:27',NULL),(323,'box_actions.php',2,'2015-03-13 15:29:19',NULL),(324,'box_clients.php',2,'2015-03-13 20:21:35',NULL),(325,'box_prospect.php',2,'2015-03-13 20:21:35',NULL),(326,'box_contacts.php',2,'2015-03-13 20:21:35',NULL),(327,'box_activity.php',2,'2015-03-13 20:21:35','(WarningUsingThisBoxSlowDown)'),(328,'box_propales.php',2,'2015-03-13 20:32:38',NULL),(329,'box_comptes.php',2,'2015-03-13 20:33:09',NULL),(330,'box_factures_imp.php',2,'2015-03-13 20:33:09',NULL),(331,'box_factures.php',2,'2015-03-13 20:33:09',NULL),(332,'box_produits.php',2,'2015-03-13 20:33:09',NULL),(333,'box_produits_alerte_stock.php',2,'2015-03-13 20:33:09',NULL),(347,'box_clients.php',1,'2017-11-15 22:05:57',NULL),(348,'box_prospect.php',1,'2017-11-15 22:05:57',NULL),(349,'box_contacts.php',1,'2017-11-15 22:05:57',NULL),(350,'box_activity.php',1,'2017-11-15 22:05:57','(WarningUsingThisBoxSlowDown)'),(374,'box_services_contracts.php',1,'2017-11-15 22:38:37',NULL),(377,'box_project.php',1,'2017-11-15 22:38:44',NULL),(378,'box_task.php',1,'2017-11-15 22:38:44',NULL),(388,'box_contracts.php',1,'2017-11-15 22:39:52',NULL),(389,'box_services_expired.php',1,'2017-11-15 22:39:52',NULL),(390,'box_ficheinter.php',1,'2017-11-15 22:39:56',NULL),(392,'box_graph_propales_permonth.php',1,'2017-11-15 22:41:47',NULL),(393,'box_propales.php',1,'2017-11-15 22:41:47',NULL),(396,'box_graph_product_distribution.php',1,'2017-11-15 22:41:47',NULL),(403,'box_goodcustomers.php',1,'2018-07-30 11:13:20','(WarningUsingThisBoxSlowDown)'),(404,'box_external_rss.php',1,'2018-07-30 11:15:25','1 (Dolibarr.org News)'),(409,'box_produits.php',1,'2018-07-30 13:38:11',NULL),(410,'box_produits_alerte_stock.php',1,'2018-07-30 13:38:11',NULL),(411,'box_commandes.php',1,'2018-07-30 13:38:11',NULL),(412,'box_graph_orders_permonth.php',1,'2018-07-30 13:38:11',NULL),(413,'box_graph_invoices_supplier_permonth.php',1,'2018-07-30 13:38:11',NULL),(414,'box_graph_orders_supplier_permonth.php',1,'2018-07-30 13:38:11',NULL),(415,'box_fournisseurs.php',1,'2018-07-30 13:38:11',NULL),(416,'box_factures_fourn_imp.php',1,'2018-07-30 13:38:11',NULL),(417,'box_factures_fourn.php',1,'2018-07-30 13:38:11',NULL),(418,'box_supplier_orders.php',1,'2018-07-30 13:38:11',NULL),(419,'box_actions.php',1,'2018-07-30 15:42:32',NULL),(424,'box_factures_imp.php',1,'2017-02-07 18:56:12',NULL),(425,'box_factures.php',1,'2017-02-07 18:56:12',NULL),(426,'box_graph_invoices_permonth.php',1,'2017-02-07 18:56:12',NULL),(427,'box_comptes.php',1,'2017-02-07 18:56:12',NULL),(429,'box_lastlogin.php',1,'2017-08-27 13:29:14',NULL),(430,'box_bookmarks.php',1,'2018-01-19 11:27:34',NULL),(431,'box_members.php',1,'2018-01-19 11:27:56',NULL),(432,'box_birthdays.php',1,'2019-06-05 08:45:40',NULL),(433,'box_last_ticket',1,'2019-06-05 09:15:29',NULL),(434,'box_last_modified_ticket',1,'2019-06-05 09:15:29',NULL),(436,'box_accountancy_last_manual_entries.php',1,'2019-11-28 11:52:58',NULL),(437,'box_accountancy_suspense_account.php',1,'2019-11-28 11:52:58',NULL),(438,'box_supplier_orders_awaiting_reception.php',1,'2019-11-28 11:52:59',NULL),(439,'box_mos.php',1,'2019-11-29 08:57:42',NULL),(445,'box_shipments.php',1,'2020-01-13 14:38:20',NULL); +INSERT INTO `llx_boxes_def` VALUES (323,'box_actions.php',2,'2015-03-13 15:29:19',NULL),(324,'box_clients.php',2,'2015-03-13 20:21:35',NULL),(325,'box_prospect.php',2,'2015-03-13 20:21:35',NULL),(326,'box_contacts.php',2,'2015-03-13 20:21:35',NULL),(327,'box_activity.php',2,'2015-03-13 20:21:35','(WarningUsingThisBoxSlowDown)'),(328,'box_propales.php',2,'2015-03-13 20:32:38',NULL),(329,'box_comptes.php',2,'2015-03-13 20:33:09',NULL),(330,'box_factures_imp.php',2,'2015-03-13 20:33:09',NULL),(331,'box_factures.php',2,'2015-03-13 20:33:09',NULL),(332,'box_produits.php',2,'2015-03-13 20:33:09',NULL),(333,'box_produits_alerte_stock.php',2,'2015-03-13 20:33:09',NULL),(347,'box_clients.php',1,'2017-11-15 22:05:57',NULL),(348,'box_prospect.php',1,'2017-11-15 22:05:57',NULL),(349,'box_contacts.php',1,'2017-11-15 22:05:57',NULL),(350,'box_activity.php',1,'2017-11-15 22:05:57','(WarningUsingThisBoxSlowDown)'),(374,'box_services_contracts.php',1,'2017-11-15 22:38:37',NULL),(377,'box_project.php',1,'2017-11-15 22:38:44',NULL),(378,'box_task.php',1,'2017-11-15 22:38:44',NULL),(388,'box_contracts.php',1,'2017-11-15 22:39:52',NULL),(389,'box_services_expired.php',1,'2017-11-15 22:39:52',NULL),(390,'box_ficheinter.php',1,'2017-11-15 22:39:56',NULL),(392,'box_graph_propales_permonth.php',1,'2017-11-15 22:41:47',NULL),(393,'box_propales.php',1,'2017-11-15 22:41:47',NULL),(396,'box_graph_product_distribution.php',1,'2017-11-15 22:41:47',NULL),(403,'box_goodcustomers.php',1,'2018-07-30 11:13:20','(WarningUsingThisBoxSlowDown)'),(404,'box_external_rss.php',1,'2018-07-30 11:15:25','1 (Dolibarr.org News)'),(409,'box_produits.php',1,'2018-07-30 13:38:11',NULL),(410,'box_produits_alerte_stock.php',1,'2018-07-30 13:38:11',NULL),(411,'box_commandes.php',1,'2018-07-30 13:38:11',NULL),(412,'box_graph_orders_permonth.php',1,'2018-07-30 13:38:11',NULL),(413,'box_graph_invoices_supplier_permonth.php',1,'2018-07-30 13:38:11',NULL),(414,'box_graph_orders_supplier_permonth.php',1,'2018-07-30 13:38:11',NULL),(415,'box_fournisseurs.php',1,'2018-07-30 13:38:11',NULL),(416,'box_factures_fourn_imp.php',1,'2018-07-30 13:38:11',NULL),(417,'box_factures_fourn.php',1,'2018-07-30 13:38:11',NULL),(418,'box_supplier_orders.php',1,'2018-07-30 13:38:11',NULL),(419,'box_actions.php',1,'2018-07-30 15:42:32',NULL),(424,'box_factures_imp.php',1,'2017-02-07 18:56:12',NULL),(425,'box_factures.php',1,'2017-02-07 18:56:12',NULL),(426,'box_graph_invoices_permonth.php',1,'2017-02-07 18:56:12',NULL),(427,'box_comptes.php',1,'2017-02-07 18:56:12',NULL),(429,'box_lastlogin.php',1,'2017-08-27 13:29:14',NULL),(430,'box_bookmarks.php',1,'2018-01-19 11:27:34',NULL),(431,'box_members.php',1,'2018-01-19 11:27:56',NULL),(432,'box_birthdays.php',1,'2019-06-05 08:45:40',NULL),(433,'box_last_ticket',1,'2019-06-05 09:15:29',NULL),(434,'box_last_modified_ticket',1,'2019-06-05 09:15:29',NULL),(436,'box_accountancy_last_manual_entries.php',1,'2019-11-28 11:52:58',NULL),(437,'box_accountancy_suspense_account.php',1,'2019-11-28 11:52:58',NULL),(438,'box_supplier_orders_awaiting_reception.php',1,'2019-11-28 11:52:59',NULL),(439,'box_mos.php',1,'2019-11-29 08:57:42',NULL),(445,'box_shipments.php',1,'2020-01-13 14:38:20',NULL); /*!40000 ALTER TABLE `llx_boxes_def` ENABLE KEYS */; UNLOCK TABLES; diff --git a/dev/tools/dolibarr-postgres2mysql.php b/dev/tools/dolibarr-postgres2mysql.php index c17a73dfe12..fd30540c019 100644 --- a/dev/tools/dolibarr-postgres2mysql.php +++ b/dev/tools/dolibarr-postgres2mysql.php @@ -357,8 +357,8 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true) $line = str_replace(" time with time zone", " time", $line); $line = str_replace(" time without time zone", " time", $line); - $line = str_replace(" timestamp DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); - $line = str_replace(" timestamp without time zone DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); + $line = str_replace(" timestamp DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", $line); + $line = str_replace(" timestamp without time zone DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", $line); if (strstr($line, "auto_increment") || preg_match('/ rowid int/', $line) || preg_match('/ id int/', $line)) { $field = getfieldname($line); diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index f6a4adac21e..0ac79bcc3aa 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -54,8 +54,8 @@ if (!$user->rights->accounting->chartofaccount) accessforbidden(); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -230,8 +230,8 @@ if (strlen(trim($search_account))) { $search_account_tmp_clean = preg_replace('/^\^/', '', $search_account_tmp); $search_account_clean = preg_replace('/^\^/', '', $search_account); } - $sql .= " AND (aa.account_number LIKE '".$startchar.$search_account_tmp_clean."'"; - $sql .= " OR aa.account_number LIKE '".$startchar.$search_account_clean."%')"; + $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); } } @@ -264,14 +264,14 @@ if ($resql) $num = $db->num_rows($resql); $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='.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='.$optioncss; + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if (!empty($conf->use_javascript_ajax)) { @@ -390,7 +390,7 @@ if ($resql) if (!empty($arrayfields['aa.account_number']['checked'])) { print ""; - print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1); + print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1, 0, 'accountcard'); print "\n"; if (!$i) $totalarray['nbfield']++; } @@ -481,11 +481,11 @@ if ($resql) // Action print ''; if ($user->rights->accounting->chartofaccount) { - print ''; + print ''; print img_edit(); print ''; print ' '; - print ''; + print ''; print img_delete(); print ''; } diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 9794198332e..d3bd17d95a5 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -280,7 +280,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); dol_syslog("actionmodify", LOG_DEBUG); //print $sql; @@ -302,7 +302,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete { if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid); dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); @@ -323,9 +323,9 @@ if ($action == $acts[0]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$db->escape($code)."'"; } $result = $db->query($sql); @@ -341,9 +341,9 @@ if ($action == $acts[1]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$db->escape($code)."'"; } $result = $db->query($sql); @@ -359,9 +359,9 @@ if ($action == 'activate_favorite') if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$db->escape($code)."'"; } $result = $db->query($sql); @@ -377,9 +377,9 @@ if ($action == 'disable_favorite') if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$db->escape($code)."'"; } $result = $db->query($sql); @@ -669,11 +669,11 @@ if ($id) print ""; // Modify link - if ($canbemodified) print ''.img_edit().''; + if ($canbemodified) print ''.img_edit().''; else print ' '; // Delete link - if ($iserasable) print ''.img_delete().''; + if ($iserasable) print ''.img_delete().''; else print ' '; print "\n"; diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index bc695da0203..29ed90bb7be 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -44,6 +44,8 @@ $cancel = GETPOST('cancel', 'alpha'); $accountingaccount = GETPOST('accountingaccount', 'alpha'); // Security check +if ($user->socid > 0) accessforbidden(); +if (!$user->rights->accounting->chartofaccount) accessforbidden(); $object = new AccountingAccount($db); @@ -370,13 +372,13 @@ if ($action == 'create') { print '
'; if (!empty($user->rights->accounting->chartofaccount)) { - print ''.$langs->trans('Modify').''; + print ''.$langs->trans('Modify').''; } else { print ''.$langs->trans('Modify').''; } if (!empty($user->rights->accounting->chartofaccount)) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index 909d633c487..d605105f8e9 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -170,7 +170,7 @@ if ($action == 'display' || $action == 'delete') { print ''.length_accountg($cpt->account_number).''; print ''.$cpt->label.''; print ''; - print "rowid."'>"; + print ''; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink'); print ""; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index ddd4240a073..9469a1e64f1 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -271,7 +271,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); dol_syslog("actionmodify", LOG_DEBUG); //print $sql; @@ -293,7 +293,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete { if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid); dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); @@ -314,7 +314,7 @@ if ($action == $acts[0]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code = '".$db->escape($code)."'"; } @@ -332,7 +332,7 @@ if ($action == $acts[1]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code = '".$db->escape($code)."'"; } @@ -350,7 +350,7 @@ if ($action == 'activate_favorite') if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code = '".$db->escape($code)."'"; } @@ -368,7 +368,7 @@ if ($action == 'disable_favorite') if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = '".$db->escape($rowid)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code = '".$db->escape($code)."'"; } diff --git a/htdocs/accountancy/admin/closure.php b/htdocs/accountancy/admin/closure.php index 63b2131f309..a425fd45768 100644 --- a/htdocs/accountancy/admin/closure.php +++ b/htdocs/accountancy/admin/closure.php @@ -92,7 +92,7 @@ print ''.$langs->trans("DefaultClosureDesc").''; print '
'; -print ''; +print ''; print ''; // Define main accounts for closure diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 96303f36b1d..b9377ce4431 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -47,9 +47,9 @@ $action = GETPOST('action', 'aZ09'); $list_account_main = array( - 'ACCOUNTING_ACCOUNT_CUSTOMER', - 'ACCOUNTING_ACCOUNT_SUPPLIER', - 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', + 'ACCOUNTING_ACCOUNT_CUSTOMER', + 'ACCOUNTING_ACCOUNT_SUPPLIER', + 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', ); $list_account = array(); @@ -75,7 +75,7 @@ if ($mysoc->isInEEC()) { $list_account[] = 'ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT'; } $list_account[] = 'ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT'; -$list_account[] = '---Other---'; +$list_account[] = '---Others---'; $list_account[] = 'ACCOUNTING_VAT_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_SOLD_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_PAY_ACCOUNT'; @@ -94,26 +94,13 @@ if ($conf->loan->enabled) { $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INTEREST'; $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE'; } +if ($conf->societe->enabled) { + $list_account[] = 'ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT'; +} /* * Actions */ - -$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; - -if (GETPOST('change_chart', 'alpha')) -{ - $chartofaccounts = GETPOST('chartofaccounts', 'int'); - - if (!empty($chartofaccounts)) { - if (!dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error++; - } - } else { - $error++; - } -} - if ($action == 'update') { $error = 0; @@ -133,9 +120,9 @@ if ($action == 'update') { $constvalue = GETPOST($constname, 'alpha'); - if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error++; - } + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } } if (!$error) { @@ -172,20 +159,20 @@ print ''; print ''; foreach ($list_account_main as $key) { - print ''; - // Param - $label = $langs->trans($key); - $keydesc = $key.'_Desc'; + print ''; + // Param + $label = $langs->trans($key); + $keydesc = $key.'_Desc'; - $htmltext = $langs->trans($keydesc); - print ''; - // Value - print ''; - print ''; + $htmltext = $langs->trans($keydesc); + print ''; + // Value + print ''; + print ''; } diff --git a/htdocs/accountancy/admin/fiscalyear.php b/htdocs/accountancy/admin/fiscalyear.php index b5cc46a3d0d..1ddcddf13e6 100644 --- a/htdocs/accountancy/admin/fiscalyear.php +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -29,8 +29,8 @@ $action = GETPOST('action', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -79,6 +79,7 @@ $object = new Fiscalyear($db); $max = 100; $form = new Form($db); +$fiscalyearstatic = new Fiscalyear($db); $title = $langs->trans('AccountingPeriods'); $helpurl = ""; @@ -132,13 +133,15 @@ if ($result) print ''; if ($num) { - $fiscalyearstatic = new Fiscalyear($db); - while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); + $fiscalyearstatic->id = $obj->rowid; + print ''; - print ''; + print ''; print ''; print ''; print ''; diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index 27ef1ea7bd1..a4227a761a4 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -300,16 +300,16 @@ if ($action == 'create') if (!empty($user->rights->accounting->fiscalyear->write)) { - /* + /* * Barre d'actions */ - print '
'; + print ''; + print '
'; } } } else { diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 006db08fe9c..516af988334 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -31,9 +31,10 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("compta", "bills", "admin", "accountancy")); +$langs->loadLangs(array("compta", "bills", "admin", "accountancy", "other")); // Security access if (empty($user->rights->accounting->chartofaccount)) @@ -45,78 +46,95 @@ $action = GETPOST('action', 'aZ09'); // Parameters ACCOUNTING_* and others $list = array( - 'ACCOUNTING_LENGTH_GACCOUNT', - 'ACCOUNTING_LENGTH_AACCOUNT', + 'ACCOUNTING_LENGTH_GACCOUNT', + 'ACCOUNTING_LENGTH_AACCOUNT', // 'ACCOUNTING_LENGTH_DESCRIPTION', // adjust size displayed for lines description for dol_trunc // 'ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT', // adjust size displayed for select account description for dol_trunc ); - +$list_binding = array( + 'ACCOUNTING_DATE_START_BINDING', + 'ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER' +); /* * Actions */ -$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; - if ($action == 'update') { $error = 0; if (!$error) { - foreach ($list as $constname) - { - $constvalue = GETPOST($constname, 'alpha'); + foreach ($list as $constname) + { + $constvalue = GETPOST($constname, 'alpha'); - if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error++; - } - } - if ($error) { - setEventMessages($langs->trans("Error"), null, 'errors'); - } + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } + if ($error) { + setEventMessages($langs->trans("Error"), null, 'errors'); + } + + foreach ($list_binding as $constname) + { + $constvalue = GETPOST($constname, 'alpha'); + + if ($constname == 'ACCOUNTING_DATE_START_BINDING') { + $constvalue = dol_mktime(12, 0, 0, GETPOST($constname.'month', 'int'), GETPOST($constname.'day', 'int'), GETPOST($constname.'year', 'int')); + } + + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } + if ($error) { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } } if ($action == 'setlistsorttodo') { - $setlistsorttodo = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); - if (!$res > 0) - $error++; + $setlistsorttodo = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setlistsortdone') { - $setlistsortdone = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); - if (!$res > 0) - $error++; - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setlistsortdone = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setmanagezero') { - $setmanagezero = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); - if (!$res > 0) - $error++; - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setmanagezero = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setdisabledirectinput') { @@ -144,20 +162,57 @@ if ($action == 'setenabledraftexport') { } if ($action == 'setenablesubsidiarylist') { - $setenablesubsidiarylist = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTANCY_COMBO_FOR_AUX", $setenablesubsidiarylist, 'yesno', 0, '', $conf->entity); - if (!$res > 0) - $error++; - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setenablesubsidiarylist = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTANCY_COMBO_FOR_AUX", $setenablesubsidiarylist, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } +} + +if ($action == 'setdisablebindingonsales') { + $setdisablebindingonsales = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_SALES", $setdisablebindingonsales, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } +} + +if ($action == 'setdisablebindingonpurchases') { + $setdisablebindingonpurchases = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_PURCHASES", $setdisablebindingonpurchases, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } +} + +if ($action == 'setdisablebindingonexpensereports') { + $setdisablebindingonexpensereports = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_EXPENSEREPORTS", $setdisablebindingonexpensereports, 'yesno', 0, '', $conf->entity); + if (!$res > 0) + $error++; + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } /* * View */ +$form = new Form($db); $title = $langs->trans('ConfigAccountingExpert'); llxHeader('', $title); @@ -170,155 +225,187 @@ print ''; print ''; print ''; -// Default mode for calculating turnover (parameter ACCOUNTING_MODE) -/* +// Params print '
'.$langs->trans("ThirdParties").' | '.$langs->trans("Users").'
'; - print $form->textwithpicto($label, $htmltext); - print ''; // Do not force class=right, or it align also the content of the select box - print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); - print '
'; + print $form->textwithpicto($label, $htmltext); + print ''; // Do not force class=right, or it align also the content of the select box + print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); + print '
'.img_object($langs->trans("ShowFiscalYear"), "technic").' '.$obj->rowid.''; + print $fiscalyearstatic->getNomUrl(1); + print ''.$obj->label.''.dol_print_date($db->jdate($obj->date_start), 'day').''.dol_print_date($db->jdate($obj->date_end), 'day').'
'; - print ''; -print ''; +print ''; print "\n"; -print ''; -print '\n"; -print ''; -print '\n"; -print "
' . $langs->trans('OptionMode') . '' . $langs->trans('Description') . ''.$langs->trans('Options').'
' . $langs->trans('OptionModeTrue') . '' . nl2br($langs->trans('OptionModeTrueDesc')); -// Write info on way to count VAT -// if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) -// { -// // print "
\n"; -// // print nl2br($langs->trans('OptionModeTrueInfoModuleComptabilite')); -// } -// else -// { -// // print "
\n"; -// // print nl2br($langs->trans('OptionModeTrueInfoExpert')); -// } -print "
' . $langs->trans('OptionModeVirtual') . '' . nl2br($langs->trans('OptionModeVirtualDesc')) . "
\n"; +// TO DO Mutualize code for yes/no constants - -print '
'; +/* Set this option as a hidden option but keep it for some needs. +print ''; +print ''.$langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL").''; +if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; +} else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; +} +print ''; */ -// Others params - -print ''; -print ''; -print ''; -print "\n"; - -if (!empty($user->admin)) -{ - // TO DO Mutualize code for yes/no constants - print ''; - print ''; - if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { - print ''; - } else { - print ''; - } - print ''; - - print ''; - print ''; - if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { - print ''; - } else { - print ''; - } - print ''; - - /* Set this option as a hidden option but keep it for some needs. - print ''; - print ''; - if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) { - print ''; - } else { - print ''; - } - print ''; - */ - - print ''; - print ''; - if (!empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { - print ''; - } else { - print ''; - } - print ''; - - print ''; - print ''; - if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { - print ''; - } else { - print ''; - } - print ''; - - print ''; - print ''; - if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { - print ''; - } else { - print ''; - } - print ''; +print ''; +print ''; +if (!empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { + print ''; +} else { + print ''; } +print ''; +print ''; +print ''; +if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print ''; +} else { + print ''; +} +print ''; + +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { + print ''; +} else { + print ''; +} +print ''; // Param a user $user->rights->accounting->chartofaccount can access foreach ($list as $key) { - print ''; + print ''; - if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue; + if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue; - // Param - $label = $langs->trans($key); - print ''; - // Value - print ''; + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + print ''; + print ''; +} +print '
'.$langs->trans('OtherOptions').'
'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("BANK_DISABLE_DIRECT_INPUT").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("ACCOUNTING_MANAGE_ZERO").''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'.$langs->trans("BANK_DISABLE_DIRECT_INPUT").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$langs->trans("ACCOUNTING_MANAGE_ZERO").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$label.''; - print ''; - print ''.$label.''; + print ''; - print '
'; +print '
'; + +// Binding params +print ''; +print ''; +print ''; +print "\n"; + +// TO DO Mutualize code for yes/no constants +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { + print ''; +} else { + print ''; +} +print ''; + +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { + print ''; +} else { + print ''; +} +print ''; + +// Param a user $user->rights->accounting->chartofaccount can access +foreach ($list_binding as $key) +{ + print ''; + + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + print ''; } +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_DISABLE_BINDING_ON_SALES)) { + print ''; +} else { + print ''; +} +print ''; + +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_DISABLE_BINDING_ON_PURCHASES)) { + print ''; +} else { + print ''; +} +print ''; + +print ''; +print ''; +if (!empty($conf->global->ACCOUNTING_DISABLE_BINDING_ON_EXPENSEREPORTS)) { + print ''; +} else { + print ''; +} +print ''; print '
'.$langs->trans('BindingOptions').'
'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$label.''; + if ($key == 'ACCOUNTING_DATE_START_BINDING') { + print $form->selectDate(($conf->global->$key ? $db->idate($conf->global->$key) : -1), $key, 0, 0, 1); + } elseif ($key == 'ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER') { + $array = array(0=>$langs->trans("PreviousMonth"), 1=>$langs->trans("CurrentMonth"), 2=>$langs->trans("Fiscalyear")); + print $form->selectarray($key, $array, (isset($conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER) ? $conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER : 0)); + } else { + print ''; + } + + print '
'.$langs->trans("ACCOUNTING_DISABLE_BINDING_ON_SALES").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$langs->trans("ACCOUNTING_DISABLE_BINDING_ON_PURCHASES").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'.$langs->trans("ACCOUNTING_DISABLE_BINDING_ON_EXPENSEREPORTS").''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'; print '
'; -print '
'; -print '
'; - -print '
'; print '
'; // End of page diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index 74247c5fccd..819160e7d23 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -22,6 +22,8 @@ * \brief Setup page to configure journals */ +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/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; @@ -274,7 +276,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); $sql .= " AND entity = ".$conf->entity; dol_syslog("actionmodify", LOG_DEBUG); @@ -297,7 +299,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete { if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid); $sql .= " AND entity = ".$conf->entity; dol_syslog("delete", LOG_DEBUG); @@ -319,9 +321,9 @@ if ($action == $acts[0]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$db->escape($code)."'"; } $sql .= " AND entity = ".$conf->entity; @@ -338,9 +340,9 @@ if ($action == $acts[1]) if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$db->escape($code)."'"; } $sql .= " AND entity = ".$conf->entity; @@ -636,19 +638,19 @@ if ($id) // Active print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; + if ($canbedisabled) print ''.$actl[$obj->active].''; else print $langs->trans("AlwaysActive"); print ""; // Modify link - if ($canbemodified) print ''.img_edit().''; + if ($canbemodified) print ''.img_edit().''; else print ' '; // Delete link if ($iserasable) { print ''; - if ($user->admin) print ''.img_delete().''; + if ($user->admin) print ''.img_delete().''; //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin print ''; } else print ' '; diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index b6465b95355..d88800016a8 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -57,6 +57,7 @@ $changeaccount_sell = GETPOST('changeaccount_sell', 'array'); $search_ref = GETPOST('search_ref', 'alpha'); $search_label = GETPOST('search_label', 'alpha'); $search_desc = GETPOST('search_desc', 'alpha'); +$search_vat = GETPOST('search_vat', 'alpha'); $search_current_account = GETPOST('search_current_account', 'alpha'); $search_current_account_valid = GETPOST('search_current_account_valid', 'alpha'); if ($search_current_account_valid == '') $search_current_account_valid = 'withoutvalidaccount'; @@ -102,6 +103,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_ref = ''; $search_label = ''; $search_desc = ''; + $search_vat = ''; $search_onsell = ''; $search_onpurchase = ''; $search_current_account = ''; @@ -136,7 +138,7 @@ if ($action == 'update') { if (!empty($chk_prod)) { $accounting = new AccountingAccount($db); - //$msg .= '
' . count($chk_prod) . ' ' . $langs->trans("SelectedLines") . '
'; + //$msg .= '
' . count($chk_prod) . ' ' . $langs->trans("SelectedLines") . '
'; $arrayofdifferentselectedvalues = array(); $cpt = 0; $ok = 0; $ko = 0; @@ -152,7 +154,7 @@ if ($action == 'update') { } if ($result <= 0) { // setEventMessages(null, $accounting->errors, 'errors'); - $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Product").' '.$productid.' '.$langs->trans("NotVentilatedinAccount").' : id='.$accounting_account_id.'
'.$sql.'
'; + $msg .= '
'.$langs->trans("ErrorDB").' : '.$langs->trans("Product").' '.$productid.' '.$langs->trans("NotVentilatedinAccount").' : id='.$accounting_account_id.'
'.$sql.'
'; $ko++; } else { $db->begin(); @@ -176,7 +178,7 @@ if ($action == 'update') { if ($accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { $sql .= " SET accountancy_code_sell_export = ".$accounting->account_number; } - $sql .= " WHERE rowid = ".$productid; + $sql .= " WHERE rowid = ".((int) $productid); dol_syslog("/accountancy/admin/productaccount.php sql=".$sql, LOG_DEBUG); if ($db->query($sql)) @@ -243,7 +245,7 @@ $pcgverid = $conf->global->CHARTOFACCOUNTS; $pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version'); if (empty($pcgvercode)) $pcgvercode = $pcgverid; -$sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy,"; +$sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy, p.tva_tx,"; $sql .= " 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,"; $sql .= " p.tms, p.fk_product_type as product_type,"; @@ -251,21 +253,21 @@ $sql .= " aa.rowid as aaid"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON"; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { - $sql .= " p.accountancy_code_buy = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_buy = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA') { - $sql .= " p.accountancy_code_buy_intra = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_buy_intra = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') { - $sql .= " p.accountancy_code_buy_export = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_buy_export = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL') { - $sql .= " p.accountancy_code_sell = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_sell = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') { - $sql .= " p.accountancy_code_sell_intra = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_sell_intra = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } else { - $sql .= " p.accountancy_code_sell_export = aa.account_number AND aa.fk_pcg_version = '".$pcgvercode."'"; + $sql .= " p.accountancy_code_sell_export = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'"; } $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { @@ -311,6 +313,9 @@ if (strlen(trim($search_label))) { if (strlen(trim($search_desc))) { $sql .= natural_search("p.description", $search_desc); } +if (strlen(trim($search_vat))) { + $sql .= natural_search("p.tva_tx", price2num($search_vat), 1); +} if ($search_onsell != '' && $search_onsell != '-1') $sql .= natural_search('p.tosell', $search_onsell, 1); if ($search_onpurchase != '' && $search_onpurchase != '-1') $sql .= natural_search('p.tobuy', $search_onpurchase, 1); @@ -343,6 +348,7 @@ if ($result) if ($search_ref > 0) $param .= "&search_desc=".urlencode($search_ref); if ($search_label > 0) $param .= "&search_desc=".urlencode($search_label); if ($search_desc > 0) $param .= "&search_desc=".urlencode($search_desc); + if ($search_vat > 0) $param .= '&search_vat='.urlencode($search_vat); if ($search_current_account > 0) $param .= "&search_current_account=".urlencode($search_current_account); if ($search_current_account_valid && $search_current_account_valid != '-1') $param .= "&search_current_account_valid=".urlencode($search_current_account_valid); if ($accounting_product_mode) $param .= '&accounting_product_mode='.urlencode($accounting_product_mode); @@ -411,6 +417,8 @@ if ($result) print ''; print ''; print ''; + print ''; + if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print ''; // On sell if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') { @@ -437,7 +445,8 @@ if ($result) 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->global->ACCOUNTANCY_SHOW_PROD_DESC)) print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder); - // On sell / On purchase + print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "p.tva_tx", "", $param, '', $sortfield, $sortorder, 'right '); + // On sell / On purchase if ($accounting_product_mode == 'ACCOUNTANCY_SELL') { print_liste_field_titre("OnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'center '); $fieldtosortaccount = "p.accountancy_code_sell"; @@ -553,11 +562,16 @@ if ($result) { // TODO ADJUST DESCRIPTION SIZE // print '' . $obj->description . ''; - // TODO: we shoul set a user defined value to adjust user square / wide screen size - $trunclengh = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION) ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; - print ''.nl2br(dol_trunc($obj->description, $trunclengh)).''; + // TODO: we should set a user defined value to adjust user square / wide screen size + $trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION) ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + print ''.nl2br(dol_trunc($obj->description, $trunclength)).''; } + // VAT + print ''; + print vatrate($obj->tva_tx); + print ''; + if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') print ''.$product_static->getLibStatut(3, 0).''; @@ -602,7 +616,7 @@ if ($result) // Accounting account buy intra (In EEC) print ''; //$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha'); This is id and we need a code - if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy_intra; + if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy; $codesell = length_accountg($obj->accountancy_code_buy_intra); //var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell); if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid @@ -612,7 +626,7 @@ if ($result) // Accounting account buy export (Out of EEC) print ''; //$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha'); This is id and we need a code - if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy_export; + if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy; $codesell = length_accountg($obj->accountancy_code_buy_export); //var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell); if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid diff --git a/htdocs/accountancy/admin/subaccount.php b/htdocs/accountancy/admin/subaccount.php new file mode 100644 index 00000000000..a6f61283d75 --- /dev/null +++ b/htdocs/accountancy/admin/subaccount.php @@ -0,0 +1,417 @@ + + * Copyright (C) 2013-2020 Alexandre Spangaro + * Copyright (C) 2016-2018 Laurent Destailleur + * + * 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/accountancy/admin/subaccount.php + * \ingroup Accountancy (Double entries) + * \brief List of accounting sub-account (auxiliary accounts) + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array("compta", "bills", "admin", "accountancy", "salaries", "hrm", "errors")); + +$mesg = ''; +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); +$id = GETPOST('id', 'int'); +$rowid = GETPOST('rowid', 'int'); +$massaction = GETPOST('massaction', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'accountingsubaccountlist'; // To manage different context of search + +$search_subaccount = GETPOST('search_subaccount', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); +$search_type = GETPOST('search_type', 'int'); + +// Security check +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 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortfield) $sortfield = "label"; +if (!$sortorder) $sortorder = "ASC"; + +$arrayfields = array( + 'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), + 'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1) +); + +if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['reconcilable']); + +/* + * Actions + */ + +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 (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 + { + $search_subaccount = ""; + $search_label = ""; + $search_type = ""; + $search_array_options = array(); + } +} + + +/* + * View + */ + +$form = new Form($db); + +llxHeader('', $langs->trans("ReportThirdParty")); + +// Customer +$sql = "SELECT sa.rowid, sa.nom as label, sa.code_compta as subaccount, '0' as type, sa.entity"; +$sql .= " FROM ".MAIN_DB_PREFIX."societe sa"; +$sql .= " WHERE sa.entity IN (".getEntity('societe').")"; +$sql .= " AND sa.code_compta <> ''"; +//print $sql; +if (strlen(trim($search_subaccount))) { + $lengthpaddingaccount = 0; + if ($conf->global->ACCOUNTING_LENGTH_AACCOUNT) { + $lengthpaddingaccount = max($conf->global->ACCOUNTING_LENGTH_AACCOUNT); + } + $search_subaccount_tmp = $search_subaccount; + $weremovedsomezero = 0; + if (strlen($search_subaccount_tmp) <= $lengthpaddingaccount) { + for ($i = 0; $i < $lengthpaddingaccount; $i++) { + if (preg_match('/0$/', $search_subaccount_tmp)) { + $weremovedsomezero++; + $search_subaccount_tmp = preg_replace('/0$/', '', $search_subaccount_tmp); + } + } + } + + //var_dump($search_subaccount); exit; + if ($search_subaccount_tmp) { + if ($weremovedsomezero) { + $search_subaccount_tmp_clean = $search_subaccount_tmp; + $search_subaccount_clean = $search_subaccount; + $startchar = '%'; + if (strpos($search_subaccount_tmp, '^') === 0) + { + $startchar = ''; + $search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp); + $search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount); + } + $sql .= " AND (sa.code_compta LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'"; + $sql .= " OR sa.code_compta LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')"; + } else $sql .= natural_search("sa.code_compta", $search_subaccount_tmp); + } +} +if (strlen(trim($search_label))) $sql .= natural_search("sa.nom", $search_label); +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; + +// Supplier +$sql .= " UNION "; +$sql .= " SELECT sa.rowid, sa.nom as label, sa.code_compta_fournisseur as subaccount, '1' as type, sa.entity FROM ".MAIN_DB_PREFIX."societe sa"; +$sql .= " WHERE sa.entity IN (".getEntity('societe').")"; +$sql .= " AND sa.code_compta_fournisseur <> ''"; +//print $sql; +if (strlen(trim($search_subaccount))) { + $lengthpaddingaccount = 0; + if ($conf->global->ACCOUNTING_LENGTH_AACCOUNT) { + $lengthpaddingaccount = max($conf->global->ACCOUNTING_LENGTH_AACCOUNT); + } + $search_subaccount_tmp = $search_subaccount; + $weremovedsomezero = 0; + if (strlen($search_subaccount_tmp) <= $lengthpaddingaccount) { + for ($i = 0; $i < $lengthpaddingaccount; $i++) { + if (preg_match('/0$/', $search_subaccount_tmp)) { + $weremovedsomezero++; + $search_subaccount_tmp = preg_replace('/0$/', '', $search_subaccount_tmp); + } + } + } + + //var_dump($search_subaccount); exit; + if ($search_subaccount_tmp) { + if ($weremovedsomezero) { + $search_subaccount_tmp_clean = $search_subaccount_tmp; + $search_subaccount_clean = $search_subaccount; + $startchar = '%'; + if (strpos($search_subaccount_tmp, '^') === 0) + { + $startchar = ''; + $search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp); + $search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount); + } + $sql .= " AND (sa.code_compta_fournisseur LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'"; + $sql .= " OR sa.code_compta_fournisseur LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')"; + } else $sql .= natural_search("sa.code_compta_fournisseur", $search_subaccount_tmp); + } +} +if (strlen(trim($search_label))) $sql .= natural_search("sa.nom", $search_label); +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; + +// User +$sql .= " UNION "; +$sql .= " SELECT u.rowid, u.lastname as label, u.accountancy_code as subaccount, '2' as type, u.entity FROM ".MAIN_DB_PREFIX."user u"; +$sql .= " WHERE u.entity IN (".getEntity('user').")"; +$sql .= " AND u.accountancy_code <> ''"; +//print $sql; +if (strlen(trim($search_subaccount))) { + $lengthpaddingaccount = 0; + if ($conf->global->ACCOUNTING_LENGTH_AACCOUNT) { + $lengthpaddingaccount = max($conf->global->ACCOUNTING_LENGTH_AACCOUNT); + } + $search_subaccount_tmp = $search_subaccount; + $weremovedsomezero = 0; + if (strlen($search_subaccount_tmp) <= $lengthpaddingaccount) { + for ($i = 0; $i < $lengthpaddingaccount; $i++) { + if (preg_match('/0$/', $search_subaccount_tmp)) { + $weremovedsomezero++; + $search_subaccount_tmp = preg_replace('/0$/', '', $search_subaccount_tmp); + } + } + } + + //var_dump($search_subaccount); exit; + if ($search_subaccount_tmp) { + if ($weremovedsomezero) { + $search_subaccount_tmp_clean = $search_subaccount_tmp; + $search_subaccount_clean = $search_subaccount; + $startchar = '%'; + if (strpos($search_subaccount_tmp, '^') === 0) + { + $startchar = ''; + $search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp); + $search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount); + } + $sql .= " AND (u.accountancy_code LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'"; + $sql .= " OR u.accountancy_code LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')"; + } else $sql .= natural_search("u.accountancy_code", $search_subaccount_tmp); + } +} +if (strlen(trim($search_label))) $sql .= natural_search("u.lastname", $search_label); +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; + +$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 resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } +} + +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/admin/subaccount.php:: $sql='.$sql); +$resql = $db->query($sql); + +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_subaccount) $param .= '&search_subaccount='.urlencode($search_subaccount); + if ($search_label) $param .= '&search_label='.urlencode($search_label); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + + print '
'; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print_barre_liste($langs->trans('ReportThirdParty'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 0, 0, 1); + + print '
'.$langs->trans("WarningCreateSubAccounts").'
'; + + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + $moreforfilter = ''; + $massactionbutton = ''; + + print '
'; + print ''."\n"; + + // Line for search fields + print ''; + if (!empty($arrayfields['subaccount']['checked'])) print ''; + if (!empty($arrayfields['label']['checked'])) print ''; + if (!empty($arrayfields['type']['checked'])) print ''; + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['reconcilable']['checked'])) print ''; } + print ''; + print ''; + + print ''; + if (!empty($arrayfields['subaccount']['checked'])) print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['label']['checked'])) print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center '); + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['reconcilable']['checked'])) print_liste_field_titre($arrayfields['reconcilable']['label'], $_SERVER["PHP_SELF"], 'reconcilable', '', $param, '', $sortfield, $sortorder, 'center '); } + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); + print "\n"; + + $totalarray = array(); + $i = 0; + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + + print ''; + + // Account number + if (!empty($arrayfields['subaccount']['checked'])) + { + print "\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Subaccount label + if (!empty($arrayfields['label']['checked'])) + { + print "\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Type + if (!empty($arrayfields['type']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + // Activated or not reconciliation on accounting account + if (!empty($arrayfields['reconcilable']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + } + + // Action + print ''."\n"; + if (!$i) $totalarray['nbfield']++; + + print ''."\n"; + $i++; + } + + $db->free($resql); + + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + print "
'.$form->selectarray('search_type', array('0'=>$langs->trans('Customer'), '1'=>$langs->trans('Supplier'), '2'=>$langs->trans('Employee')), $search_type, 1).' '; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + print $searchpicto; + print '
"; + print length_accounta($obj->subaccount); + print ""; + print $obj->label; + print "'; + $s = ''; + // Customer + if ($obj->type == 0) + { + $s .= ''.$langs->trans("Customer").''; + } + // Supplier + elseif ($obj->type == 1) + { + $s .= ''.$langs->trans("Supplier").''; + } + // User + elseif ($obj->type == 2) + { + $s .= ''.$langs->trans("Employee").''; + } + print $s; + print ''; + if (empty($obj->reconcilable)) { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } else { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + } + print ''; + $e = ''; + // Customer + if ($obj->type == 0) + { + $e .= ''.img_edit().''; + } + // Supplier + elseif ($obj->type == 1) + { + $e .= ''.img_edit().''; + } + // User + elseif ($obj->type == 2) + { + $e .= ''.img_edit().''; + } + print $e; + print '
"; + print "
"; + + print '
'; +} else { + dol_print_error($db); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 4de2be6fcbb..3608622916d 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -1,7 +1,7 @@ * Copyright (C) 2016 Florian Henry - * Copyright (C) 2016-2019 Alexandre Spangaro + * Copyright (C) 2016-2020 Alexandre Spangaro * Copyright (C) 2018 Frédéric France * * This program is free software; you can redistribute it and/or modify @@ -31,6 +31,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; @@ -45,8 +46,8 @@ $action = GETPOST('action', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -244,15 +245,15 @@ if ($action != 'export_csv') print ''; print ''; - print ''; - print ''; @@ -260,7 +261,6 @@ if ($action != 'export_csv') print ''; print_liste_field_titre("AccountAccounting", $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("Label", $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("OpeningBalance", $_SERVER['PHP_SELF'], "", $param, "", 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'class="right"', $sortfield, $sortorder); @@ -274,8 +274,14 @@ if ($action != 'export_csv') $sous_total_credit = 0; $displayed_account = ""; - $sql = "select t.numero_compte, (SUM(t.debit) - SUM(t.credit)) as opening_balance from ".MAIN_DB_PREFIX."accounting_bookkeeping as t where entity in ".$conf->entity; - $sql .= " AND t.doc_date < '".$db->idate($search_date_start)."' GROUP BY t.numero_compte"; + $accountingaccountstatic = new AccountingAccount($db); + + $sql = "SELECT t.numero_compte, (SUM(t.debit) - SUM(t.credit)) as opening_balance"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as t"; + $sql .= " WHERE t.entity = ".$conf->entity; // Never do sharing into accounting features + $sql .= " AND t.doc_date < '".$db->idate($search_date_start)."'"; + $sql .= " GROUP BY t.numero_compte"; + $resql = $db->query($sql); $nrows = $resql->num_rows; $opening_balances = array(); @@ -286,12 +292,18 @@ if ($action != 'export_csv') foreach ($object->lines as $line) { + $accountingaccountstatic->fetch(null, $line->numero_compte, true); + if (!empty($accountingaccountstatic->account_number)) { + $accounting_account = $accountingaccountstatic->getNomUrl(0, 1); + } else { + $accounting_account = length_accountg($line->numero_compte); + } + $link = ''; $total_debit += $line->debit; $total_credit += $line->credit; - $description = $object->get_compte_desc($line->numero_compte); // Search description of the account $root_account_description = $object->get_compte_racine($line->numero_compte); - if (empty($description)) { + if (empty($accountingaccountstatic->account_number)) { $link = ''.img_edit_add().''; } print ''; @@ -303,7 +315,7 @@ if ($action != 'export_csv') // Show subtotal per accounting account if ($displayed_account != "") { print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -313,7 +325,7 @@ if ($action != 'export_csv') // Show first line of a break print ''; - print ''; + print ''; print ''; $displayed_account = $root_account_description; @@ -321,10 +333,9 @@ if ($action != 'export_csv') $sous_total_credit = 0; } } - // $object->get_compte_racine($line->numero_compte); - print ''; - print ''; + // $object->get_compte_racine($line->numero_compte); + print ''; print ''; print ''; print ''; @@ -333,19 +344,19 @@ if ($action != 'export_csv') print ''; print "\n"; - // Comptabilise le sous-total + // Records the sub-total $sous_total_debit += $line->debit; $sous_total_credit += $line->credit; } if (!empty($show_subgroup)) { - print ''; + print ''; print "\n"; print ''; } - print ''; + print ''; print "\n"; print ''; diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index 4fafb8a19aa..8ca880de25f 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -292,7 +292,7 @@ if ($action == 'setjournal') { } if ($action == 'setdocref') { - $refdoc = trim(GETPOST('doc_ref', 'alpha')); + $refdoc = GETPOST('doc_ref', 'alpha'); $result = $object->updateByMvt($piece_num, 'doc_ref', $refdoc, $mode); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -328,7 +328,7 @@ llxHeader('', $langs->trans("CreateMvts")); // Confirmation to delete the command if ($action == 'delete') { - $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1); + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'confirm_delete', '', 0, 1); print $formconfirm; } diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 9a623287fc2..d89d0dca60c 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -91,8 +91,8 @@ $search_not_reconciled = GETPOST('search_reconciled_option', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; @@ -108,7 +108,7 @@ $hookmanager->initHooks(array('bookkeepinglist')); $formaccounting = new FormAccounting($db); $form = new Form($db); -if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !isset($_POST['begin']) && !isset($_GET['begin']) && !isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) +if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GETPOSTISSET('begin') && !isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) { if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('restore_lastsearch_values')) { @@ -529,7 +529,7 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { $formother = new FormOther($db); $formfile = new FormFile($db); -$title_page = $langs->trans("Bookkeeping"); +$title_page = $langs->trans("Operations").' - '.$langs->trans("Journals"); // Count total nb of records $nbtotalofrecords = ''; @@ -608,41 +608,43 @@ if ($action == 'delbookkeepingyear') { 'default' => $deljournal ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); print $formconfirm; } //$param=''; param started before -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='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); print ''; print ''; print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') print ''; print ''; -print ''; -print ''; -print ''; +print ''; +print ''; if (count($filter)) $buttonLabel = $langs->trans("ExportFilteredList"); else $buttonLabel = $langs->trans("ExportList"); // Button re-export if (!empty($conf->global->ACCOUNTING_REEXPORT)) { - $newcardbutton = ''.img_picto($langs->trans("Activated"), 'switch_on').' '; + $newcardbutton = ''.img_picto($langs->trans("Activated"), 'switch_on').' '; } else { - $newcardbutton = ''.img_picto($langs->trans("Disabled"), 'switch_off').' '; + $newcardbutton = ''.img_picto($langs->trans("Disabled"), 'switch_off').' '; } $newcardbutton .= ''.$langs->trans("IncludeDocsAlreadyExported").''; $newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export); -$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param, '', 1, array('morecss'=>'marginleftonly btnTitleSelected')); +$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss'=>'marginleftonly')); -$newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', './card.php?action=create', '', $user->rights->accounting->mouvements->creer); +$url = './card.php?action=create'; +if (!empty($socid)) $url .= '&socid='.$socid; +$newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', $url, '', $user->rights->accounting->mouvements->creer); -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); +print_barre_liste($title_page, $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 @@ -668,12 +670,10 @@ if (!empty($arrayfields['t.doc_date']['checked'])) { print ''; } @@ -701,25 +701,25 @@ if (!empty($arrayfields['t.subledger_account']['checked'])) { print ''; @@ -769,12 +769,10 @@ if (!empty($arrayfields['t.date_creation']['checked'])) { print ''; } @@ -783,12 +781,10 @@ if (!empty($arrayfields['t.tms']['checked'])) { print ''; } @@ -797,12 +793,10 @@ if (!empty($arrayfields['t.date_export']['checked'])) { print ''; } @@ -1047,10 +1041,10 @@ while ($i < min($num, $limit)) print ''; diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index d9c0c7b399f..4ed055be0b1 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -2,8 +2,8 @@ /* Copyright (C) 2016 Neil Orley * Copyright (C) 2013-2016 Olivier Geffroy * Copyright (C) 2013-2016 Florian Henry - * Copyright (C) 2013-2018 Alexandre Spangaro - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2013-2020 Alexandre Spangaro + * Copyright (C) 2018 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 @@ -31,14 +31,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.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.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page $langs->loadLangs(array("accountancy")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $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(0, 0, 0, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); @@ -54,6 +54,7 @@ if ($search_accountancy_code_end == - 1) { } $search_doc_ref = GETPOST('search_doc_ref', 'alpha'); $search_label_operation = GETPOST('search_label_operation', 'alpha'); +$search_mvt_num = GETPOST('search_mvt_num', 'int'); $search_direction = GETPOST('search_direction', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); $search_debit = GETPOST('search_debit', 'alpha'); @@ -67,8 +68,8 @@ if (GETPOST("button_delmvt_x") || GETPOST("button_delmvt.x") || GETPOST("button_ // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; @@ -85,7 +86,7 @@ $hookmanager->initHooks(array('bookkeepingbyaccountlist')); $formaccounting = new FormAccounting($db); $form = new Form($db); -if (empty($search_date_start) && empty($search_date_end) && GETPOSTISSET('search_date_startday') && GETPOSTISSET('search_date_startmonth') && GETPOSTISSET('search_date_starthour')) { +if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('search_date_startday') && !GETPOSTISSET('search_date_startmonth') && !GETPOSTISSET('search_date_starthour')) { $sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; $sql .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."'"; $sql .= $db->plimit(1); @@ -148,6 +149,7 @@ if (empty($reshook)) $search_label_account = ''; $search_doc_ref = ''; $search_label_operation = ''; + $search_mvt_num = ''; $search_direction = ''; $search_ledger_code = ''; $search_date_start = ''; @@ -192,6 +194,10 @@ if (empty($reshook)) $filter['t.label_compte'] = $search_label_account; $param .= '&search_label_compte=' . urlencode($search_label_account); } + if (!empty($search_mvt_num)) { + $filter['t.piece_num'] = $search_mvt_num; + $param .= '&search_mvt_num=' . urlencode($search_mvt_num); + } if (!empty($search_doc_ref)) { $filter['t.doc_ref'] = $search_doc_ref; $param .= '&search_doc_ref=' . urlencode($search_doc_ref); @@ -289,10 +295,11 @@ if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->suppri */ $formaccounting = new FormAccounting($db); +$formfile = new FormFile($db); $formother = new FormOther($db); $form = new Form($db); -$title_page = $langs->trans("Bookkeeping").' '.strtolower($langs->trans("By")).' '.strtolower($langs->trans("AccountAccounting")); +$title_page = $langs->trans("Operations").' - '.$langs->trans("VueByAccountAccounting").' ('.$langs->trans("Bookkeeping").')'; llxHeader('', $title_page); @@ -356,7 +363,7 @@ if ($action == 'delbookkeepingyear') { 'default' => $deljournal ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); print $formconfirm; } @@ -368,16 +375,19 @@ if ($optioncss != '') print ''; print ''; print ''; -print ''; -$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('VueByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss'=>'marginleftonly btnTitleSelected')); + +$newcardbutton .= '   '; + $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', './card.php?action=create'); 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($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$newcardbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$newcardbutton, '', $limit, 0, 0, 1); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -392,10 +402,10 @@ $moreforfilter = ''; // Accountancy account $moreforfilter .= '
'; $moreforfilter .= $langs->trans('AccountAccounting').': '; -$moreforfilter .= '
'; +$moreforfilter .= '
'; $moreforfilter .= $langs->trans('From').' '; $moreforfilter .= $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, 'maxwidth200'); -$moreforfilter .= $langs->trans('to').' '; +$moreforfilter .= ' '.$langs->trans('to').' '; $moreforfilter .= $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, 'maxwidth200'); $moreforfilter .= '
'; $moreforfilter .= '
'; @@ -423,12 +433,10 @@ if (!empty($arrayfields['t.code_journal']['checked'])) { if (!empty($arrayfields['t.doc_date']['checked'])) { print '
'; } @@ -695,10 +703,10 @@ while ($i < min($num, $limit)) print ''; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index 0b3d98a2742..321ef282dff 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -147,7 +147,7 @@ $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; $sql .= " bk.subledger_account, bk.numero_compte , bk.label_compte, bk.debit, "; $sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk"; -$sql .= " WHERE (bk.subledger_account = '".$object->code_compta."' AND bk.numero_compte = '".$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER."' )"; +$sql .= " WHERE (bk.subledger_account = '".$db->escape($object->code_compta)."' AND bk.numero_compte = '".$db->escape($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)."' )"; /* if (dol_strlen($search_date_start) || dol_strlen($search_date_end)) { diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index c6ab2fa81d6..144c2595d25 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -146,7 +146,7 @@ $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; $sql .= " bk.subledger_account, bk.numero_compte , bk.label_compte, bk.debit, "; $sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code, bk.date_validated "; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk"; -$sql .= " WHERE (bk.subledger_account = '".$object->code_compta_fournisseur."' AND bk.numero_compte = '".$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER."' )"; +$sql .= " WHERE (bk.subledger_account = '".$db->escape($object->code_compta_fournisseur)."' AND bk.numero_compte = '".$db->escape($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER)."' )"; if (dol_strlen($search_date_start) || dol_strlen($search_date_end)) { $sql .= " AND (bk.doc_date BETWEEN '".$db->idate($search_date_start)."' AND '".$db->idate($search_date_end)."' )"; } diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index fa8cd088604..0204602438f 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -809,8 +809,8 @@ class AccountancyExport foreach ($objectLines as $line) { $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); - $date_doc = dol_print_date($line->doc_date, '%Y%m%d'); - $date_valid = dol_print_date($line->date_validated, '%Y%m%d'); + $date_document = dol_print_date($line->doc_date, '%Y%m%d'); + $date_validation = dol_print_date($line->date_validated, '%Y%m%d'); // FEC:JournalCode print $line->code_journal.$separator; @@ -822,25 +822,25 @@ class AccountancyExport print $line->piece_num.$separator; // FEC:EcritureDate - print $date_creation.$separator; + print $date_document . $separator; // FEC:CompteNum print $line->numero_compte.$separator; // FEC:CompteLib - print $line->label_compte.$separator; + print dol_string_unaccent($line->label_compte) . $separator; // FEC:CompAuxNum print $line->subledger_account.$separator; // FEC:CompAuxLib - print $line->subledger_label.$separator; + print dol_string_unaccent($line->subledger_label) . $separator; // FEC:PieceRef print $line->doc_ref.$separator; // FEC:PieceDate - print $date_doc.$separator; + print dol_string_unaccent($date_creation) . $separator; // FEC:EcritureLib print $line->label_operation.$separator; @@ -858,7 +858,7 @@ class AccountancyExport print $line->date_lettering.$separator; // FEC:ValidDate - print $date_valid.$separator; + print $date_validation . $separator; // FEC:Montantdevise print $line->multicurrency_amount.$separator; @@ -1160,7 +1160,8 @@ class AccountancyExport // TYPE C if ($last_codeinvoice != $line->doc_ref) { //recherche societe en fonction de son code client - $sql = "SELECT code_client, fk_forme_juridique, nom, address, zip, town, fk_pays, phone, siret FROM ".MAIN_DB_PREFIX."societe WHERE code_client = '".$line->thirdparty_code."'"; + $sql = "SELECT code_client, fk_forme_juridique, nom, address, zip, town, fk_pays, phone, siret FROM ".MAIN_DB_PREFIX."societe"; + $sql .= " WHERE code_client = '".$this->db->escape($line->thirdparty_code)."'"; $resql = $this->db->query($sql); if ($resql && $this->db->num_rows($resql) > 0) diff --git a/htdocs/accountancy/class/accountancysystem.class.php b/htdocs/accountancy/class/accountancysystem.class.php index 719d33c8574..c2f3468016c 100644 --- a/htdocs/accountancy/class/accountancysystem.class.php +++ b/htdocs/accountancy/class/accountancysystem.class.php @@ -101,7 +101,7 @@ class AccountancySystem $sql .= " FROM ".MAIN_DB_PREFIX."accounting_system as a"; $sql .= " WHERE"; if ($rowid) { - $sql .= " a.rowid = '".$rowid."'"; + $sql .= " a.rowid = ".((int) $rowid); } elseif ($ref) { $sql .= " a.pcg_version = '".$this->db->escape($ref)."'"; } diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 6a3fa8e7998..199899f89d5 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -448,9 +448,10 @@ class AccountingAccount extends CommonObject * @param int $notooltip 1=Disable tooltip * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @param int $withcompletelabel 0=Short label (field short label), 1=Complete label (field label) + * @param string $option 'ledger', 'journals', 'accountcard' * @return string String with URL */ - public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $withcompletelabel = 0) + public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $withcompletelabel = 0, $option = '') { global $langs, $conf, $user; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -459,7 +460,16 @@ class AccountingAccount extends CommonObject $result = ''; - $url = DOL_URL_ROOT.'/accountancy/admin/card.php?id='.$this->id; + if (empty($option) || $option == 'ledger') { + $url = DOL_URL_ROOT . '/accountancy/bookkeeping/listbyaccount.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; + $labelurl = $langs->trans("ShowAccountingAccountInLedger"); + } elseif ($option == 'journals') { + $url = DOL_URL_ROOT . '/accountancy/bookkeeping/list.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; + $labelurl = $langs->trans("ShowAccountingAccountInJournals"); + } elseif ($option == 'accountcard') { + $url = DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id; + $labelurl = $langs->trans("ShowAccountingAccount"); + } // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); @@ -476,7 +486,7 @@ class AccountingAccount extends CommonObject $labeltoshow = $this->labelshort; } - $label = ''.$langs->trans("ShowAccountingAccount").''; + $label = ''.$labelurl.''; if (!empty($this->account_number)) $label .= '
'.$langs->trans('AccountAccounting').': '.length_accountg($this->account_number); if (!empty($labeltoshow)) @@ -488,7 +498,7 @@ class AccountingAccount extends CommonObject { if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label = $langs->trans("ShowAccoutingAccount"); + $label = $labelurl; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index 6067f557cfb..882eee71769 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -108,7 +108,7 @@ class AccountingJournal extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal"; $sql .= " WHERE"; if ($rowid) { - $sql .= " rowid = ".(int) $rowid; + $sql .= " rowid = ".((int) $rowid); } elseif ($journal_code) { $sql .= " code = '".$this->db->escape($journal_code)."'"; diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 1c377e70192..f5f4bf80221 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -2,7 +2,7 @@ /* Copyright (C) 2014-2017 Olivier Geffroy * Copyright (C) 2015-2017 Alexandre Spangaro * Copyright (C) 2015-2017 Florian Henry - * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2018-2020 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 @@ -57,80 +57,80 @@ class BookKeeping extends CommonObject */ public $id; - /** - * @var string Date of source document, in db date NOT NULL - */ + /** + * @var string Date of source document, in db date NOT NULL + */ public $doc_date; - /** - * @var int Deadline for payment - */ + /** + * @var int Deadline for payment + */ public $date_lim_reglement; - /** - * @var string doc_type - */ - public $doc_type; + /** + * @var string doc_type + */ + public $doc_type; - /** - * @var string doc_ref - */ + /** + * @var string doc_ref + */ public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; - /** - * @var string thirdparty code - */ - public $thirdparty_code; + /** + * @var string thirdparty code + */ + public $thirdparty_code; - /** - * @var string subledger account - */ + /** + * @var string subledger account + */ public $subledger_account; - /** - * @var string subledger label - */ + /** + * @var string subledger label + */ public $subledger_label; - /** - * @var string doc_type - */ + /** + * @var string doc_type + */ public $numero_compte; - /** - * @var string label compte - */ - public $label_compte; + /** + * @var string label compte + */ + public $label_compte; - /** - * @var string label operation - */ - public $label_operation; + /** + * @var string label operation + */ + public $label_operation; - /** - * @var float FEC:Debit - */ + /** + * @var float FEC:Debit + */ public $debit; - /** - * @var float FEC:Credit - */ + /** + * @var float FEC:Credit + */ public $credit; - /** - * @var float FEC:Amount (Not necessary) - * @deprecated Use $amount - */ + /** + * @var float FEC:Amount (Not necessary) + * @deprecated Use $amount + */ public $montant; /** @@ -138,34 +138,34 @@ class BookKeeping extends CommonObject */ public $amount; - /** - * @var string FEC:Sens (Not necessary) - */ + /** + * @var string FEC:Sens (Not necessary) + */ public $sens; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; - /** - * @var string key for import - */ + /** + * @var string key for import + */ public $import_key; - /** - * @var string code journal - */ + /** + * @var string code journal + */ public $code_journal; - /** - * @var string label journal - */ + /** + * @var string label journal + */ public $journal_label; - /** - * @var int accounting transaction id - */ + /** + * @var int accounting transaction id + */ public $piece_num; /** @@ -179,8 +179,8 @@ class BookKeeping extends CommonObject * * @param DoliDb $db Database handler */ - public function __construct(DoliDB $db) - { + public function __construct(DoliDB $db) + { $this->db = $db; } @@ -191,8 +191,8 @@ class BookKeeping extends CommonObject * @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) - { + public function create(User $user, $notrigger = false) + { global $conf, $langs; dol_syslog(__METHOD__, LOG_DEBUG); @@ -504,11 +504,11 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, Id of created object if OK */ - public function createStd(User $user, $notrigger = false, $mode = '') - { + public function createStd(User $user, $notrigger = false, $mode = '') + { global $conf, $langs; - $langs->loadLangs(array("accountancy", "bills", "compta")); + $langs->loadLangs(array("accountancy", "bills", "compta")); dol_syslog(__METHOD__, LOG_DEBUG); @@ -578,7 +578,7 @@ class BookKeeping extends CommonObject $now = dol_now(); // Check parameters - $this->journal_label = $langs->trans($this->journal_label); + $this->journal_label = $langs->trans($this->journal_label); // Insert request $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' ('; @@ -673,8 +673,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetch($id, $ref = null, $mode = '') - { + public function fetch($id, $ref = null, $mode = '') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -771,8 +771,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, >=0 if OK */ - public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') - { + public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -904,11 +904,11 @@ class BookKeeping extends CommonObject * @param int $offset Offset limit * @param array $filter Filter array * @param string $filtermode Filter mode (AND or OR) - * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) + * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) * @return int <0 if KO, >0 if OK */ - public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) - { + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -940,7 +940,7 @@ class BookKeeping extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.date_lim_reglement,"; $sql .= " t.tms as date_modification,"; - $sql .= " t.date_export"; + $sql .= " t.date_export"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter $sqlwhere = array(); @@ -960,8 +960,8 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.tms>=' || $key == 't.tms<=') { $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; - } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { - $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; + } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -970,9 +970,9 @@ class BookKeeping extends CommonObject } } $sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')'; - if ($showAlreadyExportMovements == 0) { - $sql .= " AND t.date_export IS NULL"; - } + if ($showAlreadyExportMovements == 0) { + $sql .= " AND t.date_export IS NULL"; + } if (count($sqlwhere) > 0) { $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } @@ -1020,7 +1020,7 @@ class BookKeeping extends CommonObject $line->date_creation = $this->db->jdate($obj->date_creation); $line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement); $line->date_modification = $this->db->jdate($obj->date_modification); - $line->date_export = $this->db->jdate($obj->date_export); + $line->date_export = $this->db->jdate($obj->date_export); $this->lines[] = $line; @@ -1133,8 +1133,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode ('' or _tmp') * @return int <0 if KO, >0 if OK */ - public function update(User $user, $notrigger = false, $mode = '') - { + public function update(User $user, $notrigger = false, $mode = '') + { $error = 0; dol_syslog(__METHOD__, LOG_DEBUG); @@ -1300,8 +1300,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function delete(User $user, $notrigger = false, $mode = '') - { + public function delete(User $user, $notrigger = false, $mode = '') + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1348,8 +1348,8 @@ class BookKeeping extends CommonObject * @param string $importkey Import key * @return int Result */ - public function deleteByImportkey($importkey) - { + public function deleteByImportkey($importkey) + { $this->db->begin(); // first check if line not yet in bookkeeping @@ -1379,11 +1379,11 @@ class BookKeeping extends CommonObject * @param int $delmonth Month * @return int <0 if KO, >0 if OK */ - public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) - { - global $langs; + public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) + { + global $langs; - if (empty($delyear) && empty($journal)) + if (empty($delyear) && empty($journal)) { $this->error = 'ErrorOneFieldRequired'; return -1; @@ -1428,8 +1428,8 @@ class BookKeeping extends CommonObject * @param int $piecenum Piecenum to delete * @return int Result */ - public function deleteMvtNum($piecenum) - { + public function deleteMvtNum($piecenum) + { global $conf; $this->db->begin(); @@ -1463,8 +1463,8 @@ class BookKeeping extends CommonObject * @param int $fromid Id of object to clone * @return int New id of clone */ - public function createFromClone(User $user, $fromid) - { + public function createFromClone(User $user, $fromid) + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1511,8 +1511,8 @@ class BookKeeping extends CommonObject * * @return void */ - public function initAsSpecimen() - { + public function initAsSpecimen() + { global $user; $now = dol_now(); @@ -1548,8 +1548,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchPerMvt($piecenum, $mode = '') - { + public function fetchPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation"; @@ -1613,8 +1613,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchAllPerMvt($piecenum, $mode = '') - { + public function fetchAllPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1664,16 +1664,16 @@ class BookKeeping extends CommonObject return 1; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Export bookkeeping * * @param string $model Model * @return int Result */ - public function export_bookkeeping($model = 'ebp') - { - // phpcs:enable + public function export_bookkeeping($model = 'ebp') + { + // phpcs:enable global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1739,10 +1739,10 @@ class BookKeeping extends CommonObject $this->db->begin(); - if ($direction == 0) + if ($direction == 0) { $next_piecenum = $this->getNextNumMvt(); - $now = dol_now(); + $now = dol_now(); if ($next_piecenum < 0) { $error++; @@ -1755,14 +1755,14 @@ class BookKeeping extends CommonObject $sql .= ' doc_ref, fk_doc, fk_docdet, entity, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, '.$next_piecenum.", '".$this->db->idate($now)."'"; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$this->db->escape($piece_num); + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num); $resql = $this->db->query($sql); if (!$resql) { $error++; $this->errors[] = 'Error '.$this->db->lasterror(); dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$this->db->escape($piece_num); + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num); $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -1770,7 +1770,7 @@ class BookKeeping extends CommonObject dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } } elseif ($direction == 1) { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num); $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -1785,14 +1785,14 @@ class BookKeeping extends CommonObject $sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,'; $sql .= ' numero_compte, label_compte, label_operation, debit, credit,'; $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.$piece_num; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.((int) $piece_num); $resql = $this->db->query($sql); if (!$resql) { $error++; $this->errors[] = 'Error '.$this->db->lasterror(); dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.$piece_num; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num); $resql = $this->db->query($sql); if (!$resql) { $error++; @@ -1819,22 +1819,22 @@ class BookKeeping extends CommonObject */ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Return list of accounts with label by chart of accounts - * - * @param string $selectid Preselected chart of accounts - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param array $event Event options - * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) - * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number - * @return string String with HTML select - */ - public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') - { - // phpcs:enable + * Return list of accounts with label by chart of accounts + * + * @param string $selectid Preselected chart of accounts + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) + * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number + * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number + * @return string String with HTML select + */ + public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') + { + // phpcs:enable global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -1891,7 +1891,7 @@ class BookKeeping extends CommonObject return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of a root accounting account * @@ -1900,7 +1900,7 @@ class BookKeeping extends CommonObject */ public function get_compte_racine($account = null) { - // phpcs:enable + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; @@ -1910,7 +1910,7 @@ class BookKeeping extends CommonObject $sql .= " AND asy.rowid = ".$pcgver; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid"; - $sql .= " WHERE aa.account_number = '".$account."'"; + $sql .= " WHERE aa.account_number = '".$this->db->escape($account)."'"; $sql .= " AND parent.active = 1"; $sql .= " AND root.active = 1"; $sql .= " AND aa.entity IN (".getEntity('accountancy').")"; @@ -1932,24 +1932,24 @@ class BookKeeping extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of accounting account * * @param string $account Accounting account * @return string Account desc */ - public function get_compte_desc($account = null) - { - // phpcs:enable + public function get_compte_desc($account = null) + { + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version, cat.label as category"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND aa.account_number = '".$account."'"; - $sql .= " AND asy.rowid = ".$pcgver; + $sql .= " AND aa.account_number = '".$this->db->escape($account)."'"; + $sql .= " AND asy.rowid = ".((int) $pcgver); $sql .= " AND aa.active = 1"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid"; $sql .= " WHERE aa.entity IN (".getEntity('accountancy').")"; @@ -1989,13 +1989,13 @@ class BookKeepingLine public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; public $thirdparty_code; @@ -2006,13 +2006,27 @@ class BookKeepingLine public $label_operation; public $debit; public $credit; - public $montant; - public $sens; - public $lettering_code; /** - * @var int ID - */ + * @var float Amount + * @deprecated see $amount + */ + public $montant; + + /** + * @var float Amount + */ + public $amount; + + /** + * @var string Sens + */ + public $sens; + public $lettering_code; + + /** + * @var int ID + */ public $fk_user_author; public $import_key; @@ -2021,17 +2035,17 @@ class BookKeepingLine public $piece_num; /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; /** * @var integer|string $date_modification; */ - public $date_modification; + public $date_modification; - /** - * @var integer|string $date_export; - */ - public $date_export; + /** + * @var integer|string $date_export; + */ + public $date_export; } diff --git a/htdocs/accountancy/class/lettering.class.php b/htdocs/accountancy/class/lettering.class.php index d663e0ec9c4..cfe9bf635ae 100644 --- a/htdocs/accountancy/class/lettering.class.php +++ b/htdocs/accountancy/class/lettering.class.php @@ -68,11 +68,11 @@ class Lettering extends BookKeeping $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) "; $sql .= " WHERE ( "; if ($object->code_compta != "") - $sql .= " bk.subledger_account = '".$object->code_compta."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' "; if ($object->code_compta != "" && $object->code_compta_fournisseur != "") $sql .= " OR "; if ($object->code_compta_fournisseur != "") - $sql .= " bk.subledger_account = '".$object->code_compta_fournisseur."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' "; $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) "; $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) "; @@ -95,19 +95,19 @@ class Lettering extends BookKeeping $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = payf.fk_bank AND bk.code_journal='".$obj->code_journal."')"; - $sql .= " WHERE payfacf.fk_paiementfourn = '".$obj->url_id."' "; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = payf.fk_bank AND bk.code_journal='".$this->db->escape($obj->code_journal)."')"; + $sql .= " WHERE payfacf.fk_paiementfourn = '".$this->db->escape($obj->url_id)."' "; $sql .= " AND facf.entity = ".$conf->entity; $sql .= " AND code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") "; $sql .= " AND ( "; if ($object->code_compta != "") { - $sql .= " bk.subledger_account = '".$object->code_compta."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' "; } if ($object->code_compta != "" && $object->code_compta_fournisseur != "") { $sql .= " OR "; } if ($object->code_compta_fournisseur != "") { - $sql .= " bk.subledger_account = '".$object->code_compta_fournisseur."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' "; } $sql .= " ) "; @@ -129,13 +129,13 @@ class Lettering extends BookKeeping $sql .= " AND facf.entity = ".$conf->entity; $sql .= " AND ( "; if ($object->code_compta != "") { - $sql .= " bk.subledger_account = '".$object->code_compta."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' "; } if ($object->code_compta != "" && $object->code_compta_fournisseur != "") { $sql .= " OR "; } if ($object->code_compta_fournisseur != "") { - $sql .= " bk.subledger_account = '".$object->code_compta_fournisseur."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' "; } $sql .= ") "; @@ -154,19 +154,19 @@ class Lettering extends BookKeeping $sql .= " FROM ".MAIN_DB_PREFIX."facture fac "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = pay.fk_bank AND bk.code_journal='".$obj->code_journal."')"; - $sql .= " WHERE payfac.fk_paiement = '".$obj->url_id."' "; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = pay.fk_bank AND bk.code_journal='".$this->db->escape($obj->code_journal)."')"; + $sql .= " WHERE payfac.fk_paiement = '".$this->db->escape($obj->url_id)."' "; $sql .= " AND bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") "; $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND ( "; if ($object->code_compta != "") { - $sql .= " bk.subledger_account = '".$object->code_compta."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' "; } if ($object->code_compta != "" && $object->code_compta_fournisseur != "") { $sql .= " OR "; } if ($object->code_compta_fournisseur != "") { - $sql .= " bk.subledger_account = '".$object->code_compta_fournisseur."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' "; } $sql .= " )"; @@ -188,13 +188,13 @@ class Lettering extends BookKeeping $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND ( "; if ($object->code_compta != "") { - $sql .= " bk.subledger_account = '".$object->code_compta."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' "; } if ($object->code_compta != "" && $object->code_compta_fournisseur != "") { $sql .= " OR "; } if ($object->code_compta_fournisseur != "") { - $sql .= " bk.subledger_account = '".$object->code_compta_fournisseur."' "; + $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' "; } $sql .= " ) "; @@ -238,7 +238,7 @@ class Lettering extends BookKeeping $lettre = 'AAA'; $sql = "SELECT DISTINCT lettering_code FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE "; - $sql .= " lettering_code != '' ORDER BY lettering_code DESC limit 1; "; + $sql .= " lettering_code != '' ORDER BY lettering_code DESC limit 1"; $result = $this->db->query($sql); if ($result) { @@ -252,7 +252,7 @@ class Lettering extends BookKeeping } $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE "; - $sql .= " rowid IN (".implode(',', $ids).") AND date_validated IS NULL "; + $sql .= " rowid IN (".implode(',', $ids).") AND date_validated IS NULL"; $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); @@ -272,7 +272,7 @@ class Lettering extends BookKeeping if (!$error) { $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET"; - $sql .= " lettering_code='".$lettre."'"; + $sql .= " lettering_code='".$this->db->escape($lettre)."'"; $sql .= " , date_lettering = '".$this->db->idate($now)."'"; // todo correct date it's false $sql .= " WHERE rowid IN (".implode(',', $ids).") AND date_validated IS NULL "; $this->db->begin(); diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php index 34a23b377b9..ed8f347a177 100644 --- a/htdocs/accountancy/customer/card.php +++ b/htdocs/accountancy/customer/card.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page $langs->loadLangs(array("bills", "accountancy")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 452db02d30b..1a5098bda38 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -131,9 +131,9 @@ if ($action == 'validatehistory') { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as l ON f.rowid = l.fk_facture"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$chartaccountcode."' AND aa2.entity = ".$conf->entity; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$chartaccountcode."' AND aa3.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa2.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa3.entity = ".$conf->entity; $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND l.product_type <= 2"; @@ -256,6 +256,10 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; +// Define begin binding date +if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) { + $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; +} $sql .= " AND f.fk_statut > 0"; $sql .= " AND fd.product_type <= 2"; $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy @@ -330,6 +334,10 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; +// Define begin binding date +if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) { + $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; +} $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; $sql .= " AND fd.product_type <= 2"; @@ -394,7 +402,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. } print ''; - $sql = "SELECT '".$langs->trans("TotalVente")."' AS total,"; + $sql = "SELECT '".$db->escape($langs->trans("TotalVente"))."' AS total,"; for ($i = 1; $i <= 12; $i++) { $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; if ($j > 12) $j -= 12; @@ -405,6 +413,10 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; + // Define begin binding date + if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) { + $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + } $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; $sql .= " AND fd.product_type <= 2"; @@ -447,7 +459,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. } print ''; - $sql = "SELECT '".$langs->trans("Vide")."' AS marge,"; + $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,"; for ($i = 1; $i <= 12; $i++) { $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; if ($j > 12) $j -= 12; @@ -458,6 +470,10 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; + // Define begin binding date + if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) { + $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + } $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; $sql .= " AND fd.product_type <= 2"; diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index af98dc14653..5d35040f6ab 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -61,13 +61,13 @@ $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -$offset = $limit * $page; if (!$sortfield) $sortfield = "f.datef, f.ref, fd.rowid"; if (!$sortorder) { @@ -92,8 +92,8 @@ $formaccounting = new FormAccounting($db); // 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 { - $search_societe=''; - $search_lineid = ''; + $search_societe = ''; + $search_lineid = ''; $search_ref = ''; $search_invoice = ''; $search_label = ''; @@ -176,7 +176,8 @@ print ' - - - global->MAIN_USE_METEO_WITH_PERCENTAGE)) { - print '
'; - print '
'; - print img_weather($text, 0, $options); - print '= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL0.' %'; - print '
'; - print img_weather($text, 1, $options); - print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL1.' %'; - print '
'; - print img_weather($text, 2, $options); - print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL2.' %'; - print '
'; - print img_weather($text, 3, $options); - print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; - print '
'; - print img_weather($text, 4, $options); - print '> '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; - print '
'; - print '
'; + '; - print '
'; - print img_weather($text, 0, $options); - print '= '.$level0; - print '
'; - print img_weather($text, 1, $options); - print '<= '.$level1; - print '
'; - print img_weather($text, 2, $options); - print '<= '.$level2; - print '
'; - print img_weather($text, 3, $options); - print '<= '.$level3; - print '
'; - print img_weather($text, 4, $options); - print '> '.$level3; - print '
'; - print ''; + if (!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + print '
'; + print '
'; + print img_weather($text, 0, $options); + print ' <= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL0.' %'; + print '
'; + print img_weather($text, 1, $options); + print ' <= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL1.' %'; + print '
'; + print img_weather($text, 2, $options); + print ' <= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL2.' %'; + print '
'; + print img_weather($text, 3, $options); + print ' <= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print img_weather($text, 4, $options); + print ' > '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print '
'; + } else { + print '
'; + print '
'; + print img_weather($text, 0, $options); + print ' <= '.$level0; + print '
'; + print img_weather($text, 1, $options); + print ' <= '.$level1; + print '
'; + print img_weather($text, 2, $options); + print ' <= '.$level2; + print '
'; + print img_weather($text, 3, $options); + print ' <= '.$level3; + print '
'; + print img_weather($text, 4, $options); + print ' > '.$level3; + print '
'; + print '
'; + } } } -print ''; if ($action == 'edit') { print '
'; diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index 23a781d8f31..8df2c1d36a4 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -91,11 +91,7 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -if (! empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { - $taborder = array(9, 0, 4, 3, 2, 0, 1, 8, 19, 16, 39, 27, 40, 38, 0, 5, 11, 0, 32, 33, 34, 0, 6, 0, 29, 0, 7, 24, 28, 17, 35, 36, 0, 10, 23, 12, 13, 0, 14, 0, 22, 20, 18, 21, 41, 0, 15, 30, 0, 37, 0, 25, 0); -} else { - $taborder = array(9, 0, 4, 3, 2, 0, 1, 8, 19, 16, 27, 38, 0, 5, 11, 0, 32, 33, 34, 0, 6, 0, 29, 0, 7, 24, 28, 17, 35, 36, 0, 10, 23, 12, 13, 0, 14, 0, 22, 20, 18, 21, 41, 0, 15, 30, 0, 37, 0, 25, 0); -} +$taborder = array(9, 0, 4, 3, 2, 0, 1, 8, 19, 16, 39, 27, 40, 38, 0, 5, 11, 0, 32, 33, 34, 0, 6, 0, 29, 0, 7, 24, 28, 17, 35, 36, 0, 10, 23, 12, 13, 0, 14, 0, 22, 20, 18, 21, 41, 0, 15, 30, 0, 37, 0, 25, 0); // Name of SQL tables of dictionaries $tabname = array(); @@ -492,8 +488,8 @@ $tabcond[35] = !empty($conf->expensereport->enabled); $tabcond[36] = !empty($conf->expensereport->enabled); $tabcond[37] = !empty($conf->product->enabled); $tabcond[38] = !empty($conf->socialnetworks->enabled); -$tabcond[39] = (! empty($conf->societe->enabled) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)); -$tabcond[40] = !empty($conf->societe->enabled); +$tabcond[39] = (!empty($conf->societe->enabled) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && !empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)); +$tabcond[40] = (!empty($conf->societe->enabled) && !empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)); $tabcond[41] = !empty($conf->intracommreport->enabled); // List of help for fields @@ -524,7 +520,7 @@ $tabhelp[23] = array('revenuestamp_type'=>'FixedOrPercent'); $tabhelp[24] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[25] = array('code'=>$langs->trans('EnterAnyCode')); //$tabhelp[26] = array('code'=>$langs->trans("EnterAnyCode")); -$tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode"),'picto'=>$langs->trans("PictoHelp")); +$tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode"), 'picto'=>$langs->trans("PictoHelp")); $tabhelp[28] = array('affect'=>$langs->trans("FollowedByACounter"), 'delay'=>$langs->trans("MinimumNoticePeriod"), 'newbymonth'=>$langs->trans("NbAddedAutomatically")); $tabhelp[29] = array('code'=>$langs->trans("EnterAnyCode"), 'percent'=>$langs->trans("OpportunityPercent"), 'position'=>$langs->trans("PositionIntoComboList")); $tabhelp[30] = array('code'=>$langs->trans("EnterAnyCode"), 'name'=>$langs->trans("LabelName"), 'paper_size'=>$langs->trans("LabelPaperSize")); @@ -537,7 +533,7 @@ $tabhelp[36] = array('range_ik'=>$langs->trans('PrevRangeToThisRange')); $tabhelp[37] = array('code'=>$langs->trans("EnterAnyCode"), 'unit_type' => $langs->trans('MeasuringUnitTypeDesc'), 'scale' => $langs->trans('MeasuringScaleDesc')); $tabhelp[38] = array('code'=>$langs->trans("EnterAnyCode"), 'url' => $langs->trans('UrlSocialNetworksDesc'), 'icon' => $langs->trans('FafaIconSocialNetworksDesc')); $tabhelp[39] = array('code'=>$langs->trans("EnterAnyCode")); -$tabhelp[40] = array('code'=>$langs->trans("EnterAnyCode"),'picto'=>$langs->trans("PictoHelp")); +$tabhelp[40] = array('code'=>$langs->trans("EnterAnyCode"), 'picto'=>$langs->trans("PictoHelp")); $tabhelp[41] = array('code'=>$langs->trans("EnterAnyCode")); // List of check for fields (NOT USED YET) @@ -591,9 +587,9 @@ complete_dictionary_with_modules($taborder, $tabname, $tablib, $tabsql, $tabsqls // Defaut sortorder if (empty($sortfield)) { - $tmp1 = explode(',', $tabsqlsort[$id]); - $tmp2 = explode(' ', $tmp1[0]); - $sortfield = preg_replace('/^.*\./', '', $tmp2[0]); + $tmp1 = explode(',', $tabsqlsort[$id]); + $tmp2 = explode(' ', $tmp1[0]); + $sortfield = preg_replace('/^.*\./', '', $tmp2[0]); } // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") @@ -601,27 +597,27 @@ $elementList = array(); $sourceList = array(); if ($id == 11) { - $elementList = array( - '' => '', - 'societe' => $langs->trans('ThirdParty'), - // 'proposal' => $langs->trans('Proposal'), - // 'order' => $langs->trans('Order'), - // 'invoice' => $langs->trans('Bill'), - 'supplier_proposal' => $langs->trans('SupplierProposal'), - 'order_supplier' => $langs->trans('SupplierOrder'), - 'invoice_supplier' => $langs->trans('SupplierBill'), - // 'intervention' => $langs->trans('InterventionCard'), - // 'contract' => $langs->trans('Contract'), - 'project' => $langs->trans('Project'), - 'project_task' => $langs->trans('Task'), - 'agenda' => $langs->trans('Agenda'), - 'dolresource' => $langs->trans('Resource'), - // old deprecated - 'propal' => $langs->trans('Proposal'), - 'commande' => $langs->trans('Order'), - 'facture' => $langs->trans('Bill'), - 'fichinter' => $langs->trans('InterventionCard'), - 'contrat' => $langs->trans('Contract'), + $elementList = array( + '' => '', + 'societe' => $langs->trans('ThirdParty'), + // 'proposal' => $langs->trans('Proposal'), + // 'order' => $langs->trans('Order'), + // 'invoice' => $langs->trans('Bill'), + 'supplier_proposal' => $langs->trans('SupplierProposal'), + 'order_supplier' => $langs->trans('SupplierOrder'), + 'invoice_supplier' => $langs->trans('SupplierBill'), + // 'intervention' => $langs->trans('InterventionCard'), + // 'contract' => $langs->trans('Contract'), + 'project' => $langs->trans('Project'), + 'project_task' => $langs->trans('Task'), + 'agenda' => $langs->trans('Agenda'), + 'dolresource' => $langs->trans('Resource'), + // old deprecated + 'propal' => $langs->trans('Proposal'), + 'commande' => $langs->trans('Order'), + 'facture' => $langs->trans('Bill'), + 'fichinter' => $langs->trans('InterventionCard'), + 'contrat' => $langs->trans('Contract'), ); if (!empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); @@ -657,329 +653,329 @@ if ($id == 10) if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) { - $search_country_id = ''; - $search_code = ''; + $search_country_id = ''; + $search_code = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - foreach ($listfield as $f => $value) - { - // Discard check of mandatory fields for country for some tables - if ($value == 'country_id' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryVAT', 'DictionaryRegion', 'DictionaryCompanyType', 'DictionaryHolidayTypes', 'DictionaryRevenueStamp', 'DictionaryAccountancysystem', 'DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory - if ($value == 'country' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryCanton', 'DictionaryCompanyType', 'DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory - // Discard check of mandatory fiedls for other fields - if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; - if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; - if ($value == 'color' && empty($_POST['color'])) continue; + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + // Discard check of mandatory fields for country for some tables + if ($value == 'country_id' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryVAT', 'DictionaryRegion', 'DictionaryCompanyType', 'DictionaryHolidayTypes', 'DictionaryRevenueStamp', 'DictionaryAccountancysystem', 'DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory + if ($value == 'country' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryCanton', 'DictionaryCompanyType', 'DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory + // Discard check of mandatory fiedls for other fields + if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; + if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; + if ($value == 'color' && empty($_POST['color'])) continue; if ($value == 'formula' && empty($_POST['formula'])) continue; if ($value == 'dayrule' && empty($_POST['dayrule'])) continue; if ($value == 'sortorder') continue; // For a column name 'sortorder', we use the field name 'position' if ((!isset($_POST[$value]) || $_POST[$value] == '') - && (!in_array($listfield[$f], array('decalage', 'module', 'accountancy_code', 'accountancy_code_sell', 'accountancy_code_buy', 'tracking', 'picto')) // Fields that are not mandatory - && (!($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 - ) + && (!in_array($listfield[$f], array('decalage', 'module', 'accountancy_code', 'accountancy_code_sell', 'accountancy_code_buy', 'tracking', 'picto')) // Fields that are not mandatory + && (!($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 + ) ) { - $ok = 0; - $fieldnamekey = $listfield[$f]; - // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; - if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; - if ($fieldnamekey == 'nbjour') $fieldnamekey = 'NbOfDays'; - if ($fieldnamekey == 'decalage') $fieldnamekey = 'Offset'; - if ($fieldnamekey == 'module') $fieldnamekey = 'Module'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; - if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; - if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; - if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; - if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; - if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; - if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; + $ok = 0; + $fieldnamekey = $listfield[$f]; + // We take translate key of field + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; + if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; + if ($fieldnamekey == 'nbjour') $fieldnamekey = 'NbOfDays'; + if ($fieldnamekey == 'decalage') $fieldnamekey = 'Offset'; + if ($fieldnamekey == 'module') $fieldnamekey = 'Module'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; + if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; + if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; + if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; if ($fieldnamekey == 'revenuestamp_type') $fieldnamekey = 'TypeOfRevenueStamp'; if ($fieldnamekey == 'use_default') $fieldnamekey = 'UseByDefault'; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - } - } - // Other checks - if (GETPOST('actionadd') && $tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"], array('system', 'systemauto'))) { - $ok = 0; - setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); - } - if (GETPOSTISSET("code")) - { - if (GETPOST("code") == '0') - { - $ok = 0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + // Other checks + if (GETPOST('actionadd') && $tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"], array('system', 'systemauto'))) { + $ok = 0; + setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); + } + if (GETPOSTISSET("code")) + { + if (GETPOST("code") == '0') + { + $ok = 0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } - if (GETPOSTISSET("country") && ($_POST["country"] == '0') && ($id != 2)) - { - if (in_array($tablib[$id], array('DictionaryCompanyType', 'DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries - { - $_POST["country"] = ''; - } else { - $ok = 0; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors'); - } - } - if ($id == 3 && !is_numeric($_POST["code"])) - { - $ok = 0; - setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric", $langs->transnoentities("Code")), null, 'errors'); - } + } + if (GETPOSTISSET("country") && ($_POST["country"] == '0') && ($id != 2)) + { + if (in_array($tablib[$id], array('DictionaryCompanyType', 'DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries + { + $_POST["country"] = ''; + } else { + $ok = 0; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors'); + } + } + if ($id == 3 && !is_numeric($_POST["code"])) + { + $ok = 0; + setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric", $langs->transnoentities("Code")), null, 'errors'); + } // Clean some parameters - if ((!empty($_POST["localtax1_type"]) || ($_POST['localtax1_type'] == '0')) && empty($_POST["localtax1"])) $_POST["localtax1"] = '0'; // If empty, we force to 0 - if ((!empty($_POST["localtax2_type"]) || ($_POST['localtax2_type'] == '0')) && empty($_POST["localtax2"])) $_POST["localtax2"] = '0'; // If empty, we force to 0 + if ((!empty($_POST["localtax1_type"]) || ($_POST['localtax1_type'] == '0')) && empty($_POST["localtax1"])) $_POST["localtax1"] = '0'; // If empty, we force to 0 + if ((!empty($_POST["localtax2_type"]) || ($_POST['localtax2_type'] == '0')) && empty($_POST["localtax2"])) $_POST["localtax2"] = '0'; // If empty, we force to 0 if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null - if ($id == 10 && isset($_POST["code"])) // Spaces are not allowed into code - { - $_POST["code"] = preg_replace('/\s/', '', $_POST["code"]); - } + if ($id == 10 && isset($_POST["code"])) // Spaces are not allowed into code + { + $_POST["code"] = preg_replace('/\s/', '', $_POST["code"]); + } - // If check ok and action add, add the line - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Get free id for insert - $newid = 0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid = ($obj->newid + 1); - } else { - dol_print_error($db); - } - } + // If check ok and action add, add the line + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Get free id for insert + $newid = 0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $tabrowid[$id].","; - $sql .= $tabfieldinsert[$id]; - $sql .= ",active)"; - $sql .= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",active)"; + $sql .= " VALUES("; - // List of values - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $newid.","; - $i = 0; - foreach ($listfieldinsert as $f => $value) - { - $keycode = $listfieldvalue[$i]; - if (empty($keycode)) $keycode = $value; + // List of values + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; + foreach ($listfieldinsert as $f => $value) + { + $keycode = $listfieldvalue[$i]; + if (empty($keycode)) $keycode = $value; - if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') { - $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); - } elseif ($value == 'entity') { - $_POST[$keycode] = getEntity($tabname[$id]); - } + if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') { + $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); + } elseif ($value == 'entity') { + $_POST[$keycode] = getEntity($tabname[$id]); + } - if ($i) $sql .= ","; + if ($i) $sql .= ","; - if ($keycode == 'sortorder') // For column name 'sortorder', we use the field name 'position' - { - $sql .= "'".(int) GETPOST('position', 'int')."'"; - } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + if ($keycode == 'sortorder') // For column name 'sortorder', we use the field name 'position' + { + $sql .= "'".(int) GETPOST('position', 'int')."'"; + } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } - $i++; - } - $sql .= ",1)"; + $i++; + } + $sql .= ",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST = array('id'=>$id); // Clean $_POST array, we keep only - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST = array('id'=>$id); // Clean $_POST array, we keep only + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // If verif ok and action modify, modify the line - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + // If verif ok and action modify, modify the line + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { - $sql .= $tabrowid[$id]."="; - $sql .= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - $keycode = $listfieldvalue[$i]; - if (empty($keycode)) $keycode = $field; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) + { + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + $keycode = $listfieldvalue[$i]; + if (empty($keycode)) $keycode = $field; - if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') { - $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); - } elseif ($field == 'entity') { - $_POST[$keycode] = getEntity($tabname[$id]); - } + if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') { + $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); + } elseif ($field == 'entity') { + $_POST[$keycode] = getEntity($tabname[$id]); + } - if ($i) $sql .= ","; - $sql .= $field."="; - if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' - { - $sql .= (int) GETPOST('position', 'int'); - } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + if ($i) $sql .= ","; + $sql .= $field."="; + if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' + { + $sql .= (int) GETPOST('position', 'int'); + } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } - $i++; - } - $sql .= " WHERE ".$rowidcol." = ".(int) $db->escape($rowid); - if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'"; + $i++; + } + $sql .= " WHERE ".$rowidcol." = ".(int) $db->escape($rowid); + if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (!$resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (!$resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_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 ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -997,28 +993,28 @@ llxHeader('', $title); $linkback = ''; if ($id) { - $title .= ' - '.$langs->trans($tablib[$id]); - $linkback = ''.$langs->trans("BackToDictionaryList").''; + $title .= ' - '.$langs->trans($tablib[$id]); + $linkback = ''.$langs->trans("BackToDictionaryList").''; } $titlepicto = 'title_setup'; if ($id == 10 && GETPOST('from') == 'accountancy') { - $title = $langs->trans("MenuVatAccounts"); - $titlepicto = 'accountancy'; + $title = $langs->trans("MenuVatAccounts"); + $titlepicto = 'accountancy'; } if ($id == 7 && GETPOST('from') == 'accountancy') { - $title = $langs->trans("MenuTaxAccounts"); - $titlepicto = 'accountancy'; + $title = $langs->trans("MenuTaxAccounts"); + $titlepicto = 'accountancy'; } print load_fiche_titre($title, $linkback, $titlepicto); if (empty($id)) { - print ''.$langs->trans("DictionaryDesc"); - print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; - print '

'; + print ''.$langs->trans("DictionaryDesc"); + print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; + print '

'; } @@ -1035,7 +1031,7 @@ if (GETPOST('from')) $paramwithsearch .= '&from='.urlencode(GETPOST('from', 'alp // Confirmation of the deletion of the line if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'rowid='.urlencode($rowid).'&code='.urlencode($code).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'rowid='.urlencode($rowid).'&code='.urlencode($code).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -1044,126 +1040,126 @@ if ($action == 'delete') */ if ($id) { - // Complete search values request with sort criteria - $sql = $tabsql[$id]; + // Complete search values request with sort criteria + $sql = $tabsql[$id]; - if (!preg_match('/ WHERE /', $sql)) $sql .= " WHERE 1 = 1"; - if ($search_country_id > 0) $sql .= " AND c.rowid = ".$search_country_id; - if ($search_code != '' && $id == 9) $sql .= natural_search("code_iso", $search_code); - elseif ($search_code != '' && $id == 28) $sql .= natural_search("h.code", $search_code); - elseif ($search_code != '' && $id == 32) $sql .= natural_search("a.code", $search_code); - elseif ($search_code != '' && $id == 3) $sql .= natural_search("r.code_region", $search_code); - elseif ($search_code != '' && $id != 9) $sql .= natural_search("code", $search_code); + if (!preg_match('/ WHERE /', $sql)) $sql .= " WHERE 1 = 1"; + if ($search_country_id > 0) $sql .= " AND c.rowid = ".$search_country_id; + if ($search_code != '' && $id == 9) $sql .= natural_search("code_iso", $search_code); + elseif ($search_code != '' && $id == 28) $sql .= natural_search("h.code", $search_code); + elseif ($search_code != '' && $id == 32) $sql .= natural_search("a.code", $search_code); + elseif ($search_code != '' && $id == 3) $sql .= natural_search("r.code_region", $search_code); + elseif ($search_code != '' && $id != 9) $sql .= natural_search("code", $search_code); - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield = 'country_code'; - $sql .= " ORDER BY ".$db->escape($sortfield); - if ($sortorder) - { - $sql .= " ".strtoupper($db->escape($sortorder)); - } - $sql .= ", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i', '', $tabsqlsort[$id]); - $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.',/i', '', $tabsqlsort[$id]); - } else { - $sql .= " ORDER BY "; - } - $sql .= $tabsqlsort[$id]; - $sql .= $db->plimit($listlimit + 1, $offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield = 'country_code'; + $sql .= " ORDER BY ".$db->escape($sortfield); + if ($sortorder) + { + $sql .= " ".strtoupper($db->escape($sortorder)); + } + $sql .= ", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i', '', $tabsqlsort[$id]); + $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.',/i', '', $tabsqlsort[$id]); + } else { + $sql .= " ORDER BY "; + } + $sql .= $tabsqlsort[$id]; + $sql .= $db->plimit($listlimit + 1, $offset); + //print $sql; - if (empty($tabfield[$id])) - { - dol_print_error($db, 'The table with id '.$id.' has no array tabfield defined'); - exit; - } - $fieldlist = explode(',', $tabfield[$id]); + if (empty($tabfield[$id])) + { + dol_print_error($db, 'The table with id '.$id.' has no array tabfield defined'); + exit; + } + $fieldlist = explode(',', $tabfield[$id]); - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - if ($id == 10 && empty($conf->global->FACTURE_TVAOPTION)) - { - print info_admin($langs->trans("VATIsUsedIsOff", $langs->transnoentities("Setup"), $langs->transnoentities("CompanyFoundation"))); - print "
\n"; - } + if ($id == 10 && empty($conf->global->FACTURE_TVAOPTION)) + { + print info_admin($langs->trans("VATIsUsedIsOff", $langs->transnoentities("Setup"), $langs->transnoentities("CompanyFoundation"))); + print "
\n"; + } - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused = 0; - $withentity = null; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused = 0; + $withentity = null; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - print '
'; - print '
'; + print ''; print $langs->trans('From'); print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, ''); print ' '; print $langs->trans('to'); print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, ''); print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); + print ''; + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'.$langs->trans("SubTotal").':'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_credit - $sous_total_debit)).'
'.$line->numero_compte.($root_account_description ? ' - '.$root_account_description : '').''.$line->numero_compte.($root_account_description ? ' - '.$root_account_description : '').'
'.length_accountg($line->numero_compte).''.$description.''.$accounting_account.''.price($opening_balances["'".$line->numero_compte."'"]).''.price($line->debit).''.price($line->credit).'
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_debit - $sous_total_credit)).'
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_debit - $sous_total_credit)).'
'.$langs->trans("AccountBalance").':'.price($total_debit).''.price($total_credit).''.price(price2num($total_debit - $total_credit)).'
'.$langs->trans("AccountBalance").':'.price($total_debit).''.price($total_credit).''.price(price2num($total_debit - $total_credit)).'
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1); + print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1); + print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print $langs->trans('From').' '; print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); } else { - print ''; + print ''; } print '
'; print '
'; - print $langs->trans('to').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print $langs->trans('to').' '; print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); } else { - print ''; + print ''; } print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1); + print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_creation_end, 'date_creation_end', 0, 0, 1); + print $form->selectDate($search_date_creation_end, 'date_creation_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1); + print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_modification_end, 'date_modification_end', 0, 0, 1); + print $form->selectDate($search_date_modification_end, 'date_modification_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1); + print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_export_end, 'date_export_end', 0, 0, 1); + print $form->selectDate($search_date_export_end, 'date_export_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; if (empty($line->date_export)) { if ($user->rights->accounting->mouvements->creer) { - print ''.img_edit().''; + print ''.img_edit().''; } if ($user->rights->accounting->mouvements->supprimer) { - print ' '.img_delete().''; + print ''.img_delete().''; } } print ''; print '
'; - print $langs->trans('From') . ': '; - print $form->selectDate($search_date_start, 'search_date_start', 0, 0, 1); + print $form->selectDate($search_date_start, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to') . ': '; - print $form->selectDate($search_date_end, 'search_date_end', 0, 0, 1); + print $form->selectDate($search_date_end, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; if (empty($line->date_export)) { if ($user->rights->accounting->mouvements->creer) { - print ''.img_edit().''; + print ''.img_edit().''; } if ($user->rights->accounting->mouvements->supprimer) { - print ' '.img_delete().''; + print '   '.img_delete().''; } } print ''.$langs->trans("Total").'
'.$langs->trans("Total").'
'; + print '
'; + print '
'; - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') { - $withentity = getEntity($tabname[$id]); - continue; - } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') { + $withentity = getEntity($tabname[$id]); + continue; + } - // Define field friendly name from its technical name - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - $class = ''; + // Define field friendly name from its technical name + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $class = ''; - if ($fieldlist[$field] == 'pos') { $valuetoshow = $langs->trans("Position"); $class = 'maxwidth100'; } - if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } - if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } - if ($fieldlist[$field] == 'taux') { + if ($fieldlist[$field] == 'pos') { $valuetoshow = $langs->trans("Position"); $class = 'maxwidth100'; } + if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } + if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } + if ($fieldlist[$field] == 'taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow = $langs->trans("Rate"); else $valuetoshow = $langs->trans("Amount"); $class = 'center'; - } - if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $class = "center"; $sortable = 0; } - if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $class = "center"; } - if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $class = "center"; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $class = "center"; } - if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { + } + if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $class = "center"; $sortable = 0; } + if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $class = "center"; } + if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $class = "center"; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $class = "center"; } + if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") $valuetoshow = $form->textwithtooltip($langs->trans("Type"), $langs->trans("TypePaymentDesc"), 2, 1, img_help(1, '')); else $valuetoshow = $langs->trans("Type"); - } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); $class = 'maxwidth100'; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') - { - $valuetoshow = $form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); - } - if ($fieldlist[$field] == 'libelle_facture') { - $valuetoshow = $form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); - } - if ($fieldlist[$field] == 'country') { - if (in_array('region_id', $fieldlist)) { print ''; continue; } // For region page, we do not show the country input - $valuetoshow = $langs->trans("Country"); - } - if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $class = "center"; } - if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } - if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $class = "center"; } - if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } - if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } - if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } - if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } - if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $valuetoshow = ''; } - if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); } - if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); } - if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountparent"); } - if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } - if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } - if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } - if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } + } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); $class = 'maxwidth100'; } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') + { + $valuetoshow = $form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); + } + if ($fieldlist[$field] == 'libelle_facture') { + $valuetoshow = $form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); + } + if ($fieldlist[$field] == 'country') { + if (in_array('region_id', $fieldlist)) { print ''; continue; } // For region page, we do not show the country input + $valuetoshow = $langs->trans("Country"); + } + if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $class = "center"; } + if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } + if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $class = "center"; } + if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } + if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } + if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } + if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } + if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); } + if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); } + if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } + if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountparent"); } + if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } + if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } + if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } + if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } if ($fieldlist[$field] == 'range_account') { $valuetoshow = $langs->trans("Range"); } if ($fieldlist[$field] == 'sens') { $valuetoshow = $langs->trans("Sens"); } if ($fieldlist[$field] == 'category_type') { $valuetoshow = $langs->trans("Calculated"); } @@ -1187,197 +1183,197 @@ if ($id) if ($fieldlist[$field] == 'revenuestamp_type') { $valuetoshow = $langs->trans('TypeOfRevenueStamp'); } if ($fieldlist[$field] == 'use_default') { $valuetoshow = $langs->trans('Default'); } - if ($id == 2) // Special case for state page - { - if ($fieldlist[$field] == 'region_id') { $valuetoshow = ' '; $showfield = 1; } - if ($fieldlist[$field] == 'region') { $valuetoshow = $langs->trans("Country").'/'.$langs->trans("Region"); $showfield = 1; } - } + if ($id == 2) // Special case for state page + { + if ($fieldlist[$field] == 'region_id') { $valuetoshow = ' '; $showfield = 1; } + if ($fieldlist[$field] == 'region') { $valuetoshow = $langs->trans("Country").'/'.$langs->trans("Region"); $showfield = 1; } + } - if ($valuetoshow != '') - { - 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])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); - else print $valuetoshow; - print ''; - } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; - } + if ($valuetoshow != '') + { + 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])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + else print $valuetoshow; + print ''; + } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; + } - if ($id == 4) print ''; - print ''; - print ''; - print ''; - print ''; + if ($id == 4) print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ''; - print ''; + // Line to enter new values + print ''; + print ''; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val) != '') - $obj->$val = GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val) != '') + $obj->$val = GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $tmpaction = 'create'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - if ($id == 3) unset($fieldlist[2]); // Remove field ??? if dictionary Regions + if ($id == 3) unset($fieldlist[2]); // Remove field ??? if dictionary Regions - if (empty($reshook)) - { - fieldList($fieldlist, $obj, $tabname[$id], 'add'); - } + if (empty($reshook)) + { + fieldList($fieldlist, $obj, $tabname[$id], 'add'); + } - if ($id == 4) print ''; - print ''; - print ""; + if ($id == 4) print ''; + print ''; + print ""; - $colspan = count($fieldlist) + 3; - if ($id == 4) $colspan++; + $colspan = count($fieldlist) + 3; + if ($id == 4) $colspan++; - print '
  '; - print ''; - if (!is_null($withentity)) - print ''; - print '
'; + print ''; + if (!is_null($withentity)) + print ''; + print '
'; - if ($action != 'edit') - { - print ''; - } - print '
'; + if ($action != 'edit') + { + print ''; + } + print '
'; + print ''; print '
'; - } + } - print ''; + print ''; - print '
'; + print '
'; - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - // List of available record in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); + // List of available record in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $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; - // There is several pages - if ($num > $listlimit || $page) - { - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; - } + // There is several pages + if ($num > $listlimit || $page) + { + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + } - print '
'; - print ''; + print '
'; + print '
'; - // Title line with search input fields - print ''; - $filterfound = 0; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') continue; + // Title line with search input fields + print ''; + $filterfound = 0; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') continue; - $showfield = 1; // By default + $showfield = 1; // By default - if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } - if ($showfield) - { - if ($value == 'country') - { - print ''; - $filterfound++; - } elseif ($value == 'code') - { - print ''; - $filterfound++; - } else { - print ''; - } - } - } - if ($id == 4) print ''; - print ''; - print ''; - print ''; + if ($showfield) + { + if ($value == 'country') + { + print ''; + $filterfound++; + } elseif ($value == 'code') + { + print ''; + $filterfound++; + } else { + print ''; + } + } + } + if ($id == 4) print ''; + print ''; + print ''; + print ''; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') continue; + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') continue; - // Determines the name of the field in relation to the possible names - // in data dictionaries - $showfield = 1; // By defaut - $cssprefix = ''; - $sortable = 1; - $valuetoshow = ucfirst($fieldlist[$field]); // By defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate + // Determines the name of the field in relation to the possible names + // in data dictionaries + $showfield = 1; // By defaut + $cssprefix = ''; + $sortable = 1; + $valuetoshow = ucfirst($fieldlist[$field]); // By defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate - // Special cases - if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } - if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } - if ($fieldlist[$field] == 'taux') { + // Special cases + if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } + if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } + if ($fieldlist[$field] == 'taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow = $langs->trans("Rate"); else $valuetoshow = $langs->trans("Amount"); $cssprefix = 'center '; - } - if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } - 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] == 'position') { $cssprefix = 'right '; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field] == 'libelle_facture') { $valuetoshow = $langs->trans("LabelOnDocuments"); } - if ($fieldlist[$field] == 'country') { $valuetoshow = $langs->trans("Country"); } - if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $cssprefix = "center "; } - if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } - if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $cssprefix = "center "; } - if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } - if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } - if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } - if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } - if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); $sortable = 0; } - if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); $sortable = 0; } + } + if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } + 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] == 'position') { $cssprefix = 'right '; } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); } + if ($fieldlist[$field] == 'libelle_facture') { $valuetoshow = $langs->trans("LabelOnDocuments"); } + if ($fieldlist[$field] == 'country') { $valuetoshow = $langs->trans("Country"); } + if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $cssprefix = "center "; } + if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } + if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $cssprefix = "center "; } + if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } + if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } + if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } + if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } + if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } + if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); $sortable = 0; } + if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); $sortable = 0; } if ($fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountsparent"); } - if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } - if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } - if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } - if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } + if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountsparent"); } + if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } + if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } + if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } + if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } if ($fieldlist[$field] == 'range_account') { $valuetoshow = $langs->trans("Range"); } if ($fieldlist[$field] == 'sens') { $valuetoshow = $langs->trans("Sens"); } if ($fieldlist[$field] == 'category_type') { $valuetoshow = $langs->trans("Calculated"); } @@ -1403,198 +1399,198 @@ if ($id) if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } - // Show field title - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, $cssprefix); - } - } + // Show field title + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, $cssprefix); + } + } // Favorite - Only activated on country dictionary - if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); + if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { - $tmpaction = 'edit'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) + { + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - // Show fields - if (empty($reshook)) { - $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); - } + // Show fields + if (empty($reshook)) { + $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + } - print ''; - } else { - $tmpaction = 'view'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + print ''; + } else { + $tmpaction = 'view'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - $withentity = null; + if (empty($reshook)) + { + $withentity = null; - foreach ($fieldlist as $field => $value) - { - //var_dump($fieldlist); - $class = ''; - $showfield = 1; - $valuetoshow = $obj->{$fieldlist[$field]}; + foreach ($fieldlist as $field => $value) + { + //var_dump($fieldlist); + $class = ''; + $showfield = 1; + $valuetoshow = $obj->{$fieldlist[$field]}; - if ($fieldlist[$field] == 'entity') { - $withentity = $valuetoshow; - continue; - } + if ($fieldlist[$field] == 'entity') { + $withentity = $valuetoshow; + continue; + } - if ($value == 'element') - { - $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; - } elseif ($value == 'source') - { - $valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow; - } elseif ($valuetoshow == 'all') { - $valuetoshow = $langs->trans('All'); - } elseif ($fieldlist[$field] == 'country') { - if (empty($obj->country_code)) - { - $valuetoshow = '-'; - } else { - $key = $langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); - } - } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - $valuetoshow = yn($valuetoshow); - $class = "center"; - } elseif ($fieldlist[$field] == 'type_cdr') { - if (empty($valuetoshow)) $valuetoshow = $langs->trans('None'); - elseif ($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); - elseif ($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); - $class = "center"; - } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { - $valuetoshow = price($valuetoshow); - } - if ($value == 'private') - { - $valuetoshow = yn($elementList[$valuetoshow]); - } elseif ($fieldlist[$field] == 'libelle_facture') { - $langs->load("bills"); - $key = $langs->trans("PaymentCondition".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentCondition".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - $valuetoshow = nl2br($valuetoshow); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_country') { - $key = $langs->trans("Country".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Country".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_availability') { - $langs->load("propal"); - $key = $langs->trans("AvailabilityType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "AvailabilityType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_actioncomm') { - $key = $langs->trans("Action".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Action".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif (!empty($obj->code_iso) && $fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_currencies') { - $key = $langs->trans("Currency".strtoupper($obj->code_iso)); - $valuetoshow = ($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_typent') { - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_prospectlevel') { - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_civility') { - $key = $langs->trans("Civility".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Civility".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_contact') { - $langs->load('agenda'); - $key = $langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $key = $langs->trans("PaymentConditionShort".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { - $langs->load("bills"); - $key = $langs->trans("PaymentType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'type' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { - $payment_type_list = array(0=>$langs->trans('PaymentTypeCustomer'), 1=>$langs->trans('PaymentTypeSupplier'), 2=>$langs->trans('PaymentTypeBoth')); - $valuetoshow = $payment_type_list[$valuetoshow]; - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_reason') { - $key = $langs->trans("DemandReasonType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "DemandReasonType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_method') { - $langs->load("orders"); - $key = $langs->trans($obj->code); - $valuetoshow = ($obj->code && $key != $obj->code) ? $key : $obj->{$fieldlist[$field]}; - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_shipment_mode') { - $langs->load("sendings"); - $key = $langs->trans("SendingMethod".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "SendingMethod".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paper_format') - { - $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') - { - $langs->load('trips'); - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { - $showfield = 0; - } elseif ($fieldlist[$field] == 'unicode') { - $valuetoshow = $langs->getCurrencySymbol($obj->code, 1); - } elseif ($fieldlist[$field] == 'label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'short_label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } elseif (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) - { - $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); - $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'localtax1' || $fieldlist[$field] == 'localtax2') { - $class = "center"; + if ($value == 'element') + { + $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; + } elseif ($value == 'source') + { + $valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow; + } elseif ($valuetoshow == 'all') { + $valuetoshow = $langs->trans('All'); + } elseif ($fieldlist[$field] == 'country') { + if (empty($obj->country_code)) + { + $valuetoshow = '-'; + } else { + $key = $langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); + } + } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + $valuetoshow = yn($valuetoshow); + $class = "center"; + } elseif ($fieldlist[$field] == 'type_cdr') { + if (empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif ($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif ($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $class = "center"; + } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { + $valuetoshow = price($valuetoshow); + } + if ($value == 'private') + { + $valuetoshow = yn($elementList[$valuetoshow]); + } elseif ($fieldlist[$field] == 'libelle_facture') { + $langs->load("bills"); + $key = $langs->trans("PaymentCondition".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentCondition".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + $valuetoshow = nl2br($valuetoshow); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_country') { + $key = $langs->trans("Country".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Country".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_availability') { + $langs->load("propal"); + $key = $langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "AvailabilityType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_actioncomm') { + $key = $langs->trans("Action".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Action".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif (!empty($obj->code_iso) && $fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_currencies') { + $key = $langs->trans("Currency".strtoupper($obj->code_iso)); + $valuetoshow = ($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_typent') { + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_prospectlevel') { + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_civility') { + $key = $langs->trans("Civility".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Civility".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_contact') { + $langs->load('agenda'); + $key = $langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $key = $langs->trans("PaymentConditionShort".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { + $langs->load("bills"); + $key = $langs->trans("PaymentType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'type' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { + $payment_type_list = array(0=>$langs->trans('PaymentTypeCustomer'), 1=>$langs->trans('PaymentTypeSupplier'), 2=>$langs->trans('PaymentTypeBoth')); + $valuetoshow = $payment_type_list[$valuetoshow]; + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_reason') { + $key = $langs->trans("DemandReasonType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "DemandReasonType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_method') { + $langs->load("orders"); + $key = $langs->trans($obj->code); + $valuetoshow = ($obj->code && $key != $obj->code) ? $key : $obj->{$fieldlist[$field]}; + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_shipment_mode') { + $langs->load("sendings"); + $key = $langs->trans("SendingMethod".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "SendingMethod".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paper_format') + { + $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') + { + $langs->load('trips'); + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { + $showfield = 0; + } elseif ($fieldlist[$field] == 'unicode') { + $valuetoshow = $langs->getCurrencySymbol($obj->code, 1); + } elseif ($fieldlist[$field] == 'label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'short_label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } elseif (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) + { + $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); + $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'localtax1' || $fieldlist[$field] == 'localtax2') { + $class = "center"; } elseif ($fieldlist[$field] == 'localtax1_type') { - if ($obj->localtax1 != 0) - $valuetoshow = $localtax_typeList[$valuetoshow]; - else $valuetoshow = ''; - $class = "center"; + if ($obj->localtax1 != 0) + $valuetoshow = $localtax_typeList[$valuetoshow]; + else $valuetoshow = ''; + $class = "center"; } elseif ($fieldlist[$field] == 'localtax2_type') { - if ($obj->localtax2 != 0) - $valuetoshow = $localtax_typeList[$valuetoshow]; - else $valuetoshow = ''; - $class = "center"; + if ($obj->localtax2 != 0) + $valuetoshow = $localtax_typeList[$valuetoshow]; + else $valuetoshow = ''; + $class = "center"; } elseif ($fieldlist[$field] == 'taux') { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $class = "center"; + $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); + $class = "center"; } elseif (in_array($fieldlist[$field], array('recuperableonly'))) { $class = "center"; } elseif ($fieldlist[$field] == 'accountancy_code' || $fieldlist[$field] == 'accountancy_code_sell' || $fieldlist[$field] == 'accountancy_code_buy') { - $valuetoshow = length_accountg($valuetoshow); - } elseif ($fieldlist[$field] == 'fk_tva') + $valuetoshow = length_accountg($valuetoshow); + } elseif ($fieldlist[$field] == 'fk_tva') { foreach ($form->cache_vatrates as $key => $Tab) { @@ -1619,49 +1615,49 @@ if ($id) } elseif ($fieldlist[$field] == 'code' && $id == 3) { $valuetoshow = $obj->state_code; } - $class .= ($class ? ' ' : '').'tddict'; - if ($fieldlist[$field] == 'note' && $id == 10) $class .= ' tdoverflowmax200'; - if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto'; - if ($fieldlist[$field] == 'position') $class .= ' right'; - if ($fieldlist[$field] == 'localtax1_type') $class .= ' nowrap'; - if ($fieldlist[$field] == 'localtax2_type') $class .= ' nowrap'; - // Show value for field + $class .= ($class ? ' ' : '').'tddict'; + if ($fieldlist[$field] == 'note' && $id == 10) $class .= ' tdoverflowmax200'; + if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto'; + if ($fieldlist[$field] == 'position') $class .= ' right'; + if ($fieldlist[$field] == 'localtax1_type') $class .= ' nowrap'; + if ($fieldlist[$field] == 'localtax2_type') $class .= ' nowrap'; + // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - // all true by default - $iserasable = 1; - $canbedisabled = 1; - $canbemodified = 1; - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } + // Can an entry be erased or disabled ? + // all true by default + $iserasable = 1; + $canbedisabled = 1; + $canbemodified = 1; + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } if ($id == 25 && in_array($obj->code, array('banner', 'blogpost', 'other', 'page'))) { $iserasable = 0; $canbedisabled = 0; if (in_array($obj->code, array('banner'))) $canbedisabled = 1; } - if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable = 0; } - if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled = 0; $canbedisabled = 0; } - $canbemodified = $iserasable; - if ($obj->code == 'RECEP') $canbemodified = 1; - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm") $canbemodified = 1; + if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable = 0; } + if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled = 0; $canbedisabled = 0; } + $canbemodified = $iserasable; + if ($obj->code == 'RECEP') $canbemodified = 1; + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm") $canbemodified = 1; - // Build Url. The table is id=, the id of line is rowid= - $rowidcol = $tabrowid[$id]; - // If rowidcol not defined - if (empty($rowidcol) || in_array($id, array(6, 7, 8, 13, 17, 19, 27, 32))) $rowidcol = 'rowid'; - $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((!empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0') ? $obj->{$rowidcol}:(!empty($obj->code) ?urlencode($obj->code) : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); - if (!empty($param)) $url .= '&'.$param; - if (!is_null($withentity)) $url .= '&entity='.$withentity; - $url .= '&'; + // Build Url. The table is id=, the id of line is rowid= + $rowidcol = $tabrowid[$id]; + // If rowidcol not defined + if (empty($rowidcol) || in_array($id, array(6, 7, 8, 13, 17, 19, 27, 32))) $rowidcol = 'rowid'; + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((!empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0') ? $obj->{$rowidcol}:(!empty($obj->code) ?urlencode($obj->code) : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); + if (!empty($param)) $url .= '&'.$param; + if (!is_null($withentity)) $url .= '&entity='.$withentity; + $url .= '&'; // Favorite // Only activated on country dictionary - if ($id == 4) + if ($id == 4) { print ''; } - // Active - print '"; + // Active + print '"; - // Modify link - if ($canbemodified) print ''; - else print ''; + // Modify link + if ($canbemodified) print ''; + else print ''; - // Delete link - if ($iserasable) - { - print ''; - } else print ''; + // Delete link + if ($iserasable) + { + print ''; + } else print ''; - print "\n"; - } - $i++; - } - } + print "\n"; + } + $i++; + } + } - print '
'; - print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth150 maxwidthonsmartphone'); - print ''; - print ''; - print ''; - print ''; - if ($filterfound) - { - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - } - print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth150 maxwidthonsmartphone'); + print ''; + print ''; + print ''; + print ''; + if ($filterfound) + { + $searchpicto = $form->showFilterAndCheckAddButtons(0); + print $searchpicto; + } + print '
'; - print '
'; - print ''; - print ''; - if (!is_null($withentity)) - print ''; - print ''; - print ''; - print '
'; + print '
'; + print ''; + print ''; + if (!is_null($withentity)) + print ''; + print ''; + print ''; + print '
'.$valuetoshow.''; if ($iserasable) print ''.$actl[$obj->favorite].''; @@ -1669,98 +1665,98 @@ if ($id) print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else { - if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - elseif (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - elseif (isset($obj->type) && in_array($obj->type, array('system')) && !empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else { + if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + elseif (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + elseif (isset($obj->type) && in_array($obj->type, array('system')) && !empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "'.img_edit().' '.img_edit().' '; - if ($user->admin) print ''.img_delete().''; - //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ' '; + if ($user->admin) print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin + print ' 
'; - print '
'; - } else { - dol_print_error($db); - } + print ''; + print ''; + } else { + dol_print_error($db); + } - print '
'; + print ''; } else { - /* + /* * Show list of dictionary to show */ - $lastlineisempty = false; + $lastlineisempty = false; print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; + print '
'.$langs->trans("Dictionary").''.$langs->trans("Table").'
'; + print ''; + print ''; + print ''; + print ''; - $showemptyline = ''; - foreach ($taborder as $i) - { - if (isset($tabname[$i]) && empty($tabcond[$i])) continue; + $showemptyline = ''; + foreach ($taborder as $i) + { + if (isset($tabname[$i]) && empty($tabcond[$i])) continue; - if ($i) - { - if ($showemptyline) - { - print ''; - $showemptyline = 0; - } + if ($i) + { + if ($showemptyline) + { + print ''; + $showemptyline = 0; + } - $value = $tabname[$i]; - print ''; - print ''; + print ''; - print ''; - $lastlineisempty = false; - } else { - if (!$lastlineisempty) - { - $showemptyline = 1; - $lastlineisempty = true; - } - } - } - print '
'.$langs->trans("Dictionary").''.$langs->trans("Table").'
   
   
'; - if (!empty($tabcond[$i])) - { - print ''.$langs->trans($tablib[$i]).''; - } else { - print $langs->trans($tablib[$i]); - } - print ''; - /*if (empty($tabcond[$i])) + $value = $tabname[$i]; + print '
'; + if (!empty($tabcond[$i])) + { + print ''.$langs->trans($tablib[$i]).''; + } else { + print $langs->trans($tablib[$i]); + } + print ''; + /*if (empty($tabcond[$i])) { print info_admin($langs->trans("DictionaryDisabledSinceNoModuleNeedIt"),1); }*/ - print ''.$tabname[$i].'
'; - print '
'; + print ''; + print ''.$tabname[$i].''; + $lastlineisempty = false; + } else { + if (!$lastlineisempty) + { + $showemptyline = 1; + $lastlineisempty = true; + } + } + } + print ''; + print ''; } print '
'; @@ -1799,14 +1795,14 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') continue; } - if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system', 'systemauto'))) - { - $hidden = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''); - print ''; - print ''; - print $langs->trans($hidden); - print ''; - } elseif ($fieldlist[$field] == 'country') + if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system', 'systemauto'))) + { + $hidden = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''); + print ''; + print ''; + print $langs->trans($hidden); + print ''; + } elseif ($fieldlist[$field] == 'country') { if (in_array('region_id', $fieldlist)) { @@ -1875,8 +1871,8 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print $form->selectarray($fieldlist[$field], $select_list, (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'2')); print ''; } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if ($fieldlist[$field] == 'type_cdr') print ''; - else print ''; + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; if ($fieldlist[$field] == 'type_cdr') { print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'')); } else { @@ -1890,27 +1886,27 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print ''; print ''; } elseif (in_array($fieldlist[$field], array('libelle_facture'))) { - print ''; - $transfound = 0; - $transkey = ''; - // Special case for labels - if ($tabname == MAIN_DB_PREFIX.'c_payment_term') - { - $langs->load("bills"); - $transkey = "PaymentCondition".strtoupper($obj->code); - if ($langs->trans($transkey) != $transkey) - { - $transfound = 1; - print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); - } - } - if (!$transfound) - { - print ''; - } else { - print ''; - } - print ''; + print ''; + $transfound = 0; + $transkey = ''; + // Special case for labels + if ($tabname == MAIN_DB_PREFIX.'c_payment_term') + { + $langs->load("bills"); + $transkey = "PaymentCondition".strtoupper($obj->code); + if ($langs->trans($transkey) != $transkey) + { + $transfound = 1; + print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); + } + } + if (!$transfound) + { + print ''; + } else { + print ''; + } + print ''; } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { @@ -1937,12 +1933,12 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print ''; if (!empty($conf->accounting->enabled)) { - $fieldname = $fieldlist[$field]; + $fieldname = $fieldlist[$field]; $accountancy_account = (!empty($obj->$fieldname) ? $obj->$fieldname : 0); print $formaccounting->select_account($accountancy_account, '.'.$fieldlist[$field], 1, '', 1, 1, 'maxwidth200 maxwidthonsmartphone'); } else { - $fieldname = $fieldlist[$field]; - print ''; + $fieldname = $fieldlist[$field]; + print ''; } print ''; } elseif ($fieldlist[$field] == 'fk_tva') @@ -1961,12 +1957,12 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print $form->selectExpenseRanges($obj->fk_range); print ''; } else { - $fieldValue = isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''; + $fieldValue = isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''; if ($fieldlist[$field] == 'sortorder') - { - $fieldlist[$field] = 'position'; - } + { + $fieldlist[$field] = 'position'; + } $classtd = ''; $class = ''; if ($fieldlist[$field] == 'code') $class = 'maxwidth100'; @@ -1974,29 +1970,29 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') if (in_array($fieldlist[$field], array('libelle', 'label', 'tracking'))) $class = 'quatrevingtpercent'; print ''; $transfound = 0; - $transkey = ''; + $transkey = ''; if (in_array($fieldlist[$field], array('label', 'libelle'))) // For label { - // Special case for labels - if ($tabname == MAIN_DB_PREFIX.'c_civility') { - $transkey = "Civility".strtoupper($obj->code); - } - if ($tabname == MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $transkey = "PaymentConditionShort".strtoupper($obj->code); - } - if ($transkey && $langs->trans($transkey) != $transkey) - { - $transfound = 1; - print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); - } + // Special case for labels + if ($tabname == MAIN_DB_PREFIX.'c_civility') { + $transkey = "Civility".strtoupper($obj->code); + } + if ($tabname == MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $transkey = "PaymentConditionShort".strtoupper($obj->code); + } + if ($transkey && $langs->trans($transkey) != $transkey) + { + $transfound = 1; + print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); + } } if (!$transfound) { - print ''; + print ''; } else { - print ''; - } + print ''; + } print ''; } } diff --git a/htdocs/admin/ecm.php b/htdocs/admin/ecm.php index 145dfc6cbf8..e11434c45d6 100644 --- a/htdocs/admin/ecm.php +++ b/htdocs/admin/ecm.php @@ -23,6 +23,7 @@ */ require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page @@ -70,6 +71,10 @@ $linkback = ''; +$head = ecm_admin_prepare_head(); + +dol_fiche_head($head, 'ecm', $langs->trans("ECM"), -1, 'ecm'); + print ''; print ''; print ''; @@ -92,10 +97,10 @@ if ($conf->use_javascript_ajax) } else { if (empty($conf->global->ECM_AUTO_TREE_ENABLED)) { - print ''.img_picto($langs->trans("Disabled"), 'off').''; + print ''.img_picto($langs->trans("Disabled"), 'off').''; } elseif (!empty($conf->global->USER_MAIL_REQUIRED)) { - print ''.img_picto($langs->trans("Enabled"), 'on').''; + print ''.img_picto($langs->trans("Enabled"), 'on').''; } } print ''; diff --git a/htdocs/admin/ecm_directories_extrafields.php b/htdocs/admin/ecm_directories_extrafields.php new file mode 100644 index 00000000000..77e21963e4c --- /dev/null +++ b/htdocs/admin/ecm_directories_extrafields.php @@ -0,0 +1,123 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2012 Florian Henry + * Copyright (C) 2013 Philippe Grand + * Copyright (C) 2015 Claudio Aschieri + * Copyright (C) 2020 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 htdocs/admin/ecm_directories_extrafields.php + * \ingroup ecm + * \brief Page to setup extra fields of ecm + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + + +if (!$user->admin) + accessforbidden(); + +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'ecm')); + + +$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 = 'ecm_directories'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) { + accessforbidden(); +} + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + +/* + * View + */ + +$textobject = $langs->transnoentitiesnoconv("ECM"); + +llxHeader('', $langs->trans("ECMSetup")); + +$linkback = ''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("ECMSetup"), $linkback, 'title_setup'); +print "
\n"; + +$head = ecm_admin_prepare_head(); + +dol_fiche_head($head, 'attributes_ecm_directories', $langs->trans("ECM"), -1, 'ecm'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_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/ecm_files_extrafields.php b/htdocs/admin/ecm_files_extrafields.php new file mode 100644 index 00000000000..aaa507ca7c4 --- /dev/null +++ b/htdocs/admin/ecm_files_extrafields.php @@ -0,0 +1,123 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2012 Florian Henry + * Copyright (C) 2013 Philippe Grand + * Copyright (C) 2015 Claudio Aschieri + * Copyright (C) 2020 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 htdocs/admin/ecm_files_extrafields.php + * \ingroup ecm + * \brief Page to setup extra fields of ecm + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + + +if (!$user->admin) + accessforbidden(); + +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'ecm')); + + +$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 = 'ecm_files'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) { + accessforbidden(); +} + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + +/* + * View + */ + +$textobject = $langs->transnoentitiesnoconv("ECM"); + +llxHeader('', $langs->trans("ECMSetup")); + +$linkback = ''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("ECMSetup"), $linkback, 'title_setup'); +print "
\n"; + +$head = ecm_admin_prepare_head(); + +dol_fiche_head($head, 'attributes_ecm_files', $langs->trans("ECM"), -1, 'ecm'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_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/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 21dfb60c96e..eb9ffb52831 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -45,7 +45,7 @@ $ref = GETPOST('ref', '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 +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'emailcollectorcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $operationid = GETPOST('operationid', 'int'); @@ -62,7 +62,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$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'); @@ -148,7 +148,7 @@ if (GETPOST('addoperation', 'alpha')) { $emailcollectoroperation = new EmailCollectorAction($db); $emailcollectoroperation->type = GETPOST('operationtype', 'aZ09'); - $emailcollectoroperation->actionparam = GETPOST('operationparam', 'none'); + $emailcollectoroperation->actionparam = GETPOST('operationparam', 'restricthtml'); $emailcollectoroperation->fk_emailcollector = $object->id; $emailcollectoroperation->status = 1; $emailcollectoroperation->position = 50; @@ -165,19 +165,19 @@ if (GETPOST('addoperation', 'alpha')) if ($action == 'updateoperation') { - $emailcollectoroperation = new EmailCollectorAction($db); - $emailcollectoroperation->fetch(GETPOST('rowidoperation2', 'int')); + $emailcollectoroperation = new EmailCollectorAction($db); + $emailcollectoroperation->fetch(GETPOST('rowidoperation2', 'int')); - $emailcollectoroperation->actionparam = GETPOST('operationparam2', 'none'); + $emailcollectoroperation->actionparam = GETPOST('operationparam2', 'restricthtml'); - $result = $emailcollectoroperation->update($user); + $result = $emailcollectoroperation->update($user); - if ($result > 0) - { - $object->fetchActions(); - } else { - setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); - } + if ($result > 0) + { + $object->fetchActions(); + } else { + setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + } } if ($action == 'deleteoperation') { @@ -199,11 +199,11 @@ if ($action == 'confirm_collect') $res = $object->doCollectOneCollector(); if ($res > 0) { - $debuginfo = $object->debuginfo; - setEventMessages($object->lastresult, null, 'mesgs'); + $debuginfo = $object->debuginfo; + setEventMessages($object->lastresult, null, 'mesgs'); } else { - $debuginfo = $object->debuginfo; - setEventMessages($object->error, null, 'errors'); + $debuginfo = $object->debuginfo; + setEventMessages($object->error, null, 'errors'); } $action = ''; @@ -313,7 +313,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $object->fetchActions(); $head = emailcollectorPrepareHead($object); - dol_fiche_head($head, 'card', $langs->trans("EmailCollector"), -1, 'emailcollector'); + dol_fiche_head($head, 'card', $langs->trans("EmailCollector"), -1, 'email'); $formconfirm = ''; @@ -466,6 +466,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Filters + print '
'; print '
'.$langs->trans("Description").'
'; print ''; print ''; @@ -474,29 +475,34 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; + print '
'.$langs->trans("Filters").'
'; $arrayoftypes = array( - 'from'=>array('label'=>'MailFrom', 'data-placeholder'=>$langs->trans('SearchString')), - 'to'=>array('label'=>'MailTo', 'data-placeholder'=>$langs->trans('SearchString')), - 'cc'=>array('label'=>'Cc', 'data-placeholder'=>$langs->trans('SearchString')), - 'bcc'=>array('label'=>'Bcc', 'data-placeholder'=>$langs->trans('SearchString')), - 'subject'=>array('label'=>'Subject', 'data-placeholder'=>$langs->trans('SearchString')), - 'body'=>array('label'=>'Body', 'data-placeholder'=>$langs->trans('SearchString')), - // disabled because PHP imap_search is not compatible IMAPv4, only IMAPv2 - //'header'=>array('label'=>'Header', 'data-placeholder'=>'HeaderKey SearchString'), // HEADER key value - //'X1'=>'---', - //'notinsubject'=>array('label'=>'SubjectNotIn', 'data-placeholder'=>'SearchString'), - //'notinbody'=>array('label'=>'BodyNotIn', 'data-placeholder'=>'SearchString'), - 'X2'=>'---', - 'seen'=>array('label'=>'AlreadyRead', 'data-noparam'=>1), - 'unseen'=>array('label'=>'NotRead', 'data-noparam'=>1), - 'unanswered'=>array('label'=>'Unanswered', 'data-noparam'=>1), - 'answered'=>array('label'=>'Answered', 'data-noparam'=>1), - 'smaller'=>array('label'=>'SmallerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')), - 'larger'=>array('label'=>'LargerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')), - 'X3'=>'---', - 'withtrackingid'=>array('label'=>'WithDolTrackingID', 'data-noparam'=>1), - 'withouttrackingid'=>array('label'=>'WithoutDolTrackingID', 'data-noparam'=>1) + 'from'=>array('label'=>'MailFrom', 'data-placeholder'=>$langs->trans('SearchString')), + 'to'=>array('label'=>'MailTo', 'data-placeholder'=>$langs->trans('SearchString')), + 'cc'=>array('label'=>'Cc', 'data-placeholder'=>$langs->trans('SearchString')), + 'bcc'=>array('label'=>'Bcc', 'data-placeholder'=>$langs->trans('SearchString')), + 'subject'=>array('label'=>'Subject', 'data-placeholder'=>$langs->trans('SearchString')), + 'body'=>array('label'=>'Body', 'data-placeholder'=>$langs->trans('SearchString')), + // disabled because PHP imap_search is not compatible IMAPv4, only IMAPv2 + //'header'=>array('label'=>'Header', 'data-placeholder'=>'HeaderKey SearchString'), // HEADER key value + //'X1'=>'---', + //'notinsubject'=>array('label'=>'SubjectNotIn', 'data-placeholder'=>'SearchString'), + //'notinbody'=>array('label'=>'BodyNotIn', 'data-placeholder'=>'SearchString'), + 'X2'=>'---', + 'seen'=>array('label'=>'AlreadyRead', 'data-noparam'=>1), + 'unseen'=>array('label'=>'NotRead', 'data-noparam'=>1), + 'unanswered'=>array('label'=>'Unanswered', 'data-noparam'=>1), + 'answered'=>array('label'=>'Answered', 'data-noparam'=>1), + 'smaller'=>array('label'=>'SmallerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')), + 'larger'=>array('label'=>'LargerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')), + 'X3'=>'---', + 'withtrackingid'=>array('label'=>'WithDolTrackingID', 'data-noparam'=>1), + 'withouttrackingid'=>array('label'=>'WithoutDolTrackingID', 'data-noparam'=>1), + 'withtrackingidinmsgid'=>array('label'=>'WithDolTrackingIDInMsgId', 'data-noparam'=>1), + 'withouttrackingidinmsgid'=>array('label'=>'WithoutDolTrackingIDInMsgId', 'data-noparam'=>1), + 'X4'=>'---', + 'isnotanswer'=>array('label'=>'IsNotAnAnswer', 'data-noparam'=>1), + 'isanswer'=>array('label'=>'IsAnAnswer', 'data-noparam'=>1) ); - print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', '', 0, '', 2); + print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth500', 0, '', 2); print "\n"; print ''."\n"; @@ -269,14 +280,12 @@ if ($action == 'edit') print ''; print '
'; - //Add user to select destinaries list - print ''.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''; - print $form->selectyesno('MAIN_MAIL_ENABLED_USER_DEST_SELECT', $conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT, 1); - print ''; + print '
'; - // Separator - print ' '; + print ''; + print ''; // Method print ''; + // SMTP_ALLOW_SELF_SIGNED + print ''; + // DKIM print ''; - // Separator - print ''; + print '
'.$langs->trans("MAIN_MAIL_SENDMODE").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; @@ -408,6 +417,17 @@ if ($action == 'edit') } else print yn(0).' ('.$langs->trans("NotSupported").')'; print '
'.$langs->trans("MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED").''; + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED', (!empty($conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED) ? $conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED : 0), 1); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer')))) @@ -434,8 +454,12 @@ if ($action == 'edit') print ''; print '
 
'; + + print '
'; + + print ''; + print ''; // From print ''; @@ -451,9 +475,6 @@ if ($action == 'edit') print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); print ''; - // Separator - print ''; - // From print ''; print ''; + // Add user to select destinaries list + print ''; + print '
'.$langs->trans("OtherOptions").'
'.$langs->trans("MAIN_MAIL_EMAIL_FROM", ini_get('sendmail_from') ?ini_get('sendmail_from') : $langs->transnoentities("Undefined")).'
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").'
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''; + print $form->selectyesno('MAIN_MAIL_ENABLED_USER_DEST_SELECT', $conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT, 1); + print '
'; dol_fiche_end(); @@ -498,17 +524,23 @@ if ($action == 'edit') } print ''; - //Add user to select destinaries list - print ''.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''.yn($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT).''; + print ''; - // Separator - print ' '; + print '
'; + + print ''; + print ''; // Method print ''; // Host server @@ -561,6 +593,17 @@ if ($action == 'edit') } else print ''.yn(0).' ('.$langs->trans("NotSupported").')'; print ''; + // SMTP_ALLOW_SELF_SIGNED + print ''; + if ($conf->global->MAIN_MAIL_SENDMODE == 'swiftmailer') { @@ -591,8 +634,16 @@ if ($action == 'edit') print ''; } - // Separator - print ''; + print '
'.$langs->trans("MAIN_MAIL_SENDMODE").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; $text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE]; if (empty($text)) $text = $langs->trans("Undefined").img_warning(); print $text; + + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) { + print $form->textwithpicto('', $langs->trans("WarningPHPMail").'
'.$langs->trans("WarningPHPMailA").'
'.$langs->trans("WarningPHPMailB").'
'.$langs->trans("WarningPHPMailC"), 1, 'warning'); + } + print '
'.$langs->trans("MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print ''.yn(0).' ('.$langs->trans("NotSupported").')'; + print '
 
'; + + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP)) { + print info_admin($langs->trans("WarningPHPMail").'
'.$langs->trans("WarningPHPMailA").'
'.$langs->trans("WarningPHPMailB").'
'.$langs->trans("WarningPHPMailC"), 0, 0, 'warning'); + } + + print '
'; + + print ''; + print ''; // From print ''; @@ -645,9 +696,6 @@ if ($action == 'edit') } print ''; - // Separator - print ''; - // Errors To print ''; print ''; + //Add user to select destinaries list + print ''; + print '
'.$langs->trans("OtherOptions").'
'.$langs->trans("MAIN_MAIL_EMAIL_FROM", ini_get('sendmail_from') ?ini_get('sendmail_from') : $langs->transnoentities("Undefined")).'
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").''.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -666,6 +714,9 @@ if ($action == 'edit') } print '
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''.yn($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT).'
'; dol_fiche_end(); @@ -717,16 +768,22 @@ if ($action == 'edit') $text = ''; if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') { - $text .= $langs->trans("WarningPHPMail"); // To encourage to use SMTPS + //$text .= $langs->trans("WarningPHPMail"); // To encourage to use SMTPS } if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') { - // MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS is list of IPs where email is sent from. Example: '1.2.3.4, [aaaa:bbbb:cccc:dddd]'. - if (!empty($conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS)) + if (!empty($conf->global->MAIN_EXTERNAL_MAIL_SPF_STRING_TO_ADD)) { - // List of IP show as record to add in SPF if we use the mail method - $text .= ($text ? '

' : '').$langs->trans("WarningPHPMailSPF", $conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS); + // List of string to add in SPF if the setup use the mail method + $text .= ($text ? '

' : '').$langs->trans("WarningPHPMailSPF", $conf->global->MAIN_EXTERNAL_MAIL_SPF_STRING_TO_ADD); + } else { + // MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS is list of IPs where email is sent from. Example: '1.2.3.4, [aaaa:bbbb:cccc:dddd]'. + if (!empty($conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS)) + { + // List of IP show as record to add in SPF if we use the mail method + $text .= ($text ? '

' : '').$langs->trans("WarningPHPMailSPF", $conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS); + } } } else { if (!empty($conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS)) @@ -734,7 +791,7 @@ if ($action == 'edit') // List of IP show as record to add as allowed IP if we use the smtp method $text .= ($text ? '

' : '').$langs->trans("WarningPHPMail2", $conf->global->MAIN_EXTERNAL_SMTP_CLIENT_IP_ADDRESS); } - if (!empty($conf->global->MAIN_EXTERNAL_SMTP_SPF_STRING_TO_ADD)) + if (!empty($conf->global->MAIN_EXTERNAL_SMTP_SPF_STRING_TO_ADD)) // Should be required only if you have set to use your own SMTP and wat to warn users to update their domain name to match your SMTP server. { // List of string to add in SPF if we use the smtp method $text .= ($text ? '

' : '').$langs->trans("WarningPHPMailSPF", $conf->global->MAIN_EXTERNAL_SMTP_SPF_STRING_TO_ADD); diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php index f78ef0277bb..b97437216d6 100644 --- a/htdocs/admin/mails_emailing.php +++ b/htdocs/admin/mails_emailing.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'products', 'admin', 'mails', 'other', 'errors')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if (!$user->admin) accessforbidden(); @@ -68,6 +68,7 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW_EMAILING", GETPOST("MAIN_MAIL_SMTPS_PW_EMAILING"), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS_EMAILING", GETPOST("MAIN_MAIL_EMAIL_TLS_EMAILING"), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS_EMAILING", GETPOST("MAIN_MAIL_EMAIL_STARTTLS_EMAILING"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING", GETPOST("MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING"), 'chaine', 0, '', $conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -120,7 +121,7 @@ $listofmethods['default'] = $langs->trans('DefaultOutgoingEmailSetup'); $listofmethods['mail'] = 'PHP mail function'; //$listofmethods['simplemail']='Simplemail class'; $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; -$listofmethods['swiftmailer'] = 'Swift Mailer socket library'; +if (version_compare(phpversion(), '7.0', '>=')) $listofmethods['swiftmailer'] = 'Swift Mailer socket library'; if ($action == 'edit') @@ -147,6 +148,8 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").prop("disabled", true); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val(0); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").val(0); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").prop("disabled", true); '; if ($linuxlike) { @@ -173,6 +176,8 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS_EMAILING.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").val('.$conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING.'); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER_EMAILING").show(); @@ -187,6 +192,8 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS_EMAILING.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").val('.$conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING.'); + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT_EMAILING").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER_EMAILING").show(); @@ -199,13 +206,17 @@ if ($action == 'edit') jQuery("#MAIN_MAIL_SENDMODE_EMAILING").change(function() { initfields(); }); - jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { - if (jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val() == 1) + jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").change(function() { + if (jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").val() == 1) jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val(0); + else + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").val(0); }); jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").change(function() { - if (jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").val() == 1) + if (jQuery("#MAIN_MAIL_EMAIL_STARTTLS_EMAILING").val() == 1) jQuery("#MAIN_MAIL_EMAIL_TLS_EMAILING").val(0); + else + jQuery("#MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING").val(0); }); })'; print ''."\n"; @@ -359,6 +370,18 @@ if ($action == 'edit') } else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; + // SMTP_ALLOW_SELF_SIGNED_EMAILING + + print ''.$langs->trans("MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED").''; + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING', (!empty($conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING) ? $conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING : 0), 1); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; + print ''; dol_fiche_end(); @@ -437,6 +460,17 @@ if ($action == 'edit') } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; } else print yn(0).' ('.$langs->trans("NotSupported").')'; print ''; + + // SMTP_ALLOW_SELF_SIGNED_EMAILING + print ''.$langs->trans("MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_EMAILING); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print ''; } print ''; diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php index bf841a03abe..16ae12ffcc5 100644 --- a/htdocs/admin/mails_senderprofile_list.php +++ b/htdocs/admin/mails_senderprofile_list.php @@ -43,11 +43,12 @@ $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'); +$rowid = GETPOST('rowid', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -79,7 +80,7 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'mymodule', $id, ''); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { @@ -122,6 +123,10 @@ $permissiontoread = $user->admin; $permissiontoadd = $user->admin; $permissiontodelete = $user->admin; +if ($id > 0) { + $object->fetch($id); +} + /* * Actions @@ -191,7 +196,6 @@ $now = dol_now(); $help_url = ''; $title = $langs->trans("EMailsSetup"); - llxHeader('', $title); $linkback = ''; @@ -230,7 +234,7 @@ 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 (strpos($object->fields[$key]['type'], 'integer:') === 0 || $key == 'active') { if ($search[$key] == '-1') $search[$key] = ''; $mode_search = 2; } @@ -347,15 +351,41 @@ print '
'; print ''; print ''; -print ''; +print ''; print ''; print ''; print ''; +print ''; print ''; $newcardbutton = ''; if ($action != 'create') { $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', $_SERVER['PHP_SELF'].'?action=create', '', $permissiontoadd); + + if ($action == 'edit') { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Label").'
'.$langs->trans("Email").'
'.$langs->trans("Signature").''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('signature', (GETPOSTISSET('signature') ? GETPOST('signature', 'restricthtml') : $object->signature), '', 138, 'dolibarr_notes', 'In', true, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%'); + print $doleditor->Create(1); + print '
'.$langs->trans("User").''; + print $form->select_dolusers((GETPOSTISSET('private') ? GETPOST('private', 'int') : $object->private), 'private', 1, null, 0, ($user->admin ? '' : $user->id)); + print '
'.$langs->trans("Position").'
'.$langs->trans("Status").''; + print $form->selectarray('active', $object->fields['active']['arrayofkeyval'], (GETPOSTISSET('active') ? GETPOST('active', 'int') : $object->active), 0, 0, 0, '', 1); + print '
'; + print '
'; + print '
'; + print ''; + print '   '; + print ''; + print '
'; + } } else { /*print ''; if ($optioncss != '') print ''; @@ -367,7 +397,7 @@ if ($action != 'create') { print ''; */ print ''; - print ''; + print ''; print ''; print ''; if (!$i) $totalarray['nbfield']++; @@ -550,14 +580,14 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print ''; // Keep   to have a line with enough height + print '
'.$langs->trans("Label").'
'.$langs->trans("Label").'
'.$langs->trans("Email").'
'.$langs->trans("Signature").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -531,7 +561,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); + if ($key == 'status' || $key == 'active') print $object->getLibStatut(5); else print $object->showOutputField($val, $key, $object->$key, ''); print ''; - $url = $_SERVER["PHP_SELF"].'?action=list&id='.$obj->rowid; + $url = $_SERVER["PHP_SELF"].'?id='.$obj->rowid; if ($limit) $url .= '&limit='.urlencode($limit); if ($page) $url .= '&page='.urlencode($page); if ($sortfield) $url .= '&sortfield='.urlencode($sortfield); if ($sortorder) $url .= '&page='.urlencode($sortorder); - //print ''.img_edit().''; + print ''.img_edit().''; //print '   '; - print ''.img_delete().'   '; + print ''.img_delete().'   '; 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; diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index 0f490bb828a..1158ee56655 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -45,7 +45,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; // Load translation files required by the page $langs->loadLangs(array("errors", "admin", "mails", "languages")); -$action = GETPOST('action', 'alpha') ?GETPOST('action', 'alpha') : 'view'; +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation $id = GETPOST('id', 'int'); @@ -113,29 +113,29 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { - $tmp = FormMail::getAvailableSubstitKey('formemail'); - $tmp['__(AnyTranslationKey)__'] = 'Translation'; - $helpsubstit = $langs->trans("AvailableVariables").':
'; - $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; - foreach ($tmp as $key => $val) - { - $helpsubstit .= $key.' -> '.$val.'
'; - $helpsubstitforlines .= $key.' -> '.$val.'
'; - } + $tmp = FormMail::getAvailableSubstitKey('formemail'); + $tmp['__(AnyTranslationKey)__'] = 'Translation'; + $helpsubstit = $langs->trans("AvailableVariables").':
'; + $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; + foreach ($tmp as $key => $val) + { + $helpsubstit .= $key.' -> '.$val.'
'; + $helpsubstitforlines .= $key.' -> '.$val.'
'; + } } else { - $tmp = FormMail::getAvailableSubstitKey('formemailwithlines'); - $tmp['__(AnyTranslationKey)__'] = 'Translation'; - $helpsubstit = $langs->trans("AvailableVariables").':
'; - $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; - foreach ($tmp as $key => $val) - { - $helpsubstit .= $key.' -> '.$val.'
'; - } - $tmp = FormMail::getAvailableSubstitKey('formemailforlines'); - foreach ($tmp as $key => $val) - { - $helpsubstitforlines .= $key.' -> '.$val.'
'; - } + $tmp = FormMail::getAvailableSubstitKey('formemailwithlines'); + $tmp['__(AnyTranslationKey)__'] = 'Translation'; + $helpsubstit = $langs->trans("AvailableVariables").':
'; + $helpsubstitforlines = $langs->trans("AvailableVariables").':
'; + foreach ($tmp as $key => $val) + { + $helpsubstit .= $key.' -> '.$val.'
'; + } + $tmp = FormMail::getAvailableSubstitKey('formemailforlines'); + foreach ($tmp as $key => $val) + { + $helpsubstitforlines .= $key.' -> '.$val.'
'; + } } @@ -167,6 +167,8 @@ if ($conf->adherent->enabled && $user->rights->adherent->lire) $element if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementList['contract'] = $langs->trans('MailToSendContract'); if ($conf->projet->enabled) $elementList['project'] = $langs->trans('MailToProject'); if ($conf->ticket->enabled && $user->rights->ticket->read) $elementList['ticket_send'] = $langs->trans('MailToTicket'); +if ($conf->recruitment->enabled && $user->rights->recruitment->recruitmentjobposition->read) $elementList['recruitmentcandidature_send'] = $langs->trans('RecruitmentCandidatures'); +if ($conf->agenda->enabled) $elementList['actioncomm_send'] = $langs->trans('MailToSendEventPush'); $elementList['user'] = $langs->trans('MailToUser'); $parameters = array('elementList'=>$elementList); @@ -199,206 +201,206 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e 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 - { - $search_label = ''; - $search_type_template = ''; - $search_lang = ''; - $search_fk_user = ''; - $search_topic = ''; - $toselect = ''; - $search_array_options = array(); - } + // 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 + { + $search_label = ''; + $search_type_template = ''; + $search_lang = ''; + $search_fk_user = ''; + $search_topic = ''; + $toselect = ''; + $search_array_options = array(); + } - // Actions add or modify an entry into a dictionary - if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) - { - $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + // Actions add or modify an entry into a dictionary + if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) + { + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - foreach ($listfield as $f => $value) - { - // Not mandatory fields - if ($value == 'joinfiles') continue; - if ($value == 'content') continue; - if ($value == 'content_lines') continue; + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + // Not mandatory fields + if ($value == 'joinfiles') continue; + if ($value == 'content') continue; + if ($value == 'content_lines') continue; - if (GETPOST('actionmodify', 'alpha') && $value == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid]; + if (GETPOST('actionmodify', 'alpha') && $value == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid]; - if ((!isset($_POST[$value]) || $_POST[$value] == '' || $_POST[$value] == '-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position') - { - $ok = 0; - $fieldnamekey = $listfield[$f]; - // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Code'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; - if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate'; - if ($fieldnamekey == 'fk_user') $fieldnamekey = 'Owner'; - if ($fieldnamekey == 'private') $fieldnamekey = 'Private'; - if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; - if ($fieldnamekey == 'topic') $fieldnamekey = 'Topic'; + if ((!isset($_POST[$value]) || $_POST[$value] == '' || $_POST[$value] == '-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position') + { + $ok = 0; + $fieldnamekey = $listfield[$f]; + // We take translate key of field + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Code'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate'; + if ($fieldnamekey == 'fk_user') $fieldnamekey = 'Owner'; + if ($fieldnamekey == 'private') $fieldnamekey = 'Private'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'topic') $fieldnamekey = 'Topic'; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - } - } + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd')) - { - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - $sql .= $tabfieldinsert[$id]; - $sql .= ",active)"; - $sql .= " VALUES("; + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + $sql .= $tabfieldinsert[$id]; + $sql .= ",active)"; + $sql .= " VALUES("; - // List of values - $i = 0; - foreach ($listfieldinsert as $f => $value) - { - $keycode = $listfieldvalue[$i]; - if ($value == 'lang') $keycode = 'langcode'; - if (empty($keycode)) $keycode = $value; + // List of values + $i = 0; + foreach ($listfieldinsert as $f => $value) + { + $keycode = $listfieldvalue[$i]; + if ($value == 'lang') $keycode = 'langcode'; + if (empty($keycode)) $keycode = $value; - if ($value == 'entity') $_POST[$keycode] = $conf->entity; - if ($value == 'fk_user' && !($_POST[$keycode] > 0)) $_POST[$keycode] = ''; - if ($value == 'private' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '0'; - if ($value == 'position' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '1'; - //var_dump($keycode.' '.$value); + if ($value == 'entity') $_POST[$keycode] = $conf->entity; + if ($value == 'fk_user' && !($_POST[$keycode] > 0)) $_POST[$keycode] = ''; + if ($value == 'private' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '0'; + if ($value == 'position' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '1'; + //var_dump($keycode.' '.$value); - if ($i) $sql .= ", "; - if (GETPOST($keycode) == '' && $keycode != 'langcode') $sql .= "null"; // langcode must be '' if not defined so the unique key that include lang will work - elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + if ($i) $sql .= ", "; + if (GETPOST($keycode) == '' && $keycode != 'langcode') $sql .= "null"; // langcode must be '' if not defined so the unique key that include lang will work + elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } + $i++; + } + $sql .= ", 1)"; - $i++; - } - $sql .= ", 1)"; + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST = array('id'=>$id); // Clean $_POST array, we keep only id + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST = array('id'=>$id); // Clean $_POST array, we keep only id - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + $rowidcol = "rowid"; - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify')) - { - $rowidcol = "rowid"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + $i = 0; + foreach ($listfieldmodify as $field) + { + $keycode = $listfieldvalue[$i]; + if ($field == 'lang') $keycode = 'langcode'; + if (empty($keycode)) $keycode = $field; - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - $i = 0; - foreach ($listfieldmodify as $field) - { - $keycode = $listfieldvalue[$i]; - if ($field == 'lang') $keycode = 'langcode'; - if (empty($keycode)) $keycode = $field; + if ($field == 'fk_user' && !($_POST['fk_user'] > 0)) $_POST['fk_user'] = ''; + if ($field == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid]; + if ($field == 'joinfiles') $_POST['joinfiles'] = $_POST['joinfiles-'.$rowid]; + if ($field == 'content') $_POST['content'] = $_POST['content-'.$rowid]; + if ($field == 'content_lines') $_POST['content_lines'] = $_POST['content_lines-'.$rowid]; + if ($field == 'entity') $_POST[$keycode] = $conf->entity; - if ($field == 'fk_user' && !($_POST['fk_user'] > 0)) $_POST['fk_user'] = ''; - if ($field == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid]; - if ($field == 'joinfiles') $_POST['joinfiles'] = $_POST['joinfiles-'.$rowid]; - if ($field == 'content') $_POST['content'] = $_POST['content-'.$rowid]; - if ($field == 'content_lines') $_POST['content_lines'] = $_POST['content_lines-'.$rowid]; - if ($field == 'entity') $_POST[$keycode] = $conf->entity; + if ($i) $sql .= ", "; + $sql .= $field."="; - if ($i) $sql .= ", "; - $sql .= $field."="; + if (GETPOST($keycode) == '' || ($keycode != 'langcode' && $keycode != 'position' && $keycode != 'private' && !GETPOST($keycode))) $sql .= "null"; // langcode,... must be '' if not defined so the unique key that include lang will work + elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } - if (GETPOST($keycode) == '' || ($keycode != 'langcode' && $keycode != 'position' && $keycode != 'private' && !GETPOST($keycode))) $sql .= "null"; // langcode,... must be '' if not defined so the unique key that include lang will work - elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + $i++; + } - $i++; - } - $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; - //print $sql;exit; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - } else { - setEventMessages($db->error(), null, 'errors'); - } - } - } + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); + //print $sql;exit; + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + } else { + setEventMessages($db->error(), null, 'errors'); + } + } + } - if ($action == 'confirm_delete' && $confirm == 'yes') // delete - { - $rowidcol = "rowid"; + if ($action == 'confirm_delete' && $confirm == 'yes') // delete + { + $rowidcol = "rowid"; - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."=".((int) $rowid); - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // activate - if ($action == $acts[0]) - { - $rowidcol = "rowid"; + // activate + if ($action == $acts[0]) + { + $rowidcol = "rowid"; - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."=".((int) $rowid); - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } + } - // disable - if ($action == $acts[1]) - { - $rowidcol = "rowid"; + // disable + if ($action == $acts[1]) + { + $rowidcol = "rowid"; - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."=".((int) $rowid); - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } + } } @@ -409,13 +411,15 @@ if (empty($reshook)) $form = new Form($db); $formadmin = new FormAdmin($db); -llxHeader(); +$help_url = ''; +$title = $langs->trans("EMailsSetup"); + +llxHeader('', $title); -$titre = $langs->trans("EMailsSetup"); $linkback = ''; $titlepicto = 'title_setup'; -print load_fiche_titre($titre, $linkback, $titlepicto); +print load_fiche_titre($title, $linkback, $titlepicto); $head = email_admin_prepare_head(); @@ -424,7 +428,7 @@ dol_fiche_head($head, 'templates', '', -1); // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -439,7 +443,7 @@ if (!$user->admin) } if (empty($conf->global->MAIN_MULTILANGS)) { - $sql .= " AND (lang = '".$langs->defaultlang."' OR lang IS NULL OR lang = '')"; + $sql .= " AND (lang = '".$db->escape($langs->defaultlang)."' OR lang IS NULL OR lang = '')"; } if ($search_label) $sql .= natural_search('label', $search_label); if ($search_type_template != '' && $search_type_template != '-1') $sql .= natural_search('type_template', $search_type_template); @@ -454,148 +458,149 @@ $sql .= $db->plimit($listlimit + 1, $offset); $fieldlist = explode(',', $tabfield[$id]); -// Form to add a new line -print ''; -print ''; -print ''; +if ($action == 'view') { + // Form to add a new line + print ''; + print ''; + print ''; -print '
'; -print ''; + print '
'; + print '
'; -// Line to enter new values (title) -print ''; -foreach ($fieldlist as $field => $value) -{ - // 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 = "left"; - if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); } - if ($fieldlist[$field] == 'lang') { $valuetoshow = (empty($conf->global->MAIN_MULTILANGS) ? ' ' : $langs->trans("Language")); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field] == 'private') { $align = 'center'; } - if ($fieldlist[$field] == 'position') { $align = 'center'; } - - if ($fieldlist[$field] == 'topic') { $valuetoshow = ''; } - if ($fieldlist[$field] == 'joinfiles') { $valuetoshow = ''; } - if ($fieldlist[$field] == 'content') { $valuetoshow = ''; } - if ($fieldlist[$field] == 'content_lines') { $valuetoshow = ''; } - - if ($valuetoshow != '') + // Line to enter new values (title) + print ''; + foreach ($fieldlist as $field => $value) { - print ''; + print ''; + } } -} -print ''; -print ''; + print ''; + print ''; -$obj = new stdClass(); -// If data was already input, we define them in obj to populate input fields. -if (GETPOST('actionadd')) -{ - foreach ($fieldlist as $key => $val) { - if (GETPOST($val) != '') + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key => $val) { + if (GETPOST($val) != '') $obj->$val = GETPOST($val); + } } -} -$tmpaction = 'create'; -$parameters = array( + $tmpaction = 'create'; + $parameters = array( 'fieldlist' => $fieldlist, 'tabname' => $tabname[$id] -); -$reshook = $hookmanager->executeHooks('createEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks -$error = $hookmanager->error; -$errors = $hookmanager->errors; + ); + $reshook = $hookmanager->executeHooks('createEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; + $errors = $hookmanager->errors; -// Line to enter new values (input fields) -print ''; + // Line to enter new values (input fields) + print ''; -if (empty($reshook)) -{ - if ($action == 'edit') { - fieldList($fieldlist, $obj, $tabname[$id], 'hide'); - } else { - fieldList($fieldlist, $obj, $tabname[$id], 'add'); - } -} - -print ''; -print ""; - -// Show fields for topic, join files and body -$fieldsforcontent = array('topic', 'joinfiles', 'content'); -if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('content', 'content_lines'); } -foreach ($fieldsforcontent as $tmpfieldlist) -{ - print ''; + print ""; + + // Show fields for topic, join files and body + $fieldsforcontent = array('topic', 'joinfiles', 'content'); + if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); } + foreach ($fieldsforcontent as $tmpfieldlist) { - print ''.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; - } - if ($tmpfieldlist == 'content') + print ''; - if ($tmpfieldlist == 'topic') { - print ''; + if ($tmpfieldlist == 'topic') { + print ''; + } + // else print ''; + print ''; } - // else print ''; - print ''; -} -$colspan = count($fieldlist) + 1; -//print ''; // Keep   to have a line with enough height - -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])) + // 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 = "left"; + if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); } + if ($fieldlist[$field] == 'lang') { $valuetoshow = (empty($conf->global->MAIN_MULTILANGS) ? ' ' : $langs->trans("Language")); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); } + if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field] == 'private') { $align = 'center'; } + if ($fieldlist[$field] == 'position') { $align = 'center'; } + + if ($fieldlist[$field] == 'topic') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'joinfiles') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'content') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'content_lines') { $valuetoshow = ''; } + + if ($valuetoshow != '') { - if (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value); // Tooltip on click - else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover - } else print $valuetoshow; - 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 (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value); // Tooltip on click + else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover + } else print $valuetoshow; + print ''; -print ''; -print '
'; + print ''; + print '
'; -print '
'; - - // Label - if ($tmpfieldlist == 'topic') + if (empty($reshook)) { - print ''.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; + if ($action == 'edit') { + fieldList($fieldlist, $obj, $tabname[$id], 'hide'); + } else { + fieldList($fieldlist, $obj, $tabname[$id], 'add'); + } } - if ($tmpfieldlist == 'joinfiles') + + print ''; + print '
'; + + // Label + if ($tmpfieldlist == 'topic') + { + print ''.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; + } + if ($tmpfieldlist == 'joinfiles') + { + print ''.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; + } + if ($tmpfieldlist == 'content') print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; - if ($tmpfieldlist == 'content_lines') + if ($tmpfieldlist == 'content_lines') print $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; - // Input field - if ($tmpfieldlist == 'topic') { - print ''; - } elseif ($tmpfieldlist == 'joinfiles') { - print ''; - } else { - if ($context != 'hide') { - // print ''; - $okforextended = true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) + // Input field + if ($tmpfieldlist == 'topic') { + print ''; + } elseif ($tmpfieldlist == 'joinfiles') { + print ''; + } else { + if ($context != 'hide') { + // print ''; + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; - $doleditor = new DolEditor($tmpfieldlist, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); - print $doleditor->Create(1); - } else print ' '; - } - print '
'; - if ($action != 'edit') { - print ''; + $doleditor = new DolEditor($tmpfieldlist, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 500, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); + print $doleditor->Create(1); + } else print ' '; } print ''; + if ($action != 'edit') { + print ''; + } + print '
 
'; -print '
'; -print ''; -print '
'; + $colspan = count($fieldlist) + 1; + //print '
 
'; + print ''; + print ''; + print '
'; +} // END IF not edit print '
'; print ''; @@ -609,90 +614,90 @@ dol_syslog("htdocs/admin/dict", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - $param = '&id='.$id; - if ($search_label) $param .= '&search_label='.urlencode($search_label); - if ($search_lang > 0) $param .= '&search_lang='.urlencode($search_lang); - if ($search_type_template != '-1') $param .= '&search_type_template='.urlencode($search_type_template); - if ($search_fk_user > 0) $param .= '&search_fk_user='.urlencode($search_fk_user); - if ($search_topic) $param .= '&search_topic='.urlencode($search_topic); + $param = '&id='.$id; + if ($search_label) $param .= '&search_label='.urlencode($search_label); + if ($search_lang > 0) $param .= '&search_lang='.urlencode($search_lang); + if ($search_type_template != '-1') $param .= '&search_type_template='.urlencode($search_type_template); + if ($search_fk_user > 0) $param .= '&search_fk_user='.urlencode($search_fk_user); + if ($search_topic) $param .= '&search_topic='.urlencode($search_topic); - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch .= '&sortorder='.urlencode($sortorder); - if ($sortfield) $paramwithsearch .= '&sortfield='.urlencode($sortfield); - if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.urlencode(GETPOST('from', 'alpha')); + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch .= '&sortorder='.urlencode($sortorder); + if ($sortfield) $paramwithsearch .= '&sortfield='.urlencode($sortfield); + if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.urlencode(GETPOST('from', 'alpha')); - // There is several pages - if ($num > $listlimit) - { - print ''; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print ''; - } + // There is several pages + if ($num > $listlimit) + { + print ''; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print ''; + } - // Title line with search boxes - print ''; + // Title line with search boxes + print ''; - $filterfound = 0; - foreach ($fieldlist as $field => $value) - { - if ($value == 'label') { - print ''; - } elseif ($value == 'lang') { - print ''; - print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1, 0, 0, 'maxwidth100'); - print ''; - } elseif ($value == 'fk_user') { - print ''; - $restrictid = array(); - if (!$user->admin) $restrictid = array($user->id); - //var_dump($restrictid); - print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, 'hierarchyme', null, 0, 0, 1, '', 0, '', 'maxwidth100'); - print ''; - } elseif ($value == 'topic') { - print ''; - } elseif ($value == 'type_template') { - print ''.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100 maxwidth100onsmartphone').''; - } elseif (!in_array($value, array('content', 'content_lines'))) { - print ''; - } - } + $filterfound = 0; + foreach ($fieldlist as $field => $value) + { + if ($value == 'label') { + print ''; + } elseif ($value == 'lang') { + print ''; + print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1, 0, 0, 'maxwidth100'); + print ''; + } elseif ($value == 'fk_user') { + print ''; + $restrictid = array(); + if (!$user->admin) $restrictid = array($user->id); + //var_dump($restrictid); + print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, 'hierarchyme', null, 0, 0, 1, '', 0, '', 'maxwidth100'); + print ''; + } elseif ($value == 'topic') { + print ''; + } elseif ($value == 'type_template') { + print ''.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100 maxwidth100onsmartphone').''; + } elseif (!in_array($value, array('content', 'content_lines'))) { + print ''; + } + } - if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print ''; + if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print ''; - // Action column - print ''; - $searchpicto = $form->showFilterButtons(); - print $searchpicto; - print ''; - print ''; + // Action column + print ''; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print ''; + print ''; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - $showfield = 1; // By defaut - $align = "left"; - $sortable = 1; - $valuetoshow = ''; - $forcenowrap = 1; - /* + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + $showfield = 1; // By defaut + $align = "left"; + $sortable = 1; + $valuetoshow = ''; + $forcenowrap = 1; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow = ucfirst($fieldlist[$field]); // By defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); } - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); } + $valuetoshow = ucfirst($fieldlist[$field]); // By defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); } + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); } + if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); } if ($fieldlist[$field] == 'private') { $align = 'center'; } if ($fieldlist[$field] == 'position') { $align = 'center'; } @@ -700,99 +705,99 @@ if ($resql) if ($fieldlist[$field] == 'content') { $valuetoshow = $langs->trans("Content"); $showfield = 0; } if ($fieldlist[$field] == 'content_lines') { $valuetoshow = $langs->trans("ContentLines"); $showfield = 0; } - // Show fields - if ($showfield) - { - if (!empty($tabhelp[$id][$value])) - { - if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltip'.$value, $forcenowrap); // Tooltip on click - else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, '', $forcenowrap); // Tooltip on hover - } - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, "align=".$align, $sortfield, $sortorder); - } - } + // Show fields + if ($showfield) + { + if (!empty($tabhelp[$id][$value])) + { + if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltip'.$value, $forcenowrap); // Tooltip on click + else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, '', $forcenowrap); // Tooltip on hover + } + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, "align=".$align, $sortfield, $sortorder); + } + } - print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); + print getTitleFieldOfList(''); + print ''; - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { - print ''; + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) + { + print ''; - $tmpaction = 'edit'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('editEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - // Show fields - if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + // Show fields + if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit'); - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + print ''; + print ''; - $fieldsforcontent = array('topic', 'joinfiles', 'content'); - if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) - { - $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); - } - foreach ($fieldsforcontent as $tmpfieldlist) - { - $showfield = 1; - $align = "left"; - $valuetoshow = $obj->{$tmpfieldlist}; + $fieldsforcontent = array('topic', 'joinfiles', 'content'); + if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) + { + $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); + } + foreach ($fieldsforcontent as $tmpfieldlist) + { + $showfield = 1; + $align = "left"; + $valuetoshow = $obj->{$tmpfieldlist}; - $class = 'tddict'; - // Show value for field - if ($showfield) { + $class = 'tddict'; + // Show value for field + if ($showfield) { // Show line for topic, joinfiles and content - print ''; - print ''; - if ($tmpfieldlist == 'topic') - { - print ''.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; - print ''; - } - if ($tmpfieldlist == 'joinfiles') - { - print ''.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; - print ''; - } - if ($tmpfieldlist == 'content') - { - print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; - $okforextended = true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; - $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); - print $doleditor->Create(1); - } - print ''; - print ''; - print ''; - } - } + print ''; + print ''; + if ($tmpfieldlist == 'topic') + { + print ''.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; + print ''; + } + if ($tmpfieldlist == 'joinfiles') + { + print ''.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).' '; + print ''; + } + if ($tmpfieldlist == 'content') + { + print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'
'; + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; + $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 500, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); + print $doleditor->Create(1); + } + print ''; + print ''; + print ''; + } + } - print "\n"; - } else { - $keyforobj = 'type_template'; - if (!in_array($obj->$keyforobj, array_keys($elementList))) - { - $i++; - continue; // It means this is a type of template not into elementList (may be because enabled condition of this type is false because module is not enabled) - } + print "\n"; + } else { + $keyforobj = 'type_template'; + if (!in_array($obj->$keyforobj, array_keys($elementList))) + { + $i++; + continue; // It means this is a type of template not into elementList (may be because enabled condition of this type is false because module is not enabled) + } // Test on 'enabled' if (!dol_eval($obj->enabled, 1)) { @@ -800,100 +805,100 @@ if ($resql) continue; // Email template not qualified } - print ''; + print ''; - $tmpaction = 'view'; - $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $tmpaction = 'view'; + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - if (in_array($fieldlist[$field], array('content', 'content_lines'))) continue; - $showfield = 1; - $align = "left"; - $valuetoshow = $obj->{$fieldlist[$field]}; - if ($value == 'label' || $value == 'topic') - { - $valuetoshow = dol_escape_htmltag($valuetoshow); - } - if ($value == 'type_template') - { - $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; - } - if ($value == 'lang' && $valuetoshow) - { - $valuetoshow = $valuetoshow.' - '.$langs->trans("Language_".$valuetoshow); - } - if ($value == 'fk_user') - { - if ($valuetoshow > 0) - { - $fuser = new User($db); - $fuser->fetch($valuetoshow); - $valuetoshow = $fuser->getNomUrl(1); - } - } - if ($value == 'private') - { - $align = "center"; - if ($valuetoshow) $valuetoshow = yn($valuetoshow); - else $valuetoshow = ''; - } - if ($value == 'position') - { - $align = "center"; - } - if ($value == 'joinfiles') - { - $align = "center"; - if ($valuetoshow) $valuetoshow = 1; - else $valuetoshow = ''; - } + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { + if (in_array($fieldlist[$field], array('content', 'content_lines'))) continue; + $showfield = 1; + $align = "left"; + $valuetoshow = $obj->{$fieldlist[$field]}; + if ($value == 'label' || $value == 'topic') + { + $valuetoshow = dol_escape_htmltag($valuetoshow); + } + if ($value == 'type_template') + { + $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; + } + if ($value == 'lang' && $valuetoshow) + { + $valuetoshow = $valuetoshow.' - '.$langs->trans("Language_".$valuetoshow); + } + if ($value == 'fk_user') + { + if ($valuetoshow > 0) + { + $fuser = new User($db); + $fuser->fetch($valuetoshow); + $valuetoshow = $fuser->getNomUrl(1); + } + } + if ($value == 'private') + { + $align = "center"; + if ($valuetoshow) $valuetoshow = yn($valuetoshow); + else $valuetoshow = ''; + } + if ($value == 'position') + { + $align = "center"; + } + if ($value == 'joinfiles') + { + $align = "center"; + if ($valuetoshow) $valuetoshow = 1; + else $valuetoshow = ''; + } - $class = 'tddict'; + $class = 'tddict'; // Show value for field if ($showfield) { - print ''; - print ''.$valuetoshow.''; + print ''; + print ''.$valuetoshow.''; } - } - } + } + } - // Can an entry be erased or disabled ? - $iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default - if (!$user->admin && $obj->fk_user != $user->id) - { - $iserasable = 0; - $canbedisabled = 0; - $canbemodified = 0; - } + // Can an entry be erased or disabled ? + $iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default + if (!$user->admin && $obj->fk_user != $user->id) + { + $iserasable = 0; + $canbedisabled = 0; + $canbemodified = 0; + } - $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) : ''); - if ($param) $url .= '&'.$param; - $url .= '&'; + $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) : ''); + if ($param) $url .= '&'.$param; + $url .= '&'; - // Status / Active - print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else print ''.$actl[$obj->active].''; - print ""; + // Status / Active + print ''; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else print ''.$actl[$obj->active].''; + print ""; - // Modify link / Delete link - print ''; - if ($canbemodified) print ''.img_edit().''; - if ($iserasable) - { - print ''.img_delete().''; - //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - } - print ''; + // Modify link / Delete link + print ''; + if ($canbemodified) print ''.img_edit().''; + if ($iserasable) + { + print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin + } + print ''; - /* + /* $fieldsforcontent = array('content'); if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { @@ -921,15 +926,15 @@ if ($resql) } }*/ - print "\n"; - } + print "\n"; + } - $i++; - } - } + $i++; + } + } } else { - dol_print_error($db); + dol_print_error($db); } print ''; @@ -1028,7 +1033,7 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') else { $size = ''; $class = ''; $classtd = ''; if ($fieldlist[$field] == 'code') $class = 'maxwidth100'; - if ($fieldlist[$field] == 'label') $class = 'maxwidth100'; + if ($fieldlist[$field] == 'label') $class = 'maxwidth200'; if ($fieldlist[$field] == 'private') { $class = 'maxwidth50'; $classtd = 'center'; } if ($fieldlist[$field] == 'position') { $class = 'maxwidth50'; $classtd = 'center'; } if ($fieldlist[$field] == 'libelle') $class = 'quatrevingtpercent'; diff --git a/htdocs/admin/mails_ticket.php b/htdocs/admin/mails_ticket.php new file mode 100644 index 00000000000..39e159535ba --- /dev/null +++ b/htdocs/admin/mails_ticket.php @@ -0,0 +1,574 @@ + + * Copyright (C) 2009-2012 Regis Houssin + * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2016 Jonathan TISSEAU + * + * 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/mails_ticket.php + * \brief Page to setup mails for ticket + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array('companies', 'products', 'admin', 'mails', 'other', 'errors')); + +$action = GETPOST('action', 'aZ09'); + +if (!$user->admin) accessforbidden(); + +$usersignature = $user->signature; +// For action = test or send, we ensure that content is not html, even for signature, because this we want a test with NO html. +if ($action == 'test' || $action == 'send') +{ + $usersignature = dol_string_nohtmltag($usersignature); +} + +$substitutionarrayfortest = array( +'__LOGIN__' => $user->login, +'__ID__' => 'TESTIdRecord', +'__EMAIL__' => 'TESTEMail', +'__LASTNAME__' => 'TESTLastname', +'__FIRSTNAME__' => 'TESTFirstname', +'__USER_SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? $usersignature : ''), +//'__PERSONALIZED__' => 'TESTPersonalized' // Hiden because not used yet +); +complete_substitutions_array($substitutionarrayfortest, $langs); + + + +/* + * Actions + */ + +if ($action == 'update' && empty($_POST["cancel"])) +{ + // Send mode parameters + dolibarr_set_const($db, "MAIN_MAIL_SENDMODE_TICKET", GETPOST("MAIN_MAIL_SENDMODE_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT_TICKET", GETPOST("MAIN_MAIL_SMTP_PORT_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER_TICKET", GETPOST("MAIN_MAIL_SMTP_SERVER_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID_TICKET", GETPOST("MAIN_MAIL_SMTPS_ID_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW_TICKET", GETPOST("MAIN_MAIL_SMTPS_PW_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS_TICKET", GETPOST("MAIN_MAIL_EMAIL_TLS_TICKET"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS_TICKET", GETPOST("MAIN_MAIL_EMAIL_STARTTLS_TICKET"), 'chaine', 0, '', $conf->entity); + + header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); + exit; +} + + +// Actions to send emails +$id = 0; +$actiontypecode = ''; // Not an event for agenda +$triggersendname = ''; // Disable triggers +$paramname = 'id'; +$mode = 'emailfortest'; +$trackid = (($action == 'testhtml') ? "testhtml" : "test"); +$sendcontext = 'ticket'; // Force to use dedicated context of setup for ticket +include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + +if ($action == 'presend' && GETPOST('trackid') == 'test') $action = 'test'; +if ($action == 'presend' && GETPOST('trackid') == 'testhtml') $action = 'testhtml'; + + + + +/* + * View + */ + +$form = new Form($db); + +$linuxlike = 1; +if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; +if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + +if (empty($conf->global->MAIN_MAIL_SENDMODE_TICKET)) $conf->global->MAIN_MAIL_SENDMODE_TICKET = 'default'; +$port = !empty($conf->global->MAIN_MAIL_SMTP_PORT_TICKET) ? $conf->global->MAIN_MAIL_SMTP_PORT_TICKET : ini_get('smtp_port'); +if (!$port) $port = 25; +$server = !empty($conf->global->MAIN_MAIL_SMTP_SERVER_TICKET) ? $conf->global->MAIN_MAIL_SMTP_SERVER_TICKET : ini_get('SMTP'); +if (!$server) $server = '127.0.0.1'; + + +$wikihelp = 'EN:Setup_EMails|FR:Paramétrage_EMails|ES:Configuración_EMails'; +llxHeader('', $langs->trans("Setup"), $wikihelp); + +print load_fiche_titre($langs->trans("EMailsSetup"), '', 'title_setup'); + +$head = email_admin_prepare_head(); + +// List of sending methods +$listofmethods = array(); +$listofmethods['default'] = $langs->trans('DefaultOutgoingEmailSetup'); +$listofmethods['mail'] = 'PHP mail function'; +//$listofmethods['simplemail']='Simplemail class'; +$listofmethods['smtps'] = 'SMTP/SMTPS socket library'; +if (version_compare(phpversion(), '7.0', '>=')) $listofmethods['swiftmailer'] = 'Swift Mailer socket library'; + + +if ($action == 'edit') +{ + if ($conf->use_javascript_ajax) + { + print "\n".''."\n"; + } + + print ''; + print ''; + print ''; + + dol_fiche_head($head, 'common_ticket', '', -1); + + print ''.$langs->trans("EMailsDesc")."
\n"; + print "
\n"; + + + clearstatcache(); + + print ''; + print ''; + + // Method + + print ''; + + // Host server + + print ''; + + // Port + + print ''; + + // ID + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer')))) + { + $mainstmpid = (!empty($conf->global->MAIN_MAIL_SMTPS_ID_TICKET) ? $conf->global->MAIN_MAIL_SMTPS_ID_TICKET : ''); + print ''; + } + + // PW + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer')))) + { + $mainsmtppw = (!empty($conf->global->MAIN_MAIL_SMTPS_PW_TICKET) ? $conf->global->MAIN_MAIL_SMTPS_PW_TICKET : ''); + print ''; + } + + // TLS + + print ''; + + // STARTTLS + + print ''; + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; + + // SuperAdministrator access only + if ((empty($conf->global->MAIN_MODULE_MULTICOMPANY)) || ($user->admin && !$user->entity)) + { + print $form->selectarray('MAIN_MAIL_SENDMODE_TICKET', $listofmethods, $conf->global->MAIN_MAIL_SENDMODE_TICKET); + } else { + $text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE_TICKET]; + if (empty($text)) $text = $langs->trans("Undefined"); + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text, $htmltext, 1, 'superadmin'); + print ''; + } + print '
'; + if (!$conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail') + { + print $langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike"); + print ''; + print $langs->trans("SeeLocalSendMailSetup"); + } else { + $mainserver = (!empty($conf->global->MAIN_MAIL_SMTP_SERVER_TICKET) ? $conf->global->MAIN_MAIL_SMTP_SERVER_TICKET : ''); + $smtpserver = ini_get('SMTP') ?ini_get('SMTP') : $langs->transnoentities("Undefined"); + if ($linuxlike) print $langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike"); + else print $langs->trans("MAIN_MAIL_SMTP_SERVER", $smtpserver); + print ''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + print ''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; + } else { + $text = !empty($mainserver) ? $mainserver : $smtpserver; + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text, $htmltext, 1, 'superadmin'); + print ''; + } + } + print '
'; + if (!$conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail') + { + print $langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike"); + print ''; + print $langs->trans("SeeLocalSendMailSetup"); + } else { + $mainport = (!empty($conf->global->MAIN_MAIL_SMTP_PORT_TICKET) ? $conf->global->MAIN_MAIL_SMTP_PORT_TICKET : ''); + $smtpport = ini_get('smtp_port') ?ini_get('smtp_port') : $langs->transnoentities("Undefined"); + if ($linuxlike) print $langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike"); + else print $langs->trans("MAIN_MAIL_SMTP_PORT", $smtpport); + print ''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + print ''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; + } else { + $text = (!empty($mainport) ? $mainport : $smtpport); + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($text, $htmltext, 1, 'superadmin'); + print ''; + } + } + print '
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + } else { + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($conf->global->MAIN_MAIL_SMTPS_ID_TICKET, $htmltext, 1, 'superadmin'); + print ''; + } + print '
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''; + // SuperAdministrator access only + if (empty($conf->multicompany->enabled) || ($user->admin && !$user->entity)) + { + print ''; + } else { + $htmltext = $langs->trans("ContactSuperAdminForChange"); + print $form->textwithpicto($conf->global->MAIN_MAIL_SMTPS_PW_TICKET, $htmltext, 1, 'superadmin'); + print ''; + } + print '
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_TLS_TICKET', (!empty($conf->global->MAIN_MAIL_EMAIL_TLS_TICKET) ? $conf->global->MAIN_MAIL_EMAIL_TLS_TICKET : 0), 1); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; + if (!empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_STARTTLS_TICKET', (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS_TICKET) ? $conf->global->MAIN_MAIL_EMAIL_STARTTLS_TICKET : 0), 1); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + print ''; +} else { + dol_fiche_head($head, 'common_ticket', '', -1); + + print ''.$langs->trans("EMailsDesc")."
\n"; + print "
\n"; + + print ''; + print ''; + + // Method + print ''; + + if (!empty($conf->global->MAIN_MAIL_SENDMODE_TICKET) && $conf->global->MAIN_MAIL_SENDMODE_TICKET != 'default') + { + // Host server + if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && $conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail')) + { + print ''; + } else { + print ''; + } + + // Port + if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && $conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail')) + { + print ''; + } else { + print ''; + } + + // SMTPS ID + if (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer'))) + { + print ''; + } + + // SMTPS PW + if (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer'))) + { + print ''; + } + + // TLS + print ''; + + // STARTTLS + print ''; + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; + $text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE_TICKET]; + if (empty($text)) $text = $langs->trans("Undefined").img_warning(); + print $text; + print '
'.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_SERVER", ini_get('SMTP') ?ini_get('SMTP') : $langs->transnoentities("Undefined")).''.(!empty($conf->global->MAIN_MAIL_SMTP_SERVER_TICKET) ? $conf->global->MAIN_MAIL_SMTP_SERVER_TICKET : '').'
'.$langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_PORT", ini_get('smtp_port') ?ini_get('smtp_port') : $langs->transnoentities("Undefined")).''.(!empty($conf->global->MAIN_MAIL_SMTP_PORT_TICKET) ? $conf->global->MAIN_MAIL_SMTP_PORT_TICKET : '').'
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''.$conf->global->MAIN_MAIL_SMTPS_ID_TICKET.'
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./', '*', $conf->global->MAIN_MAIL_SMTPS_PW_TICKET).'
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_TLS_TICKET); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE_TICKET) && in_array($conf->global->MAIN_MAIL_SENDMODE_TICKET, array('smtps', 'swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_STARTTLS_TICKET); + } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'; + + dol_fiche_end(); + + + if ($conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + print '
'; + /* + // Warning 1 + if ($linuxlike) + { + $sendmailoption=ini_get('mail.force_extra_parameters'); + if (empty($sendmailoption) || ! preg_match('/ba/',$sendmailoption)) + { + print info_admin($langs->trans("SendmailOptionNotComplete")); + } + }*/ + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } + + + // Buttons for actions + + print '
'; + + print ''.$langs->trans("Modify").''; + + if (!empty($conf->global->MAIN_MAIL_SENDMODE_TICKET) && $conf->global->MAIN_MAIL_SENDMODE_TICKET != 'default') + { + if ($conf->global->MAIN_MAIL_SENDMODE_TICKET != 'mail' || !$linuxlike) + { + if (function_exists('fsockopen') && $port && $server) + { + print ''.$langs->trans("DoTestServerAvailability").''; + } + } else { + print ''.$langs->trans("DoTestServerAvailability").''; + } + + print ''.$langs->trans("DoTestSend").''; + + if (!empty($conf->fckeditor->enabled)) + { + print ''.$langs->trans("DoTestSendHTML").''; + } + } + + print '
'; + + + if ($conf->global->MAIN_MAIL_SENDMODE_TICKET == 'mail' && !in_array($action, array('testconnect', 'test', 'testhtml'))) + { + $text = $langs->trans("WarningPHPMail"); + print info_admin($text); + } + + // Run the test to connect + if ($action == 'testconnect') + { + print load_fiche_titre($langs->trans("DoTestServerAvailability")); + + include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mail = new CMailFile('', '', '', '', array(), array(), array(), '', '', 0, '', '', '', '', $trackid, $sendcontext); + + $result = $mail->check_server_port($server, $port); + if ($result) print '
'.$langs->trans("ServerAvailableOnIPOrPort", $server, $port).'
'; + else { + $errormsg = $langs->trans("ServerNotAvailableOnIPOrPort", $server, $port); + + if ($mail->error) { + $errormsg .= ' - '.$mail->error; + } + + setEventMessages($errormsg, null, 'errors'); + } + print '
'; + } + + // Show email send test form + if ($action == 'test' || $action == 'testhtml') + { + print '
'; + print load_fiche_titre($action == 'testhtml' ? $langs->trans("DoTestSendHTML") : $langs->trans("DoTestSend")); + + dol_fiche_head(''); + + // Cree l'objet formulaire mail + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + $formmail->fromname = (isset($_POST['fromname']) ? $_POST['fromname'] : $conf->global->MAIN_MAIL_EMAIL_FROM); + $formmail->frommail = (isset($_POST['frommail']) ? $_POST['frommail'] : $conf->global->MAIN_MAIL_EMAIL_FROM); + $formmail->trackid = (($action == 'testhtml') ? "testhtml" : "test"); + $formmail->withfromreadonly = 0; + $formmail->withsubstit = 0; + $formmail->withfrom = 1; + $formmail->witherrorsto = 1; + $formmail->withto = (!empty($_POST['sendto']) ? $_POST['sendto'] : ($user->email ? $user->email : 1)); + $formmail->withtocc = (!empty($_POST['sendtocc']) ? $_POST['sendtocc'] : 1); // ! empty to keep field if empty + $formmail->withtoccc = (!empty($_POST['sendtoccc']) ? $_POST['sendtoccc'] : 1); // ! empty to keep field if empty + $formmail->withtopic = (isset($_POST['subject']) ? $_POST['subject'] : $langs->trans("Test")); + $formmail->withtopicreadonly = 0; + $formmail->withfile = 2; + $formmail->withbody = (isset($_POST['message']) ? $_POST['message'] : ($action == 'testhtml' ? $langs->transnoentities("PredefinedMailTestHtml") : $langs->transnoentities("PredefinedMailTest"))); + $formmail->withbodyreadonly = 0; + $formmail->withcancel = 1; + $formmail->withdeliveryreceipt = 1; + $formmail->withfckeditor = ($action == 'testhtml' ? 1 : 0); + $formmail->ckeditortoolbar = 'dolibarr_mailings'; + // Tableau des substitutions + $formmail->substit = $substitutionarrayfortest; + // Tableau des parametres complementaires du post + $formmail->param["action"] = "send"; + $formmail->param["models"] = "body"; + $formmail->param["mailid"] = 0; + $formmail->param["returnurl"] = $_SERVER["PHP_SELF"]; + + // Init list of files + if (GETPOST("mode") == 'init') + { + $formmail->clear_attached_files(); + } + + print $formmail->get_form('addfile', 'removefile'); + + dol_fiche_end(); + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index d92a3b30504..31e0f896633 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -31,7 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php'; // Load translation files required by the page $langs->loadLangs(array("other", "admin")); -$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$cancel = GETPOST('cancel', 'alphanohtml'); // We click on a Cancel button +$confirm = GETPOST('confirm'); if (!$user->admin) accessforbidden(); @@ -40,8 +41,8 @@ $dirsmartphone = array(); $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']); foreach ($dirmenus as $dirmenu) { - $dirstandard[] = $dirmenu.'standard'; - $dirsmartphone[] = $dirmenu.'smartphone'; + $dirstandard[] = $dirmenu.'standard'; + $dirsmartphone[] = $dirmenu.'smartphone'; } $action = GETPOST('action', 'aZ09'); @@ -66,194 +67,193 @@ if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); if ($action == 'update') { - if (!$cancel) - { - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { - $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + if (!$cancel) + { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuIdParent', 'alphanohtml') && !is_numeric(GETPOST('menuIdParent', 'alphanohtml'))) + { + $tmp = explode('&', GETPOST('menuIdParent', 'alphanohtml')); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { + $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - if ($result > 0) - { - $menu->titre = GETPOST('titre', 'alpha'); // deprecated - $menu->title = GETPOST('titre', 'alpha'); - $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuIdParent', 'alpha'))) - { - $menu->fk_menu = GETPOST('menuIdParent', 'alpha'); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + if ($result > 0) + { + $menu->title = GETPOST('titre', 'alphanohtml'); + $menu->leftmenu = GETPOST('leftmenu', 'aZ09'); + $menu->url = GETPOST('url', 'alphanohtml'); + $menu->langs = GETPOST('langs', 'alphanohtml'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alphanohtml'); + $menu->perms = GETPOST('perms', 'alphanohtml'); + $menu->target = GETPOST('target', 'alphanohtml'); + $menu->user = GETPOST('user', 'alphanohtml'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alphanohtml'); + if (is_numeric(GETPOST('menuIdParent', 'alphanohtml'))) + { + $menu->fk_menu = GETPOST('menuIdParent', 'alphanohtml'); + } else { + if (GETPOST('type', 'alphanohtml') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->update($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } else { - setEventMessages($menu->error, $menu->errors, 'errors'); - } - $action = "edit"; + $result = $menu->update($user); + if ($result > 0) + { + setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } else { + setEventMessages($menu->error, $menu->errors, 'errors'); + } + $action = "edit"; - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } else { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } else { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } } if ($action == 'add') { - if ($cancel) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); - exit; - } + if ($cancel) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); + exit; + } - $leftmenu = ''; $mainmenu = ''; - if (GETPOST('menuId', 'alpha', 3) && !is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $tmp = explode('&', GETPOST('menuId', 'alpha', 3)); - foreach ($tmp as $s) - { - if (preg_match('/fk_mainmenu=/', $s)) - { + $leftmenu = ''; $mainmenu = ''; + if (GETPOST('menuId', 'alphanohtml', 3) && !is_numeric(GETPOST('menuId', 'alphanohtml', 3))) + { + $tmp = explode('&', GETPOST('menuId', 'alphanohtml', 3)); + foreach ($tmp as $s) + { + if (preg_match('/fk_mainmenu=/', $s)) + { $mainmenu = preg_replace('/fk_mainmenu=/', '', $s); - } - if (preg_match('/fk_leftmenu=/', $s)) - { - $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); - } - } - } + } + if (preg_match('/fk_leftmenu=/', $s)) + { + $leftmenu = preg_replace('/fk_leftmenu=/', '', $s); + } + } + } - $langs->load("errors"); + $langs->load("errors"); - $error = 0; - if (!$error && !$_POST['menu_handler']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['type']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['url']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['titre']) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') - { - setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); - $action = 'create'; - $error++; - } - if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') - { - setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); - $action = 'create'; - $error++; - } + $error = 0; + if (!$error && !$_POST['menu_handler']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MenuHandler")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['type']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['url']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['titre']) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && $_POST['menuId'] && $_POST['type'] == 'top') + { + setEventMessages($langs->trans("ErrorTopMenuMustHaveAParentWithId0"), null, 'errors'); + $action = 'create'; + $error++; + } + if (!$error && !$_POST['menuId'] && $_POST['type'] == 'left') + { + setEventMessages($langs->trans("ErrorLeftMenuMustHaveAParentId"), null, 'errors'); + $action = 'create'; + $error++; + } - if (!$error) - { - $menu = new Menubase($db); - $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); - $menu->type = GETPOST('type', 'alpha'); - $menu->titre = GETPOST('titre', 'alpha'); // deprecated - $menu->title = GETPOST('titre', 'alpha'); - $menu->url = GETPOST('url', 'alpha'); - $menu->langs = GETPOST('langs', 'alpha'); - $menu->position = GETPOST('position', 'int'); - $menu->enabled = GETPOST('enabled', 'alpha'); - $menu->perms = GETPOST('perms', 'alpha'); - $menu->target = GETPOST('target', 'alpha'); - $menu->user = GETPOST('user', 'alpha'); - $menu->mainmenu = GETPOST('propertymainmenu', 'alpha'); - if (is_numeric(GETPOST('menuId', 'alpha', 3))) - { - $menu->fk_menu = GETPOST('menuId', 'alpha', 3); - } else { - if (GETPOST('type', 'alpha') == 'top') $menu->fk_menu = 0; - else $menu->fk_menu = -1; - $menu->fk_mainmenu = $mainmenu; - $menu->fk_leftmenu = $leftmenu; - } + if (!$error) + { + $menu = new Menubase($db); + $menu->menu_handler = preg_replace('/_menu$/', '', GETPOST('menu_handler', 'aZ09')); + $menu->type = GETPOST('type', 'alphanohtml'); + $menu->title = GETPOST('titre', 'alphanohtml'); + $menu->url = GETPOST('url', 'alphanohtml'); + $menu->langs = GETPOST('langs', 'alphanohtml'); + $menu->position = GETPOST('position', 'int'); + $menu->enabled = GETPOST('enabled', 'alphanohtml'); + $menu->perms = GETPOST('perms', 'alphanohtml'); + $menu->target = GETPOST('target', 'alphanohtml'); + $menu->user = GETPOST('user', 'alphanohtml'); + $menu->mainmenu = GETPOST('propertymainmenu', 'alphanohtml'); + if (is_numeric(GETPOST('menuId', 'alphanohtml', 3))) + { + $menu->fk_menu = GETPOST('menuId', 'alphanohtml', 3); + } else { + if (GETPOST('type', 'alphanohtml') == 'top') $menu->fk_menu = 0; + else $menu->fk_menu = -1; + $menu->fk_mainmenu = $mainmenu; + $menu->fk_leftmenu = $leftmenu; + } - $result = $menu->create($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); - exit; - } else { - $action = 'create'; - setEventMessages($menu->error, $menu->errors, 'errors'); - } - } + $result = $menu->create($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".GETPOST('menu_handler', 'aZ09')); + exit; + } else { + $action = 'create'; + setEventMessages($menu->error, $menu->errors, 'errors'); + } + } } // delete -if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') +if ($action == 'confirm_delete' && $confirm == 'yes') { - $this->db->begin(); + $db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); - $result = $db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); + $result = $db->query($sql); - if ($result == 0) - { - $this->db->commit(); + if ($result == 0) + { + $db->commit(); - llxHeader(); - setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); - llxFooter(); - exit; - } else { - $this->db->rollback(); + llxHeader(); + setEventMessages($langs->trans("MenuDeleted"), null, 'mesgs'); + llxFooter(); + exit; + } else { + $db->rollback(); - $reload = 0; - $_GET["action"] = ''; - } + $reload = 0; + $_GET["action"] = ''; + $action = ''; + } } @@ -270,7 +270,7 @@ llxHeader('', $langs->trans("Menu")); if ($action == 'create') { - print ''; - print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); + print load_fiche_titre($langs->trans("NewMenu"), '', 'title_setup'); - print '
'; - print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Id - $parent_rowid = GETPOST('menuId', 'int'); - if (GETPOST('menuId', 'int')) - { - $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); - $res = $db->query($sql); - if ($res) - { - while ($menu = $db->fetch_array($res)) - { - $parent_rowid = $menu['rowid']; - $parent_mainmenu = $menu['mainmenu']; - $parent_leftmenu = $menu['leftmenu']; - $parent_langs = $menu['langs']; - $parent_level = $menu['level']; - } - } - } + // Id + $parent_rowid = GETPOST('menuId', 'int'); + if (GETPOST('menuId', 'int')) + { + $sql = "SELECT m.rowid, m.mainmenu, m.leftmenu, m.level, m.langs FROM ".MAIN_DB_PREFIX."menu as m WHERE m.rowid = ".GETPOST('menuId', 'int'); + $res = $db->query($sql); + if ($res) + { + while ($menu = $db->fetch_array($res)) + { + $parent_rowid = $menu['rowid']; + $parent_mainmenu = $menu['mainmenu']; + $parent_leftmenu = $menu['leftmenu']; + $parent_langs = $menu['langs']; + $parent_level = $menu['level']; + } + } + } - // Handler - print ''; - print ''; - print ''; + // Handler + print ''; + print ''; + print ''; - // User - print ''; - print ''; - print ''; + // User + print ''; + print ''; + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - print ''; - print ''; - print ''; + // Mainmenu code + print ''; + print ''; + print ''; - // MenuId Parent - print ''; - if ($parent_rowid) - { - print ''; - } else { - print ''; - } - print ''; + // MenuId Parent + print ''; + if ($parent_rowid) + { + print ''; + } else { + print ''; + } + print ''; - // Title - print ''; + // Title + print ''; - // URL - print ''; + // URL + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('MenuHandler').''; - $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); - print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''; + $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/', $menu_handler) ? '' : '_menu'), 'menu_handler', array_merge($dirstandard, $dirsmartphone)); + print ''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''; - if ($parent_rowid) - { - print $langs->trans('Left'); - print ''; - } else { - print ''; - } - print ''.$langs->trans('DetailType').'
'.$langs->trans('Type').''; + if ($parent_rowid) + { + print $langs->trans('Left'); + print ''; + } else { + print ''; + } + print ''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').''; - print $langs->trans("Example").': mytopmenukey'; - print '
'.$langs->trans('MainMenuCode').''; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent').''.$parent_rowid.''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'.$langs->trans('Rights').''.$langs->trans('DetailRight').'
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; } elseif ($action == 'edit') { - print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); - print '
'; + print load_fiche_titre($langs->trans("ModifMenu"), '', 'title_setup'); + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - $menu = new Menubase($db); - $result = $menu->fetch(GETPOST('menuId', 'int')); - //var_dump($menu); + $menu = new Menubase($db); + $result = $menu->fetch(GETPOST('menuId', 'int')); + //var_dump($menu); - // Id - print ''; + // Id + print ''; - // Module - print ''; + // Module + print ''; - // Handler - if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); - else $handler = $menu->menu_handler; - print ''; + // Handler + if ($menu->menu_handler == 'all') $handler = $langs->trans('AllMenus'); + else $handler = $menu->menu_handler; + print ''; - // User - print ''; + // User + print ''; - // Type - print ''; + // Type + print ''; - // Mainmenu code - if ($menu->type == 'top') - { - print ''; - /*if ($parent_rowid) + // Mainmenu code + if ($menu->type == 'top') + { + print ''; + /*if ($parent_rowid) { print ''; } else {*/ - print ''; - //} - print ''; - } + print ''; + //} + print ''; + } - // MenuId Parent - print ''; - $valtouse = $menu->fk_menu; - if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; - if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; - print ''; - print ''; + // MenuId Parent + print ''; + $valtouse = $menu->fk_menu; + if ($menu->fk_mainmenu) $valtouse = 'fk_mainmenu='.$menu->fk_mainmenu; + if ($menu->fk_leftmenu) $valtouse .= '&fk_leftmenu='.$menu->fk_leftmenu; + print ''; + print ''; - // Niveau - //print ''; + // Niveau + //print ''; - // Title - print ''; + // Title + print ''; - // Url - print ''; + // Url + print ''; - // Langs - print ''; + // Langs + print ''; - // Position - print ''; + // Position + print ''; - // Target - print ''; + // Target + print ''; - // Enabled - print ''; + // Enabled + print ''; - // Perms - print ''; + // Perms + print ''; - print '
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('Id').''.$menu->id.''.$langs->trans('DetailId').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuModule').''.$menu->module.''.$langs->trans('DetailMenuModule').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuHandler').''.$handler.''.$langs->trans('DetailMenuHandler').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('MenuForUsers').''.$langs->trans('DetailUser').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('Type').''.$langs->trans(ucfirst($menu->type)).''.$langs->trans('DetailType').'
'.$langs->trans('MainMenuCode').'
'.$langs->trans('MainMenuCode').''.$parent_rowid.'mainmenu).'">'; - print $langs->trans("Example").': mytopmenukey'; - print '
mainmenu).'">'; + print $langs->trans("Example").': mytopmenukey'; + print '
'.$langs->trans('MenuIdParent'); - print ''.$langs->trans('DetailMenuIdParent'); - print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; - print '
'.$langs->trans('MenuIdParent'); + print ''.$langs->trans('DetailMenuIdParent'); + print ', '.$langs->trans("Example").': fk_mainmenu=abc&fk_leftmenu=def'; + print '
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Level').''.$menu->level.''.$langs->trans('DetailLevel').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('Title').''.$langs->trans('DetailTitre').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('URL').''.$langs->trans('DetailUrl').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('LangFile').''.$langs->trans('DetailLangs').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Position').''.$langs->trans('DetailPosition').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Target').''.$langs->trans('DetailTarget').'
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); - if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; - print '
'.$langs->trans('Enabled').''.$langs->trans('DetailEnabled'); + if (!empty($menu->enabled)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->enabled, 1)).')'; + print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); - if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; - print '
'.$langs->trans('Rights').''.$langs->trans('DetailRight'); + if (!empty($menu->perms)) print ' ('.$langs->trans("ConditionIsCurrently").': '.yn(dol_eval($menu->perms, 1)).')'; + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - // Bouton - print '
'; + // Bouton + print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; - print ''; + print ''; - print '
'; + print '
'; } // End of page diff --git a/htdocs/admin/menus/index.php b/htdocs/admin/menus/index.php index 095905afe8b..f83507c37aa 100644 --- a/htdocs/admin/menus/index.php +++ b/htdocs/admin/menus/index.php @@ -42,7 +42,7 @@ foreach ($dirmenus as $dirmenu) $dirsmartphone[] = $dirmenu.'smartphone'; } -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $menu_handler_top = $conf->global->MAIN_MENU_STANDARD; @@ -320,20 +320,20 @@ if ($conf->use_javascript_ajax) $titre = $langs->trans($menu['titre']); $entry = '
'; - $entry .= '   '.$titre.''; + $entry .= '   '.$titre.''; $entry .= ''; - $entry .= ''.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').' '; - $entry .= ''.img_edit_add('default').' '; - $entry .= ''.img_delete('default').' '; + $entry .= ''.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').' '; + $entry .= ''.img_edit_add('default').' '; + $entry .= ''.img_delete('default').' '; $entry .= '     '; - $entry .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; + $entry .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; $entry .= '
'; - $buttons = ''.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').' '; - $buttons .= ''.img_edit_add('default').' '; - $buttons .= ''.img_delete('default').' '; - $buttons .= '     '; - $buttons .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; + $buttons = ''.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').' '; + $buttons .= ''.img_edit_add('default').' '; + $buttons .= ''.img_delete('default').' '; + $buttons .= '     '; + $buttons .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; $data[] = array( 'rowid'=>$menu['rowid'], diff --git a/htdocs/admin/menus/other.php b/htdocs/admin/menus/other.php index 2fad8491e7a..cd8c7cccfa6 100644 --- a/htdocs/admin/menus/other.php +++ b/htdocs/admin/menus/other.php @@ -29,7 +29,7 @@ $langs->loadLangs(array("user", "other", "admin")); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); /* diff --git a/htdocs/admin/modulehelp.php b/htdocs/admin/modulehelp.php index 2e256f3c5ad..c788eca01d3 100644 --- a/htdocs/admin/modulehelp.php +++ b/htdocs/admin/modulehelp.php @@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->loadLangs(array('errors', 'admin', 'modulebuilder')); $mode = GETPOST('mode', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); if (empty($mode)) $mode = 'desc'; diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 3c525200442..c61e352aad8 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -40,7 +40,7 @@ $langs->loadLangs(array("errors", "admin", "modulebuilder")); $mode = GETPOSTISSET('mode') ? GETPOST('mode', 'alpha') : (empty($conf->global->MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT) ? 'commonkanban' : 'common'); if (empty($mode)) $mode = 'common'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); //var_dump($_POST);exit; $value = GETPOST('value', 'alpha'); $page_y = GETPOST('page_y', 'int'); @@ -797,7 +797,7 @@ if ($mode == 'common' || $mode == 'commonkanban') } } $codeenabledisable .= ''."\n"; - $codeenabledisable .= 'trans("Disabled"), 'switch_off'); diff --git a/htdocs/admin/mrp.php b/htdocs/admin/mrp.php index de1a6888de0..863633176bd 100644 --- a/htdocs/admin/mrp.php +++ b/htdocs/admin/mrp.php @@ -33,7 +33,7 @@ $langs->loadLangs(array('admin', 'errors', 'mrp', 'other')); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); @@ -56,11 +56,11 @@ if ($action == 'updateMask') if (!$res > 0) $error++; if (!$error) - { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'errors'); - } + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } elseif ($action == 'specimen') { $modele = GETPOST('module', 'alpha'); @@ -73,7 +73,7 @@ if ($action == 'updateMask') $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/mrp/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/mrp/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { $filefound = 1; @@ -111,7 +111,7 @@ elseif ($action == 'set') $ret = delDocumentModel($value, $type); if ($ret > 0) { - if ($conf->global->MRP_MO_ADDON_PDF == "$value") dolibarr_del_const($db, 'MRP_MO_ADDON_PDF', $conf->entity); + if ($conf->global->MRP_MO_ADDON_PDF == "$value") dolibarr_del_const($db, 'MRP_MO_ADDON_PDF', $conf->entity); } } @@ -145,25 +145,25 @@ elseif ($action == 'setdoc') if (!$res > 0) $error++; if (!$error) - { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'errors'); - } + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } elseif ($action == 'set_MRP_MO_FREE_TEXT') { - $freetext = GETPOST("MRP_MO_FREE_TEXT", 'none'); // No alpha here, we want exact string + $freetext = GETPOST("MRP_MO_FREE_TEXT", 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "MRP_MO_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); if (!$res > 0) $error++; if (!$error) - { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'errors'); - } + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } @@ -212,7 +212,7 @@ foreach ($dirmodels as $reldir) { while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 7) == 'mod_mo_' && substr($file, dol_strlen($file) - 3, 3) == 'php') + if (substr($file, 0, 7) == 'mod_mo_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); @@ -230,20 +230,20 @@ foreach ($dirmodels as $reldir) print $module->info(); print ''; - // Show example of numbering model - print ''; - $tmp = $module->getExample(); - if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); - else print $tmp; - print ''."\n"; + // Show example of numbering model + print ''; + $tmp = $module->getExample(); + if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); + else print $tmp; + print ''."\n"; print ''; if ($conf->global->MRP_MO_ADDON == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { - print '
'; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } @@ -257,16 +257,16 @@ foreach ($dirmodels as $reldir) $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; $mrp->type = 0; $nextval = $module->getNextValue($mysoc, $mrp); - 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).'
'; - } - } + 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 $form->textwithpicto('', $htmltooltip, 1, 0); @@ -293,7 +293,7 @@ print load_fiche_titre($langs->trans("MOsModelModule"), '', ''); $def = array(); $sql = "SELECT nom"; $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql .= " WHERE type = '".$type."'"; +$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -325,108 +325,108 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - foreach (array('', '/doc') as $valdir) - { - $realpath = $reldir."core/modules/mrp".$valdir; - $dir = dol_buildpath($realpath); + foreach (array('', '/doc') as $valdir) + { + $realpath = $reldir."core/modules/mrp".$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); + 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); + 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); + 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; + $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 ''; - print (empty($module->name) ? $name : $module->name); - print "\n"; - if (method_exists($module, 'info')) print $module->info($langs); - else print $module->description; - print ''; + 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; + print ''; - // Active - if (in_array($name, $def)) - { - print ''."\n"; - print ''; - print img_picto($langs->trans("Enabled"), 'switch_on'); - print ''; - print ''; - } else { - print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; - print ""; - } + // Active + if (in_array($name, $def)) + { + print ''."\n"; + print ''; + print img_picto($langs->trans("Enabled"), 'switch_on'); + print ''; + print ''; + } else { + print ''."\n"; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print ""; + } - // Default - print ''; - if ($conf->global->MRP_MO_ADDON_PDF == $name) - { - print img_picto($langs->trans("Default"), 'on'); - } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; - } - print ''; + // Default + print ''; + if ($conf->global->MRP_MO_ADDON_PDF == $name) + { + print img_picto($langs->trans("Default"), 'on'); + } else { + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + } + print ''; - // 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; + // 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("MultiLanguage").': '.yn($module->option_multilang, 1, 1); - $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftMOs").': '.yn($module->option_draft_watermark, 1, 1); + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftMOs").': '.yn($module->option_draft_watermark, 1, 1); - print ''; - print $form->textwithpicto('', $htmltooltip, 1, 0); - print ''; + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print ''; - // Preview - print ''; - if ($module->type == 'pdf') - { - print ''.img_object($langs->trans("Preview"), 'bill').''; - } else { - print img_object($langs->trans("PreviewNotAvailable"), 'generic'); - } - print ''; + // Preview + print ''; + if ($module->type == 'pdf') + { + print ''.img_object($langs->trans("Preview"), 'bill').''; + } else { + print img_object($langs->trans("PreviewNotAvailable"), 'generic'); + } + print ''; - print "\n"; - } - } - } - } - } - } - } + print "\n"; + } + } + } + } + } + } + } } print ''; @@ -458,11 +458,11 @@ print $form->textwithpicto($langs->trans("FreeLegalTextOnMOs"), $langs->trans("A $variablename = 'MRP_MO_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { - include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); - print $doleditor->Create(); + include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + print $doleditor->Create(); } print ''; print ''; diff --git a/htdocs/admin/mrp_extrafields.php b/htdocs/admin/mrp_extrafields.php index cab7232f569..b0bd0e522ab 100644 --- a/htdocs/admin/mrp_extrafields.php +++ b/htdocs/admin/mrp_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'mrp_mo'; diff --git a/htdocs/admin/multicurrency.php b/htdocs/admin/multicurrency.php index a7e073f08d2..a447551b04e 100644 --- a/htdocs/admin/multicurrency.php +++ b/htdocs/admin/multicurrency.php @@ -38,7 +38,7 @@ if (!$user->admin) { } // Parameters -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); /* diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php index a32cd0fa1f5..b484e7acea9 100644 --- a/htdocs/admin/notification.php +++ b/htdocs/admin/notification.php @@ -95,7 +95,7 @@ if ($action == 'setvalue' && $user->admin) { $db->begin(); - $result = dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", GETPOST("email_from", "none"), 'chaine', 0, '', $conf->entity); + $result = dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", GETPOST("email_from", "restricthtml"), 'chaine', 0, '', $conf->entity); if ($result < 0) $error++; diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index 85cd9284535..8b0e9516abd 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -40,7 +40,7 @@ $langs->loadLangs(array('admin', 'oauth')); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); /* diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index a78913b7e16..2c8f2070724 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -1,6 +1,7 @@ * Copyright (C) 2014-2018 Frederic France + * Copyright (C) 2020 Nicolas ZABOURI * * 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 @@ $langs->loadLangs(array('admin', 'printing', 'oauth')); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $mode = GETPOST('mode', 'alpha'); $value = GETPOST('value', 'alpha'); $varname = GETPOST('varname', 'alpha'); @@ -57,50 +58,50 @@ if (!$mode) $mode = 'setup'; if ($action == 'setconst' && $user->admin) { - $error = 0; - $db->begin(); + $error = 0; + $db->begin(); - $setupconstarray = GETPOST('setupdriver', 'array'); + $setupconstarray = GETPOST('setupdriver', 'array'); - foreach ($setupconstarray as $setupconst) { - //print '
'.print_r($setupconst, true).'
'; + foreach ($setupconstarray as $setupconst) { + //print '
'.print_r($setupconst, true).'
'; - $constname = dol_escape_htmltag($setupconst['varname']); - $constvalue = dol_escape_htmltag($setupconst['value']); - $consttype = dol_escape_htmltag($setupconst['type']); - $constnote = dol_escape_htmltag($setupconst['note']); + $constname = dol_escape_htmltag($setupconst['varname']); + $constvalue = dol_escape_htmltag($setupconst['value']); + $consttype = dol_escape_htmltag($setupconst['type']); + $constnote = dol_escape_htmltag($setupconst['note']); - $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity); - if (!$result > 0) $error++; - } + $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity); + if (!$result > 0) $error++; + } - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null); - } else { - $db->rollback(); - dol_print_error($db); - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } else { + $db->rollback(); + dol_print_error($db); + } + $action = ''; } if ($action == 'setvalue' && $user->admin) { - $db->begin(); + $db->begin(); - $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null); - } else { - $db->rollback(); - dol_print_error($db); - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } else { + $db->rollback(); + dol_print_error($db); + } + $action = ''; } @@ -130,272 +131,275 @@ if (GETPOST('error')) { if ($mode == 'setup' && $user->admin) { - print ''.$langs->trans("OAuthSetupForLogin")."

\n"; + print ''.$langs->trans("OAuthSetupForLogin")."

\n"; - foreach ($list as $key) - { - $supported = 0; - if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; - if (!$supported) continue; // show only supported + foreach ($list as $key) + { + $supported = 0; + if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; + if (!$supported) continue; // show only supported - $OAUTH_SERVICENAME = 'Unknown'; - if ($key[0] == 'OAUTH_GITHUB_NAME') - { - $OAUTH_SERVICENAME = 'GitHub'; - // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). - // We pass this param list in to 'state' because we need it before and after the redirect. - $shortscope = 'user,public_repo'; - $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms = 'https://github.com/settings/applications/'; - } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') - { - $OAUTH_SERVICENAME = 'Google'; - // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). - // We pass this param list in to 'state' because we need it before and after the redirect. - $shortscope = 'userinfo_email,userinfo_profile,cloud_print'; - //$scope.=',gmail_full'; - $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms = 'https://security.google.com/settings/security/permissions'; - } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') - { - $OAUTH_SERVICENAME = 'StripeTest'; - $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = ''; - $urltocheckperms = ''; - } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME') - { - $OAUTH_SERVICENAME = 'StripeLive'; - $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = ''; - $urltocheckperms = ''; - } else { + $OAUTH_SERVICENAME = 'Unknown'; + if ($key[0] == 'OAUTH_GITHUB_NAME') + { + $OAUTH_SERVICENAME = 'GitHub'; + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'user,public_repo'; + $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://github.com/settings/applications/'; + } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') + { + $OAUTH_SERVICENAME = 'Google'; + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'userinfo_email,userinfo_profile,cloud_print'; + if (!empty($conf->global->OAUTH_GSUITE)){ + $shortscope .= ',admin_directory_user'; + } + //$scope.=',gmail_full'; + $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://security.google.com/settings/security/permissions'; + } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') + { + $OAUTH_SERVICENAME = 'StripeTest'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; + } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME') + { + $OAUTH_SERVICENAME = 'StripeLive'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; + } else { $urltorenew = ''; $urltodelete = ''; $urltocheckperms = ''; } - // Show value of token - $tokenobj = null; - // Token - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - // Dolibarr storage - $storage = new DoliStorage($db, $conf); - try { - $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); - } catch (Exception $e) - { - // Return an error if token not found - } + // Show value of token + $tokenobj = null; + // Token + require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; + // Dolibarr storage + $storage = new DoliStorage($db, $conf); + try { + $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); + } catch (Exception $e) + { + // Return an error if token not found + } - // Set other properties - $refreshtoken = false; - $expiredat = ''; + // Set other properties + $refreshtoken = false; + $expiredat = ''; - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if (is_object($tokenobj)) { - $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30)); - } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if (is_object($tokenobj)) { + $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30)); + } - if ($key[1] != '' && $key[2] != '') { - if (is_object($tokenobj)) { - $refreshtoken = $tokenobj->getRefreshToken(); + if ($key[1] != '' && $key[2] != '') { + if (is_object($tokenobj)) { + $refreshtoken = $tokenobj->getRefreshToken(); - $endoflife = $tokenobj->getEndOfLife(); - if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES) - { - $expiredat = $langs->trans("Never"); - } elseif ($endoflife == $tokenobj::EOL_UNKNOWN) - { - $expiredat = $langs->trans("Unknown"); - } else { - $expiredat = dol_print_date($endoflife, "dayhour"); - } - } - } + $endoflife = $tokenobj->getEndOfLife(); + if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES) + { + $expiredat = $langs->trans("Never"); + } elseif ($endoflife == $tokenobj::EOL_UNKNOWN) + { + $expiredat = $langs->trans("Unknown"); + } else { + $expiredat = dol_print_date($endoflife, "dayhour"); + } + } + } - $submit_enabled = 0; + $submit_enabled = 0; - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - print ''."\n"; + print '
'."\n"; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; - print ''; - print ''; - //var_dump($key); - print $langs->trans("OAuthIDSecret").''; - print ''; - print ''; - print ''."\n"; + print ''; + print ''; + //var_dump($key); + print $langs->trans("OAuthIDSecret").''; + print ''; + print ''; + print ''."\n"; - print ''; - print ''; - //var_dump($key); - print $langs->trans("IsTokenGenerated"); - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + //var_dump($key); + print $langs->trans("IsTokenGenerated"); + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - //var_dump($key); - print $langs->trans("Token").''; - print ''; - print ''."\n"; + } + print ''; + print ''."\n"; - if (is_object($tokenobj)) - { - // Token refresh - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_REFRESH").''; - print ''; - print ''; + if (is_object($tokenobj)) + { + // Token refresh + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_REFRESH").''; + print ''; + print ''; - // Token expired - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_EXPIRED").''; - print ''; - print ''; + // Token expired + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_EXPIRED").''; + print ''; + print ''; - // Token expired at - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_EXPIRE_AT").''; - print ''; - print ''; - } + // Token expired at + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_EXPIRE_AT").''; + print ''; + print ''; + } - print '
'.$langs->trans($key[0]).'
'.$langs->trans($key[0]).'
'; - print $langs->trans("SeePreviousTab"); - print ''; - print '
'; + print $langs->trans("SeePreviousTab"); + print ''; + print '
'; - if (is_object($tokenobj)) print $langs->trans("HasAccessToken"); - else print $langs->trans("NoAccessToken"); - print ''; - // Links to delete/checks token - if (is_object($tokenobj)) - { - //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? - print ''.$langs->trans('DeleteAccess').'
'; - } - // Request remote token - if ($urltorenew) - { - print ''.$langs->trans('RequestAccess').'
'; - } - // Check remote access - if ($urltocheckperms) - { - print '
'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; - } - print '
'; + if (is_object($tokenobj)) print $langs->trans("HasAccessToken"); + else print $langs->trans("NoAccessToken"); + print ''; + // Links to delete/checks token + if (is_object($tokenobj)) + { + //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? + print ''.$langs->trans('DeleteAccess').'
'; + } + // Request remote token + if ($urltorenew) + { + print ''.$langs->trans('RequestAccess').'
'; + } + // Check remote access + if ($urltocheckperms) + { + print '
'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; + } + print '
'; - if (is_object($tokenobj)) - { - //var_dump($tokenobj); - print $tokenobj->getAccessToken().'
'; - //print 'Refresh: '.$tokenobj->getRefreshToken().'
'; - //print 'EndOfLife: '.$tokenobj->getEndOfLife().'
'; - //var_dump($tokenobj->getExtraParams()); - /*print '
Extra:
';*/ - } - print '
'; - print yn($refreshtoken); - print '
'; + print yn($refreshtoken); + print '
'; - print yn($expire); - print '
'; + print yn($expire); + print '
'; - print $expiredat; - print '
'; + print $expiredat; + print '
'; + print ''; - if (!empty($driver)) - { - if ($submit_enabled) { - print '
'; - } - } + if (!empty($driver)) + { + if ($submit_enabled) { + print '
'; + } + } - print '
'; - } + print ''; + } } if ($mode == 'test' && $user->admin) { - print $langs->trans('PrintTestDesc'.$driver)."

\n"; + print $langs->trans('PrintTestDesc'.$driver)."

\n"; - print ''; - if (!empty($driver)) - { - require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; - $classname = 'printing_'.$driver; - $langs->load($driver); - $printer = new $classname($db); - //print '
'.print_r($printer, true).'
'; - if (count($printer->getlistAvailablePrinters())) { - if ($printer->listAvailablePrinters() == 0) { - print $printer->resprint; - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - } else { - print $langs->trans('PleaseConfigureDriverfromList'); - } - } + print '
'; + if (!empty($driver)) + { + require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; + $classname = 'printing_'.$driver; + $langs->load($driver); + $printer = new $classname($db); + //print '
'.print_r($printer, true).'
'; + if (count($printer->getlistAvailablePrinters())) { + if ($printer->listAvailablePrinters() == 0) { + print $printer->resprint; + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + } else { + print $langs->trans('PleaseConfigureDriverfromList'); + } + } - print '
'; + print ''; } if ($mode == 'userconf' && $user->admin) { - print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; + print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; - $resql = $db->query($sql); - while ($row = $db->fetch_array($resql)) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - } - print '
'.$langs->trans("User").''.$langs->trans("PrintModule").''.$langs->trans("PrintDriver").''.$langs->trans("Printer").''.$langs->trans("PrinterLocation").''.$langs->trans("PrinterId").''.$langs->trans("NumberOfCopy").''.$langs->trans("Delete").'
'.$row['login'].''.$row['module'].''.$row['driver'].''.$row['printer_name'].''.$row['printer_location'].''.$row['printer_id'].''.$row['copy'].''.img_picto($langs->trans("Delete"), 'delete').'
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; + $resql = $db->query($sql); + while ($row = $db->fetch_array($resql)) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + print '
'.$langs->trans("User").''.$langs->trans("PrintModule").''.$langs->trans("PrintDriver").''.$langs->trans("Printer").''.$langs->trans("PrinterLocation").''.$langs->trans("PrinterId").''.$langs->trans("NumberOfCopy").''.$langs->trans("Delete").'
'.$row['login'].''.$row['module'].''.$row['driver'].''.$row['printer_name'].''.$row['printer_location'].''.$row['printer_id'].''.$row['copy'].''.img_picto($langs->trans("Delete"), 'delete').'
'; } dol_fiche_end(); diff --git a/htdocs/admin/order_extrafields.php b/htdocs/admin/order_extrafields.php index 2c72c55697f..1b2bb0c0cd0 100644 --- a/htdocs/admin/order_extrafields.php +++ b/htdocs/admin/order_extrafields.php @@ -45,7 +45,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'commande'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/admin/orderdet_extrafields.php b/htdocs/admin/orderdet_extrafields.php index 55732a40a51..1f645241646 100644 --- a/htdocs/admin/orderdet_extrafields.php +++ b/htdocs/admin/orderdet_extrafields.php @@ -46,7 +46,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'commandedet'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/admin/payment.php b/htdocs/admin/payment.php index 85d7e140a6d..92b5c9511d5 100644 --- a/htdocs/admin/payment.php +++ b/htdocs/admin/payment.php @@ -32,7 +32,7 @@ $langs->loadLangs(array("admin", "other", "errors", "bills")); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); @@ -68,7 +68,7 @@ if ($action == 'setmod') if ($action == 'setparams') { - $freetext = GETPOST('FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS', 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS", $freetext, 'chaine', 0, '', $conf->entity); if (!$res > 0) $error++; @@ -182,7 +182,7 @@ foreach ($dirmodels as $reldir) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { - print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; + print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; } print ''; diff --git a/htdocs/admin/paymentbybanktransfer.php b/htdocs/admin/paymentbybanktransfer.php index 3464a0857b7..718e64e6446 100644 --- a/htdocs/admin/paymentbybanktransfer.php +++ b/htdocs/admin/paymentbybanktransfer.php @@ -36,7 +36,7 @@ $langs->loadLangs(array("admin", "withdrawals")); // Security check if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $type = 'paymentorder'; @@ -210,7 +210,7 @@ print load_fiche_titre($langs->trans("OrdersModelModule"),'',''); $def = array(); $sql = "SELECT nom"; $sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; +$sql.= " WHERE type = '".$db->escape($type)."'"; $sql.= " AND entity = ".$conf->entity; $resql=$db->query($sql); if ($resql) @@ -291,7 +291,7 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"),'switch_on'); print ''; print ''; @@ -299,7 +299,7 @@ foreach ($dirmodels as $reldir) else { print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"),'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"),'switch_off').''; print ""; } @@ -311,7 +311,7 @@ foreach ($dirmodels as $reldir) } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; } print ''; @@ -465,7 +465,7 @@ if (! empty($conf->global->MAIN_MODULE_NOTIFICATION)) print ''.dolGetFirstLastname($obj->firstname,$obj->lastname).''; $label=($langs->trans("Notify_".$obj->code)!="Notify_".$obj->code?$langs->trans("Notify_".$obj->code):$obj->label); print ''.$label.''; - print 'rowid.'">'.img_delete().''; + print 'rowid.'">'.img_delete().''; print ''; $i++; } diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index 6fb1cb297dd..363edca6c80 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -37,7 +37,7 @@ $langs->loadLangs(array('admin', 'languages', 'other', 'companies', 'products', if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); @@ -89,18 +89,6 @@ if ($action == 'update') exit; } -if ($action == 'activate_pdfsecurity') -{ - dolibarr_set_const($db, "PDF_SECURITY_ENCRYPTION", "1", 'chaine', 0, '', $conf->entity); - header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); - exit; -} elseif ($action == 'disable_pdfsecurity') -{ - dolibarr_del_const($db, "PDF_SECURITY_ENCRYPTION", $conf->entity); - header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); - exit; -} - /* diff --git a/htdocs/admin/perms.php b/htdocs/admin/perms.php index 0662a571cc9..cd9d290b828 100644 --- a/htdocs/admin/perms.php +++ b/htdocs/admin/perms.php @@ -128,9 +128,10 @@ print ''; print ''; print ''; -print ''; print ''; +print ''; print ''; +if ($user->admin) print ''; print ''."\n"; //print "xx".$conf->global->MAIN_USE_ADVANCED_PERMS; @@ -178,7 +179,6 @@ if ($result) $found = false; foreach ($modules[$obj->module]->rights as $key => $val) { - $rights_class = $objMod->rights_class; if ($val[4] == $obj->perms && (empty($val[5]) || $val[5] == $obj->subperms)) { $found = true; @@ -209,6 +209,8 @@ if ($result) print ''; print ''; print ''; + // Permission id + if ($user->admin) print ''; print ''."\n"; } @@ -223,15 +225,21 @@ if ($result) // Tick if ($obj->bydefault == 1) { - print ''; print ''; } else { - print ''; print ''; + // Permission id + if ($user->admin) print ''; + print ''."\n"; $i++; diff --git a/htdocs/admin/prelevement.php b/htdocs/admin/prelevement.php index 42c7b52cb75..50d01924364 100644 --- a/htdocs/admin/prelevement.php +++ b/htdocs/admin/prelevement.php @@ -36,7 +36,7 @@ $langs->loadLangs(array("admin", "withdrawals")); // Security check if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $type = 'paymentorder'; @@ -217,7 +217,7 @@ print load_fiche_titre($langs->trans("OrdersModelModule"),'',''); $def = array(); $sql = "SELECT nom"; $sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; +$sql.= " WHERE type = '".$db->escape($type)."'"; $sql.= " AND entity = ".$conf->entity; $resql=$db->query($sql); if ($resql) @@ -298,7 +298,7 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''; @@ -306,7 +306,7 @@ foreach ($dirmodels as $reldir) else { print '"; } @@ -318,7 +318,7 @@ foreach ($dirmodels as $reldir) } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; } print ''; @@ -472,7 +472,7 @@ if (! empty($conf->global->MAIN_MODULE_NOTIFICATION)) print ''; $label=($langs->trans("Notify_".$obj->code)!="Notify_".$obj->code?$langs->trans("Notify_".$obj->code):$obj->label); print ''; - print ''; + print ''; print ''; $i++; } diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index 4855a164412..3b574956cd0 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -39,7 +39,7 @@ $langs->loadLangs(array("admin", "other", "errors", "propal")); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); @@ -130,7 +130,7 @@ if ($action == 'updateMask') { setEventMessages($langs->trans("Error"), null, 'errors'); } } elseif ($action == 'set_PROPOSAL_FREE_TEXT') { - $freetext = GETPOST('PROPOSAL_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('PROPOSAL_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "PROPOSAL_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); @@ -266,7 +266,7 @@ foreach ($dirmodels as $reldir) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { - print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } @@ -316,7 +316,7 @@ print load_fiche_titre($langs->trans("ProposalsPDFModules"), '', ''); $def = array(); $sql = "SELECT nom"; $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql .= " WHERE type = '".$type."'"; +$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -395,13 +395,13 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''; } else { print ""; } @@ -411,7 +411,7 @@ foreach ($dirmodels as $reldir) { print img_picto($langs->trans("Default"), 'on'); } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; } print ''; @@ -661,11 +661,11 @@ if ($conf->banque->enabled) { if (empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL)) { - print ''.img_picto($langs->trans("Disabled"),'switch_off').''; + print ''.img_picto($langs->trans("Disabled"),'switch_off').''; } else { - print ''.img_picto($langs->trans("Enabled"),'switch_on').''; + print ''.img_picto($langs->trans("Enabled"),'switch_on').''; } } print ''; diff --git a/htdocs/admin/receiptprinter.php b/htdocs/admin/receiptprinter.php index 4332c4feab0..350d4a3dc15 100644 --- a/htdocs/admin/receiptprinter.php +++ b/htdocs/admin/receiptprinter.php @@ -36,7 +36,7 @@ $langs->loadLangs(array("admin", "receiptprinter")); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $mode = GETPOST('mode', 'alpha'); $printername = GETPOST('printername', 'alpha'); @@ -53,16 +53,16 @@ if (!$mode) $mode = 'config'; // used in library escpos maybe useful if php doesn't support gzdecode if (!function_exists('gzdecode')) { - /** - * Gzdecode - * - * @param string $data data to deflate - * @return string data deflated - */ - function gzdecode($data) - { - return gzinflate(substr($data, 10, -8)); - } + /** + * Gzdecode + * + * @param string $data data to deflate + * @return string data deflated + */ + function gzdecode($data) + { + return gzinflate(substr($data, 10, -8)); + } } @@ -71,167 +71,167 @@ if (!function_exists('gzdecode')) { */ if ($action == 'addprinter' && $user->admin) { - $error = 0; - if (empty($printername)) { - $error++; - setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printername)) { + $error++; + setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors'); + } - if (empty($parameter)) { - setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings'); - } + if (empty($parameter)) { + setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings'); + } - if (!$error) { - $db->begin(); - $result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter); + if ($result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("PrinterAdded", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("PrinterAdded", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'deleteprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->deletePrinter($printerid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->deletePrinter($printerid); + if ($result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("PrinterDeleted", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("PrinterDeleted", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'updateprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("PrinterUpdated", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("PrinterUpdated", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'testprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - // test - $ret = $printer->sendTestToPrinter($printerid); - if ($ret == 0) { - setEventMessages($langs->trans("TestSentToPrinter", $printername), null); - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - } - $action = ''; + if (!$error) { + // test + $ret = $printer->sendTestToPrinter($printerid); + if ($ret == 0) { + setEventMessages($langs->trans("TestSentToPrinter", $printername), null); + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + } + $action = ''; } if ($action == 'testtemplate' && $user->admin) { - $error = 0; - // if (empty($printerid)) { - // $error++; - // setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - // } + $error = 0; + // if (empty($printerid)) { + // $error++; + // setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + // } - // if (! $error) { + // if (! $error) { // test require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($db); //$object->initAsSpecimen(); $object->fetch(18); //var_dump($object->lines); - $ret = $printer->sendToPrinter($object, $templateid, 1); - if ($ret == 0) { - setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null); - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - //} - $action = ''; + $ret = $printer->sendToPrinter($object, $templateid, 1); + if ($ret == 0) { + setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null); + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + //} + $action = ''; } if ($action == 'updatetemplate' && $user->admin) { - $error = 0; - if (empty($templateid)) { - $error++; - setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($templateid)) { + $error++; + setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->updateTemplate($templatename, $template, $templateid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->updateTemplate($templatename, $template, $templateid); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("TemplateUpdated", $templatename), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("TemplateUpdated", $templatename), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'addtemplate' && $user->admin) { - $error = 0; - if (empty($templatename)) { - $error++; - setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors'); - } + $error = 0; + if (empty($templatename)) { + $error++; + setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->addTemplate($templatename, $template); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->addTemplate($templatename, $template); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("TemplateAdded", $templatename), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("TemplateAdded", $templatename), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'deletetemplate' && $user->admin) { @@ -273,116 +273,116 @@ $head = receiptprinteradmin_prepare_head($mode); // mode = config if ($mode == 'config' && $user->admin) { - print ''; - print ''; - if ($action != 'editprinter') { - print ''; - } else { - print ''; - } + print ''; + print ''; + if ($action != 'editprinter') { + print ''; + } else { + print ''; + } - dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); + dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); - print ''.$langs->trans("ReceiptPrinterDesc")."

\n"; + print ''.$langs->trans("ReceiptPrinterDesc")."

\n"; - print '
'.$langs->trans("Module").' '.$langs->trans("Default").' '.$langs->trans("Permissions").''.$langs->trans("ID").'
   
'; - print ''.img_edit_remove().''; + print ''; + print ''; + //print img_edit_remove(); + print img_picto('', 'switch_on'); + print ''; print ''; - print img_picto($langs->trans("Active"), 'tick'); + //print img_picto($langs->trans("Active"), 'tick'); print ''; - print ''.img_edit_add().''; + print ''; + print ''; + //print img_edit_add(); + print img_picto('', 'switch_off'); + print ''; print ''; print ' '; @@ -241,6 +249,9 @@ if ($result) // Permission and tick print ''.$perm_libelle.''.$obj->id.'
'."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"),'switch_on'); print ''; print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"),'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"),'switch_off').''; print "'.dolGetFirstLastname($obj->firstname,$obj->lastname).''.$label.'rowid.'">'.img_delete().'rowid.'">'.img_delete().'
'."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print '\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; print "
'."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $ret = $printer->listprinters(); - $nbofprinters = count($printer->listprinters); + print '
'.$langs->trans("Name").''.$langs->trans("Type").''.$langs->trans("Profile").''.$langs->trans("Parameters").'
'."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $ret = $printer->listprinters(); + $nbofprinters = count($printer->listprinters); - if ($action != 'editprinter') { - print ''; - print ''; - $ret = $printer->selectTypePrinter(); - print ''; - $ret = $printer->selectProfilePrinter(); - print ''; - print ''; - print ''; - print ''; - } + if ($action != 'editprinter') { + print ''; + print ''; + $ret = $printer->selectTypePrinter(); + print ''; + $ret = $printer->selectProfilePrinter(); + print ''; + print ''; + print ''; + print ''; + } - if ($ret > 0) { - setEventMessages($printer->error, $printer->errors, 'errors'); - } else { - for ($line = 0; $line < $nbofprinters; $line++) { - print ''; - if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) { - print ''; - print ''; - $ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']); - print ''; - $ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']); - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - // edit icon - print ''; - print ''; - } - } - } + if ($ret > 0) { + setEventMessages($printer->error, $printer->errors, 'errors'); + } else { + for ($line = 0; $line < $nbofprinters; $line++) { + print ''; + if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) { + print ''; + print ''; + $ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']); + print ''; + $ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']); + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + print ''; + // edit icon + print ''; + print ''; + } + } + } - print '
'.$langs->trans("Name").''.$langs->trans("Type").''.$langs->trans("Profile").''.$langs->trans("Parameters").'
'.$printer->resprint.''.$printer->profileresprint.''; - if ($action != 'editprinter') { - print '
'; - } - print '
'.$printer->resprint.''.$printer->profileresprint.''; + if ($action != 'editprinter') { + print '
'; + } + print '
'.$printer->resprint.''.$printer->profileresprint.''; - print '
'; - print '
'.$printer->listprinters[$line]['name'].''.$langs->trans($printer->listprinters[$line]['fk_type_name']).''.$langs->trans($printer->listprinters[$line]['fk_profile_name']).''.$printer->listprinters[$line]['parameter'].''; - print img_picto($langs->trans("Edit"), 'edit'); - print ''; - // delete icon - print ''; - print img_picto($langs->trans("Delete"), 'delete'); - print ''; - // test icon - print ''; - print img_picto($langs->trans("TestPrinter"), 'printer'); - print '
'.$printer->resprint.''.$printer->profileresprint.''; + print '
'; + print '
'.$printer->listprinters[$line]['name'].''.$langs->trans($printer->listprinters[$line]['fk_type_name']).''.$langs->trans($printer->listprinters[$line]['fk_profile_name']).''.$printer->listprinters[$line]['parameter'].''; + print img_picto($langs->trans("Edit"), 'edit'); + print ''; + // delete icon + print ''; + print img_picto($langs->trans("Delete"), 'delete'); + print ''; + // test icon + print ''; + print img_picto($langs->trans("TestPrinter"), 'printer'); + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print ''; + print ''; - print '
'; + print '
'; - print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n"; + print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n"; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("CONNECTOR_DUMMY").':'.$langs->trans("CONNECTOR_DUMMY_HELP").'
'.$langs->trans("CONNECTOR_NETWORK_PRINT").':'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'
'.$langs->trans("CONNECTOR_FILE_PRINT").':'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'
'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'
'.$langs->trans("CONNECTOR_CUPS_PRINT").':'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'
'; + print ''."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("CONNECTOR_DUMMY").':'.$langs->trans("CONNECTOR_DUMMY_HELP").'
'.$langs->trans("CONNECTOR_NETWORK_PRINT").':'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'
'.$langs->trans("CONNECTOR_FILE_PRINT").':'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'
'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'
'.$langs->trans("CONNECTOR_CUPS_PRINT").':'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'
'; - print '
'; + print '
'; - print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n"; + print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n"; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("PROFILE_DEFAULT").':'.$langs->trans("PROFILE_DEFAULT_HELP").'
'.$langs->trans("PROFILE_SIMPLE").':'.$langs->trans("PROFILE_SIMPLE_HELP").'
'.$langs->trans("PROFILE_EPOSTEP").':'.$langs->trans("PROFILE_EPOSTEP_HELP").'
'.$langs->trans("PROFILE_P822D").':'.$langs->trans("PROFILE_P822D_HELP").'
'.$langs->trans("PROFILE_STAR").':'.$langs->trans("PROFILE_STAR_HELP").'
'; + print ''."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("PROFILE_DEFAULT").':'.$langs->trans("PROFILE_DEFAULT_HELP").'
'.$langs->trans("PROFILE_SIMPLE").':'.$langs->trans("PROFILE_SIMPLE_HELP").'
'.$langs->trans("PROFILE_EPOSTEP").':'.$langs->trans("PROFILE_EPOSTEP_HELP").'
'.$langs->trans("PROFILE_P822D").':'.$langs->trans("PROFILE_P822D_HELP").'
'.$langs->trans("PROFILE_STAR").':'.$langs->trans("PROFILE_STAR_HELP").'
'; } // mode = template @@ -390,56 +390,56 @@ if ($mode == 'template' && $user->admin) { dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print '
'; - print ''; - if ($action != 'edittemplate') { - print ''; - } else { - print ''; - } + print ''; + if ($action != 'edittemplate') { + print ''; + } else { + print ''; + } - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $ret = $printer->listPrintersTemplates(); - //print '
'.print_r($printer->listprinterstemplates, true).'
'; - if ($ret > 0) { - setEventMessages($printer->error, $printer->errors, 'errors'); - } else { - $max = count($printer->listprinterstemplates); - for ($line = 0; $line < $max; $line++) { - print ''; - if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - // edit icon - print ''; - } - print ''; - } - } + print '
'.$langs->trans("Name").''.$langs->trans("Template").'
'; - print ''; - print ''.$printer->listprinterstemplates[$line]['name'].''.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).''; - print img_picto($langs->trans("Edit"), 'edit'); - print ''; - // delete icon - print ''; - print img_picto($langs->trans("Delete"), 'delete'); - print ''; - // test icon - print ''; - print img_picto($langs->trans("TestPrinterTemplate"), 'printer'); - print '
'."\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $ret = $printer->listPrintersTemplates(); + //print '
'.print_r($printer->listprinterstemplates, true).'
'; + if ($ret > 0) { + setEventMessages($printer->error, $printer->errors, 'errors'); + } else { + $max = count($printer->listprinterstemplates); + for ($line = 0; $line < $max; $line++) { + print ''; + if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + // edit icon + print ''; + } + print ''; + } + } - if ($action != 'edittemplate') { - print ''; + if ($action != 'edittemplate') { + print ''; print ''; print '
'.$langs->trans("Name").''.$langs->trans("Template").'
'; + print ''; + print ''.$printer->listprinterstemplates[$line]['name'].''.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).''; + print img_picto($langs->trans("Edit"), 'edit'); + print ''; + // delete icon + print ''; + print img_picto($langs->trans("Delete"), 'delete'); + print ''; + // test icon + print ''; + print img_picto($langs->trans("TestPrinterTemplate"), 'printer'); + print '
'; print '
'."\n"; - print '
'; + print '
'.$langs->trans("RunCommandSummary").':
'."\n"; + print '
'."\n"; + print '
'; - //print $paramclear; + //print $paramclear; - // Now show result - print ''.$langs->trans("BackupResult").': '; + // Now show result + print ''.$langs->trans("BackupResult").': '; print $_SESSION["commandbackupresult"]; $_SESSION["commandbackuplastdone"] = ''; @@ -568,20 +568,20 @@ $filecompression['zip'] = array('function' => 'dol_compress_dir', 'id' => 'radio $i = 0; foreach ($filecompression as $key => $val) { - if (!$val['function'] || function_exists($val['function'])) // Enabled export format - { - $checked = ''; - if ($key == 'gz') $checked = ' checked'; - print ''; - print ' '; - } else // Disabled export format - { - print ''; - print ' '; - print ' ('.$langs->trans("NotAvailable").')'; - } - print '     '; - $i++; + if (!$val['function'] || function_exists($val['function'])) // Enabled export format + { + $checked = ''; + if ($key == 'gz') $checked = ' checked'; + print ''; + print ' '; + } else // Disabled export format + { + print ''; + print ' '; + print ' ('.$langs->trans("NotAvailable").')'; + } + print '     '; + $i++; } print ''; diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index 408d82404dc..cbe25f0ff75 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -30,15 +30,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $langs->load("admin"); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $what = GETPOST('what', 'alpha'); $export_type = GETPOST('export_type', 'alpha'); $file = GETPOST('filename_template', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; diff --git a/htdocs/admin/tools/export_files.php b/htdocs/admin/tools/export_files.php index 85e3b2b2e5c..485df8c318b 100644 --- a/htdocs/admin/tools/export_files.php +++ b/htdocs/admin/tools/export_files.php @@ -30,17 +30,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $langs->load("admin"); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $what = GETPOST('what', 'alpha'); $export_type = GETPOST('export_type', 'alpha'); -$file = trim(GETPOST('zipfilename_template', 'alpha')); +$file = GETPOST('zipfilename_template', 'alpha'); $compression = GETPOST('compression'); $file = dol_sanitizeFileName($file); $file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2)$/i', '', $file); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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"; diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index e9d06885dfd..32567f14074 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -1,8 +1,8 @@ +/* Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Bahfir Abbes - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018 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 @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -46,8 +46,8 @@ $langs->loadLangs(array("companies", "admin", "users", "other")); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -60,8 +60,8 @@ $search_code = GETPOST("search_code", "alpha"); $search_ip = GETPOST("search_ip", "alpha"); $search_user = GETPOST("search_user", "alpha"); $search_desc = GETPOST("search_desc", "alpha"); -$search_ua = GETPOST("search_ua", "none"); -$search_prefix_session = GETPOST("search_prefix_session", "none"); +$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; @@ -226,6 +226,7 @@ if ($result) } print ''; + print ''; print_barre_liste($langs->trans("ListOfSecurityEvents"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $nbtotalofrecords, 'setup', 0, '', '', $limit); @@ -235,6 +236,20 @@ if ($result) print $form->formconfirm($_SERVER["PHP_SELF"].'?noparam=noparam', $langs->trans('PurgeAuditEvents'), $langs->trans('ConfirmPurgeAuditEvents'), 'confirm_purge', $formquestion, 'no', 1); } + // Check some parameters + // TODO Add a tab with this and other information + /* + global $dolibarr_main_prod, $dolibarr_nocsrfcheck; + if (empty($dolibarr_main_prod)) { + print $langs->trans("Warning").' dolibarr_main_prod = '.$dolibarr_main_prod; + print ' '.img_warning($langs->trans('SwitchThisForABetterSecurity', 1)).'
'; + } + if (!empty($dolibarr_nocsrfcheck)) { + print $langs->trans("Warning").' dolibarr_nocsrfcheck = '.$dolibarr_nocsrfcheck; + print ' '.img_warning($langs->trans('SwitchThisForABetterSecurity', 0)).'
'; + } + */ + print '
'; print ''; diff --git a/htdocs/admin/tools/listsessions.php b/htdocs/admin/tools/listsessions.php index 07f9f1ef47c..aedc41e0b23 100644 --- a/htdocs/admin/tools/listsessions.php +++ b/htdocs/admin/tools/listsessions.php @@ -31,7 +31,7 @@ $langs->loadLangs(array("companies", "install", "users", "other")); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check diff --git a/htdocs/admin/tools/purge.php b/htdocs/admin/tools/purge.php index 9898e290ddc..c41b43b3b48 100644 --- a/htdocs/admin/tools/purge.php +++ b/htdocs/admin/tools/purge.php @@ -29,7 +29,7 @@ $langs->load("admin"); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $choice = GETPOST('choice', 'aZ09'); diff --git a/htdocs/admin/tools/update.php b/htdocs/admin/tools/update.php index 67f07a4eb24..27b53e8266e 100644 --- a/htdocs/admin/tools/update.php +++ b/htdocs/admin/tools/update.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if (!$user->admin) accessforbidden(); diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 309d15485eb..c962a9fb776 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -33,11 +33,11 @@ $langs->loadLangs(array("companies", "products", "admin", "sms", "other", "error if (!$user->admin) accessforbidden(); $id = GETPOST('rowid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $langcode = GETPOST('langcode', 'alphanohtml'); $transkey = GETPOST('transkey', 'alphanohtml'); -$transvalue = GETPOST('transvalue', 'none'); +$transvalue = GETPOST('transvalue', 'restricthtml'); $mode = GETPOST('mode', 'aZ09') ?GETPOST('mode', 'aZ09') : 'searchkey'; @@ -73,16 +73,16 @@ 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 { - $transkey = ''; - $transvalue = ''; - $toselect = ''; - $search_array_options = array(); + $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 (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') @@ -139,25 +139,25 @@ if ($action == 'add') } if (!$error) { - $db->begin(); + $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).")"; + $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) { - $db->commit(); - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $db->commit(); + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; $transkey = ""; $transvalue = ""; } else { - $db->rollback(); - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); - } else { - setEventMessages($db->lasterror(), null, 'errors'); - } + $db->rollback(); + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); + } else { + setEventMessages($db->lasterror(), null, 'errors'); + } $action = ''; } } @@ -196,15 +196,15 @@ $enabledisablehtml = ''; $enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { - // Button off, click to enable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml .= ''; + // Button off, click to enable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { - // Button on, click to disable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml .= ''; + // Button on, click to disable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); @@ -247,43 +247,43 @@ if ($mode == 'overwrite') if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled'; print '
'; - print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); - $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; - print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; - print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; - print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; - print '
'; + print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); + $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; + print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; + print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; + print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; + print ''; - print '
'; + print '
'; print ''; - print ''; + print ''; print '
'; - print '
'; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to add new record - print "\n"; + // Line to add new record + print "\n"; - print ''."\n"; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print ''."\n"; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print '\n"; - print ''; + print '\n"; + print ''; - // Show constants - $sql = "SELECT rowid, entity, lang, transkey, transvalue"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE 1 = 1"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - $sql .= $db->order($sortfield, $sortorder); + // Show constants + $sql = "SELECT rowid, entity, lang, transkey, transvalue"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE 1 = 1"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + $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; + 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); + while ($i < $num) + { + $obj = $db->fetch_object($result); - print "\n"; + print "\n"; - print ''; + print ''; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Value - print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + } else { + print dol_escape_htmltag($obj->transvalue); + } + print ''; - print ''; + print ''; + } else { + print ''.img_edit().''; + print '   '; + print ''.img_delete().''; + } + print ''; - print "\n"; - print "\n"; - $i++; - } - } + print "\n"; + print "\n"; + $i++; + } + } - print '
'; - print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - print '
'; + print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + print ''; print ''; @@ -292,118 +292,118 @@ if ($mode == 'overwrite') } else {*/ - print ''; - print ''; - //} - print ''; - print "
'; + print ''; + //} + print ''; + print "
'.$obj->lang.''.$obj->transkey.''.$obj->lang.''.$obj->transkey.''; - /*print ''; + // Value + print ''; + /*print ''; print ''; print ''; print ''; */ - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - } else { - print dol_escape_htmltag($obj->transvalue); - } - print ''; - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - print ''; - print '   '; - print ''; - } else { - print ''.img_edit().''; + print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + print ''; print '   '; - print ''.img_delete().''; - } - print '
'; - print '
'; + print '
'; + print '
'; } if ($mode == 'searchkey') { - $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; + $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; - $newlang = new Translate('', $conf); - $newlang->setDefaultLang($langcode); + $newlang = new Translate('', $conf); + $newlang->setDefaultLang($langcode); - $newlangfileonly = new Translate('', $conf); - $newlangfileonly->setDefaultLang($langcode); + $newlangfileonly = new Translate('', $conf); + $newlangfileonly->setDefaultLang($langcode); - $recordtoshow = array(); + $recordtoshow = array(); - // Search modules dirs - $modulesdir = dolGetModulesDirs(); + // Search modules dirs + $modulesdir = dolGetModulesDirs(); - $nbtotaloffiles = 0; - $nbempty = 0; - /*var_dump($langcode); + $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++; - 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) - { - $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' + 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) + { + $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' - // Directory of translation files - $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels - $dir_lang_osencoded = dol_osencode($dir_lang); + // Directory of translation files + $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels + $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) - { + $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); + foreach ($filearray as $file) + { $tmpfile = preg_replace('/.lang/i', '', basename($file['name'])); $moduledirname = (basename(dirname(dirname($dir_lang)))); @@ -416,135 +416,135 @@ if ($mode == 'searchkey') 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++; - } + } + $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; - $recordtoshow[$key] = $val; - } - } + // 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; + $recordtoshow[$key] = $val; + } + } - //print '
'; - $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); - $nbtotalofrecords = count($recordtoshow); - $num = $limit + 1; - if (($offset + $num) > $nbtotalofrecords) $num = $limit; + //print '
'; + $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); + $nbtotalofrecords = count($recordtoshow); + $num = $limit + 1; + 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").')'; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); + //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").')'; + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); - print ''; - print ''; + print ''; + print ''; print '
'; - print ''; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to search new record - print "\n"; + // Line to search new record + print "\n"; - print ''."\n"; - print ''."\n"; + print ''; - // Action column - print ''; - print ''; + print ''; + //} + print ''; + // Action column + 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) - { - $i++; - if ($i <= $offset) continue; - if ($i > ($offset + $limit)) break; - print ''; }*/ - print ''."\n"; - } + print ''."\n"; + } - print '
'; - //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); - print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '
'; + //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); + print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''; print ''; } else {*/ - print ''; - //} - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); - print $searchpicto; - print '
'; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + print $searchpicto; + print '
'.$langcode.''.$key.''; - print dol_escape_htmltag($val); - print ''; - if (!empty($newlangfileonly->tab_translate[$key])) - { - if ($val != $newlangfileonly->tab_translate[$key]) - { - // retrieve rowid - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE transkey = '".$key."'"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - dol_syslog("translation::select from table", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - } - print ''.img_edit().''; - print ' '; - print ''.img_delete().''; - print '  '; - $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); - print $form->textwithpicto('', $htmltext, 1, 'info'); - } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) - { - //print $key.'-'.$val; - print ''.img_edit_add($langs->trans("Overwrite")).''; - } + // Show result + $i = 0; + foreach ($recordtoshow as $key => $val) + { + $i++; + if ($i <= $offset) continue; + if ($i > ($offset + $limit)) break; + print '
'.$langcode.''.$key.''; + print dol_escape_htmltag($val); + print ''; + if (!empty($newlangfileonly->tab_translate[$key])) + { + if ($val != $newlangfileonly->tab_translate[$key]) + { + // retrieve rowid + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE transkey = '".$key."'"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + } + print ''.img_edit().''; + print ' '; + print ''.img_delete().''; + print '  '; + $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); + print $form->textwithpicto('', $htmltext, 1, 'info'); + } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + { + //print $key.'-'.$val; + print ''.img_edit_add($langs->trans("Overwrite")).''; + } - 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; + 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; - print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; - } - } else { - $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); - print $form->textwithpicto('', $htmltext, 1, 'warning'); - } - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; + } + } else { + $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); + print $form->textwithpicto('', $htmltext, 1, 'warning'); + } + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''.$val.'
'; - print '
'; + print ''; + print '
'; } dol_fiche_end(); diff --git a/htdocs/admin/user.php b/htdocs/admin/user.php index f866b418131..620efb0540e 100644 --- a/htdocs/admin/user.php +++ b/htdocs/admin/user.php @@ -38,7 +38,7 @@ if (!$user->admin) accessforbidden(); $extrafields = new ExtraFields($db); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); $value = GETPOST('value', 'alpha'); @@ -155,9 +155,9 @@ if ($conf->use_javascript_ajax) } else { if (empty($conf->global->USER_MAIL_REQUIRED)) { - print ''.img_picto($langs->trans("Disabled"), 'off').''; + print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { - print ''.img_picto($langs->trans("Enabled"), 'on').''; + print ''.img_picto($langs->trans("Enabled"), 'on').''; } } print ''; @@ -192,7 +192,7 @@ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $def = array(); $sql = "SELECT nom"; $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql .= " WHERE type = '".$type."'"; +$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -269,13 +269,13 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print ''; } else { print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; print ""; } @@ -285,7 +285,7 @@ foreach ($dirmodels as $reldir) { print img_picto($langs->trans("Default"), 'on'); } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; } print ''; diff --git a/htdocs/admin/usergroup.php b/htdocs/admin/usergroup.php index 490c79a3363..9ae01790bb2 100644 --- a/htdocs/admin/usergroup.php +++ b/htdocs/admin/usergroup.php @@ -38,7 +38,7 @@ if (!$user->admin) accessforbidden(); $extrafields = new ExtraFields($db); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $value = GETPOST('value', 'alpha'); $type = 'group'; @@ -124,7 +124,7 @@ $form = new Form($db); $def = array(); $sql = "SELECT nom"; $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql .= " WHERE type = '".$type."'"; +$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " AND entity = ".$conf->entity; $resql = $db->query($sql); if ($resql) @@ -201,13 +201,13 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print ''; } else { print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; print ""; } @@ -217,7 +217,7 @@ foreach ($dirmodels as $reldir) { print img_picto($langs->trans("Default"), 'on'); } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; } print ''; diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index 4254408ed90..19d71ebb1d9 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -51,8 +51,8 @@ $actl[1] = img_picto($langs->trans("Activated"), 'switch_on'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -124,252 +124,252 @@ $sourceList = array(); // Actions add or modify a website if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield = explode(',', $tabfield[$id]); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', $tabfield[$id]); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - 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'); - break; - } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) - { + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) + { $ok = 0; - $fieldnamekey = $listfield[$f]; + $fieldnamekey = $listfield[$f]; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + break; + } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) + { + $ok = 0; + $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors'); break; - } - } + } + } - // Clean parameters - if (!empty($_POST['ref'])) - { - $websitekey = strtolower($_POST['ref']); - } + // Clean parameters + if (!empty($_POST['ref'])) + { + $websitekey = strtolower($_POST['ref']); + } - // Si verif ok et action add, on ajoute la ligne - 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) - { - $obj = $db->fetch_object($result); - $newid = ($obj->newid + 1); - } else { - dol_print_error($db); - } - } + // Si verif ok et action add, on ajoute la ligne + 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) + { + $obj = $db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($db); + } + } - /* $website=new Website($db); + /* $website=new Website($db); $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)) - $sql .= $tabrowid[$id].","; - $sql .= $tabfieldinsert[$id]; - $sql .= ",status)"; - $sql .= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + 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)) - $sql .= $newid.","; - $i = 0; - 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]])."'"; - $i++; - } - $sql .= ",1)"; + // List of values + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; + 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]])."'"; + $i++; + } + $sql .= ",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - unset($_POST); // Clean $_POST array, we keep only - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + unset($_POST); // Clean $_POST array, we keep only + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify', 'alpha')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify', 'alpha')) + { + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $db->begin(); + $db->begin(); - $website = new Website($db); - $rowid = GETPOST('rowid', 'int'); - $website->fetch($rowid); + $website = new Website($db); + $rowid = GETPOST('rowid', 'int'); + $website->fetch($rowid); - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { - $sql .= $tabrowid[$id]."="; - $sql .= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql .= ","; - $sql .= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) + { + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); - if ($newname != $website->ref) - { - $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; - $destfile = DOL_DATA_ROOT.'/website/'.$newname; + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); + if ($newname != $website->ref) + { + $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; + $destfile = DOL_DATA_ROOT.'/website/'.$newname; - if (dol_is_dir($destfile)) - { - $error++; - setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); - } else { - @rename($srcfile, $destfile); + if (dol_is_dir($destfile)) + { + $error++; + setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); + } else { + @rename($srcfile, $destfile); - // 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$'); + // 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) - { - dolReplaceInFile($value['fullname'], $arrayreplacement); - } - } - } - } else { - $error++; - setEventMessages($db->lasterror(), null, 'errors'); - } + { + dolReplaceInFile($value['fullname'], $arrayreplacement); + } + } + } + } else { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel', 'alpha')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_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 ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $website = new Website($db); - $website->fetch($rowid); + $website = new Website($db); + $website->fetch($rowid); - if ($website->id > 0) - { - $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website ='".$rowid."'"; - $result = $db->query($sql); + if ($website->id > 0) + { + $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website ='".$rowid."'"; - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object ='".$rowid."'"; - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid ='".$rowid."'"; - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } + $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } - if ($website->ref) - { - dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); - } - } else { - dol_print_error($db, 'Failed to load website with id '.$rowid); - } + if ($website->ref) + { + dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); + } + } else { + dol_print_error($db, 'Failed to load website with id '.$rowid); + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid ='".$rowid."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid ='".$rowid."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -411,7 +411,7 @@ print "
\n"; // Confirmation de la suppression de la ligne 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); + 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); @@ -420,205 +420,205 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql = $tabsql[$id]; - $sql .= $db->order($sortfield, $sortorder); - $sql .= $db->plimit($limit + 1, $offset); - //print $sql; + // Complete requete recherche valeurs avec critere de tri + $sql = $tabsql[$id]; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit + 1, $offset); + //print $sql; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - print ''; - print ''; - print ''; + print ''; + print ''; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused = 0; - $var = false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused = 0; + $var = false; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // 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 != '') - { - print ''; - } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; - } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // 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 != '') + { + print ''; + } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; + } - print ''; - print ''; + print ''; + print ''; - // Line to enter new values - print ""; + // Line to enter new values + print ""; - $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')) - $obj->$val = GETPOST($val); - } - } + $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')) + $obj->$val = GETPOST($val); + } + } - fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); + fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); - print ''; - print ""; + print ''; + print ""; - $colspan = count($fieldlist) + 2; - } + $colspan = count($fieldlist) + 2; + } - 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; - 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; + print ''; - print '
'; + print '
'; - if ($action != 'edit') - { - print ''; - } - print '
'; + if ($action != 'edit') + { + print ''; + } + print '
'; - print ''; + print ''; + print ''; - // List of websites in database - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - if ($num) - { - print '
'; + // List of websites in database + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print '
'; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield = 1; // Par defaut - $align = "left"; - $sortable = 1; - $valuetoshow = ''; - /* + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield = 1; // Par defaut + $align = "left"; + $sortable = 1; + $valuetoshow = ''; + /* $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"); } + $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"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); - } - } + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page ? 'page='.$page.'&' : ''), "", 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - 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; + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + 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'; - $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + print ''; + } else { + $tmpaction = 'view'; + $parameters = array('var'=>$var, '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; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - $showfield = 1; - $align = "left"; - $fieldname = $fieldlist[$field]; - $valuetoshow = $obj->$fieldname; + 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 ''; - } - } + } + } - // 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. + // 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. - $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) : '').'&'; + $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) : '').'&'; - // Active - print '"; + // Active + print '"; - // Modify link - print ''; + // Modify link + print ''; - // Delete link - if ($iserasable) print ''; - else print ''; + // Delete link + if ($iserasable) print ''; + else print ''; - print "\n"; - } - $i++; - } + print "\n"; + } + $i++; + } - print '
 '; - print '  '; + print ' '.$valuetoshow.''; - print ''.$actl[($obj->status ? 1 : 0)].''; - print "'; + print ''.$actl[($obj->status ? 1 : 0)].''; + print "'.img_edit().''.img_edit().''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'
'; + print ''; - print '
'; - } - } else { - dol_print_error($db); - } + print ''; + } + } else { + dol_print_error($db); + } } dol_fiche_end(); @@ -649,7 +649,7 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') foreach ($fieldlist as $field => $value) { - $fieldname = $fieldlist[$field]; + $fieldname = $fieldlist[$field]; if ($fieldlist[$field] == 'lang') { print ''; diff --git a/htdocs/admin/website_options.php b/htdocs/admin/website_options.php index 6f0cffa41c8..1df7642b646 100644 --- a/htdocs/admin/website_options.php +++ b/htdocs/admin/website_options.php @@ -46,8 +46,8 @@ $status = 1; // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index 7d2bf379282..a8bcbcf8172 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -1,8 +1,8 @@ - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2016 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2005-2016 Laurent Destailleur + * Copyright (C) 2005-2012 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 @@ -19,170 +19,220 @@ */ /** - * \file htdocs/admin/workflow.php - * \ingroup company - * \brief Workflows setup page + * \file htdocs/admin/workflow.php + * \ingroup company + * \brief Workflows setup page */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -// Load translation files required by the page -$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposals", "receptions")); - +// security check if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +// Load translation files required by the page +$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions", "errors")); + +$action = GETPOST('action', 'aZ09'); /* * Actions */ -if (preg_match('/set(.*)/', $action, $reg)) -{ - if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) - { - dol_print_error($db); - } +if (preg_match('/set(.*)/', $action, $reg)) { + if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } } -if (preg_match('/del(.*)/', $action, $reg)) -{ - if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) - { - dol_print_error($db); - } +if (preg_match('/del(.*)/', $action, $reg)) { + if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) { + dol_print_error($db); + } } +// List of workflow we can enable +clearstatcache(); + +$workflowcodes = array( + // Automatic creation + 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array( + 'family'=>'create', + 'position'=>10, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order' + ), + 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array( + 'family'=>'create', + 'position'=>20, + 'enabled'=>(!empty($conf->commande->enabled) && !empty($conf->facture->enabled)), + 'picto'=>'bill' + ), + + 'separator1'=>array('family'=>'separator', 'position'=>25), + + // Automatic classification of proposal + 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array( + 'family'=>'classify_proposal', + 'position'=>30, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'propal', + 'warning'=>'' + ), + 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array( + 'family'=>'classify_proposal', + 'position'=>31, + 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->facture->enabled)), + 'picto'=>'propal', + 'warning'=>'' + ), + + // Automatic classification of order + 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array( + 'family'=>'classify_order', + 'position'=>40, + 'enabled'=>(!empty($conf->expedition->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order' + ), + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array( + 'family'=>'classify_order', + 'position'=>41, + 'enabled'=>(!empty($conf->facture->enabled) && !empty($conf->commande->enabled)), + 'picto'=>'order', + 'warning'=>'' + ), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. + + 'separator2'=>array('family'=>'separator', 'position'=>50), + + // Automatic classification supplier proposal + 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array( + 'family'=>'classify_supplier_proposal', + 'position'=>60, + 'enabled'=>(!empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))), + 'picto'=>'propal', + 'warning'=>'' + ), + + // Automatic classification supplier order + 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array( + 'family'=>'classify_supplier_order', + 'position'=>62, + 'enabled'=>(!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)), + 'picto'=>'order', + 'warning'=>'' + ), + + // Automatic classification reception + 'WORKFLOW_BILL_ON_RECEPTION'=>array( + 'family'=>'classify_reception', + 'position'=>64, + 'enabled'=>(!empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))), + 'picto'=>'bill' + ), +); + +if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) { + foreach ($conf->modules_parts['workflow'] as $workflow) { + $workflowcodes = array_merge($workflowcodes, $workflow); + } +} + +// remove not available workflows (based on activated modules and global defined keys) +$workflowcodes = array_filter($workflowcodes, function ($var) { + return $var['enabled']; }); /* - * View + * View */ -llxHeader('', $langs->trans("WorkflowSetup"), ''); +llxHeader('', $langs->trans("WorkflowSetup"), "EN:Module_Workflow_En|FR:Module_Workflow|ES:Módulo_Workflow"); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("WorkflowSetup"), $linkback, 'title_setup'); -print ''.$langs->trans("WorkflowDesc").'
'; -print "
"; +print ''.$langs->trans("WorkflowDesc").''; +print '
'; +print '
'; -// List of workflow we can enable +// current module setup don't support any automatic workflow of this module +if (count($workflowcodes) < 1) { + print $langs->trans("ThereIsNoWorkflowToModify"); -clearstatcache(); - -$workflowcodes = array( - // Automatic creation - 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), - 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array('family'=>'create', 'position'=>20, 'enabled'=>'! empty($conf->commande->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'bill'), - 'separator1'=>array('family'=>'separator', 'position'=>25), - // Automatic classification of proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'propal', 'warning'=>''), - 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>31, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'propal', 'warning'=>''), - // Automatic classification of order - 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array('family'=>'classify_order', 'position'=>40, 'enabled'=>'! empty($conf->expedition->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify_order', 'position'=>41, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order', 'warning'=>''), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card. - 'separator2'=>array('family'=>'separator', 'position'=>50), - // Automatic classification supplier proposal - 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array('family'=>'classify_supplier_proposal', 'position'=>60, 'enabled'=>'! empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'propal', 'warning'=>''), - // Automatic classification supplier order - 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)', 'picto'=>'order', 'warning'=>''), - //Automatic classification reception - 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>64, 'enabled'=>'! empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'bill'), -); - -if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) -{ - foreach ($conf->modules_parts['workflow'] as $workflow) - { - $workflowcodes = array_merge($workflowcodes, $workflow); - } + llxFooter(); + $db->close(); + return; } // Sort on position $workflowcodes = dol_sort_array($workflowcodes, 'position'); -$nbqualified = 0; +print ''; + $oldfamily = ''; -print '
'."\n"; - -foreach ($workflowcodes as $key => $params) -{ - $picto = $params['picto']; - $enabled = $params['enabled']; - $family = $params['family']; - - if ($family == 'separator') - { - print '

'; - print ''."\n"; +foreach ($workflowcodes as $key => $params) { + if ($params['family'] == 'separator') { + print '
'; + print '
'; + print ''; continue; } - if (!verifCond($enabled)) continue; - - $nbqualified++; - - - if ($oldfamily != $family) - { - print ''."\n"; - print ' '; - print ' '; - print "\n"; - $oldfamily = $family; - } - print "\n"; - print "\n"; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + + $oldfamily = $params['family']; + } + + print ''; + print ''; + + print ''; + print ''; } -if ($nbqualified == 0) -{ - print '
'; - if ($family == 'create') - { - print $langs->trans("AutomaticCreation"); - } elseif (preg_match('/classify_(.*)/', $family, $reg)) - { - print $langs->trans("AutomaticClassification"); - if ($reg[1] == 'proposal') print ' - '.$langs->trans('Proposal'); - if ($reg[1] == 'order') print ' - '.$langs->trans('Order'); - if ($reg[1] == 'supplier_proposal') print ' - '.$langs->trans('SupplierProposal'); - if ($reg[1] == 'supplier_order') print ' - '.$langs->trans('SupplierOrder'); - if ($reg[1] == 'reception') print ' - '.$langs->trans('Reception'); + if ($oldfamily != $params['family']) { + if ($params['family'] == 'create') { + $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'); } else { - print $langs->trans("Description"); + $header = $langs->trans("Description"); } - print ''.$langs->trans("Status").'
".img_object('', $picto).$langs->trans('desc'.$key); - if (!empty($params['warning'])) - { - $langs->load("errors"); - print ' '.img_warning($langs->transnoentitiesnoconv($params['warning'])); - } - print "'; - if (!empty($conf->use_javascript_ajax)) - { - print ajax_constantonoff($key); - } else { - if (!empty($conf->global->$key)) - { - print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - } else { - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; - } - } - print '
'.$header.''.$langs->trans("Status").'
'; + print img_object('', $params['picto']); + print ' '.$langs->trans('desc'.$key); + + if (!empty($params['warning'])) { + print ' '.img_warning($langs->transnoentitiesnoconv($params['warning'])); + } + + print ''; + + if (!empty($conf->use_javascript_ajax)) { + print ajax_constantonoff($key); + } else { + if (!empty($conf->global->$key)) { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + } else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } + } + + print '
'.$langs->trans("ThereIsNoWorkflowToModify"); -} print '
'; // End of page diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 8cc22578f2a..a7eab61211d 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -112,11 +112,11 @@ print ''.$langs->trans("ApiProductionMode").''; $production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true); if ($production_mode) { - print ''; + print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; } else { - print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 83bd00555d6..554edbb892e 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -32,7 +32,7 @@ class DolibarrApi /** * @var DoliDb $db Database object */ - protected static $db; + protected $db; /** * @var Restler $r Restler object diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index a6d0d72b8de..84f7bf303e7 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -59,6 +59,16 @@ class DolibarrApiAccess implements iAuthenticate */ public static $user = ''; + + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName /** * Check access @@ -107,15 +117,15 @@ class DolibarrApiAccess implements iAuthenticate $sql = "SELECT u.login, u.datec, u.api_key, "; $sql .= " u.tms as date_modification, u.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.api_key = '".$db->escape($api_key)."'"; + $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."'"; // TODO Check if 2 users has same API key. - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - if ($db->num_rows($result)) + if ($this->db->num_rows($result)) { - $obj = $db->fetch_object($result); + $obj = $this->db->fetch_object($result); $login = $obj->login; $stored_key = $obj->api_key; $userentity = $obj->entity; @@ -125,11 +135,11 @@ class DolibarrApiAccess implements iAuthenticate $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); - $conf->setValues($db); + $conf->setValues($this->db); } } } else { - throw new RestException(503, 'Error when fetching user api_key :'.$db->error_msg); + throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg); } if ($stored_key != $api_key) { // This should not happen since we did a search on api_key @@ -141,7 +151,7 @@ class DolibarrApiAccess implements iAuthenticate { throw new RestException(503, 'Error when searching login user from api key'); } - $fuser = new User($db); + $fuser = new User($this->db); $result = $fuser->fetch('', $login, '', 0, (empty($userentity) ? -1 : $conf->entity)); // If user is not entity 0, we search in working entity $conf->entity (that may have been forced to a different value than user entity) if ($result <= 0) { throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')'); diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 69fef80fd6b..9605f46f219 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -196,7 +196,7 @@ class Documents extends DolibarrApi throw new RestException(404, 'Invoice not found'); } - $templateused = $doctemplate ? $doctemplate : $this->invoice->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->invoice->model_pdf; $result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); @@ -210,7 +210,7 @@ class Documents extends DolibarrApi if (!$result) { throw new RestException(404, 'Order not found'); } - $templateused = $doctemplate ? $doctemplate : $this->order->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->order->model_pdf; $result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); @@ -224,7 +224,7 @@ class Documents extends DolibarrApi if (!$result) { throw new RestException(404, 'Proposal not found'); } - $templateused = $doctemplate ? $doctemplate : $this->propal->modelpdf; + $templateused = $doctemplate ? $doctemplate : $this->propal->model_pdf; $result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { throw new RestException(500, 'Error generating document'); diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 078d631aa3d..8627808a679 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -40,7 +40,7 @@ class Login * * Request the API token for a couple username / password. * Using method POST is recommanded for security reasons (method GET is often logged by default by web servers with parameters so with login and pass into server log file). - * Both methods are provided for developer conveniance. Best is to not use at all the login API method and enter directly the "DOLAPIKEY" into field at the top right of page. Note: The API key (DOLAPIKEY) can be found/set on the user page. + * Both methods are provided for developer conveniance. Best is to not use at all the login API method and enter directly the "DOLAPIKEY" into field at the top right of page. Note: The API token (DOLAPIKEY) can be found/set on the user page. * * @param string $login User login * @param string $password User password diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 5dade088fd0..8177fbf7e1e 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -4,7 +4,7 @@ * Copyright (C) 2017 Regis Houssin * Copyright (C) 2017 Neil Orley * Copyright (C) 2018 Frédéric France - * Copyright (C) 2018-2019 Thibault FOUCART + * Copyright (C) 2018-2020 Thibault FOUCART * * * This program is free software; you can redistribute it and/or modify @@ -24,6 +24,7 @@ use Luracast\Restler\RestException; require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/cstate.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; /** @@ -34,1721 +35,1865 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; */ class Setup extends DolibarrApi { - private $translations = null; - - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of ordering methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" - * - * @url GET dictionary/ordering_methods - * - * @return array [List of ordering methods] - * - * @throws RestException 400 - */ - public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_types - * - * @return array [List of payment types] - * - * @throws RestException 400 - */ - public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of countries. - * - * The names of the countries will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by country ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $lang Code of the language the label of the countries must be translated to - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of countries - * - * @url GET dictionary/countries - * - * @throws RestException - */ - public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql .= " WHERE 1 = 1"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $country = new Ccountry($this->db); - if ($country->fetch($obj->rowid) > 0) { - // Translate the name of the country if needed - // and then apply the filter if there is one. - $this->translateLabel($country, $lang, 'Country'); - - if (empty($filter) || stripos($country->label, $filter) !== false) { - $list[] = $this->_cleanObjectDatas($country); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of countries'); - } - - return $list; - } - - /** - * Get country by ID. - * - * @param int $id ID of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/{id} - * - * @throws RestException - */ - public function getCountryByID($id, $lang = '') - { - return $this->_fetchCcountry($id, '', '', $lang); - } - - /** - * Get country by Code. - * - * @param string $code Code of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byCode/{code} - * - * @throws RestException - */ - public function getCountryByCode($code, $lang = '') - { - return $this->_fetchCcountry('', $code, '', $lang); - } - - /** - * Get country by Iso. - * - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byISO/{iso} - * - * @throws RestException - */ - public function getCountryByISO($iso, $lang = '') - { - return $this->_fetchCcountry('', '', $iso, $lang); - } - - /** - * Get country. - * - * @param int $id ID of country - * @param string $code Code of country - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @throws RestException - */ - private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') - { - $country = new Ccountry($this->db); - - $result = $country->fetch($id, $code, $iso); - if ($result < 0) { - throw new RestException(503, 'Error when retrieving country : '.$country->error); - } elseif ($result == 0) { - throw new RestException(404, 'country not found'); - } - - $this->translateLabel($country, $lang, 'Country'); - - return $this->_cleanObjectDatas($country); - } - - /** - * Get the list of delivery times. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Delivery times is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. - * - * @url GET dictionary/availability - * - * @return array [List of availability] - * - * @throws RestException 400 - */ - public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); - - unset($object->error); - unset($object->errors); - - return $object; - } - - /** - * Translate the name of the object to the given language. - * - * @param object $object Object with label to translate - * @param string $lang Code of the language the name of the object must be translated to - * @param string $prefix Prefix for translation key - * - * @return void - */ - private function translateLabel($object, $lang, $prefix = 'Country') - { - if (!empty($lang)) { - // Load the translations if this is a new language. - if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { - global $conf; - $this->translations = new Translate('', $conf); - $this->translations->setDefaultLang($lang); - $this->translations->load('dict'); - } - if ($object->code) { - $key = $prefix.$object->code; - - $translation = $this->translations->trans($key); - if ($translation != $key) { - $object->label = html_entity_decode($translation); - } - } - } - } - - /** - * Get the list of shipment methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * - * @return array List of shipment methods - * - * @url GET dictionary/shipment_methods - * - * @throws RestException - */ - public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of events types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of event - * @param string $module To filter on module events - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of events types - * - * @url GET dictionary/event_types - * - * @throws RestException - */ - public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of Expense Report types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of expense report types - * - * @url GET dictionary/expensereport_types - * - * @throws RestException - */ - public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, label, accountancy_code, active, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of contacts types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of contact - * @param string $module To filter on module contacts - * @param int $active Contact's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of Contacts types - * - * @url GET dictionary/contact_types - * - * @throws RestException - */ - public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of civilities. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module events - * @param int $active Civility is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of civility types - * - * @url GET dictionary/civilities - * - * @throws RestException - */ - public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of currencies. - * - * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of currencies - * - * @url GET dictionary/currencies - * - * @throws RestException - */ - public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.code_iso, t.label, t.unicode"; - if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; - $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; - if (!empty($multicurrency)) { - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; - } - $sql .= " WHERE t.active = ".$active; - if (!empty($multicurrency)) { - $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; - if (!empty($multicurrency) && $multicurrency != 2) { - $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; - } - } - - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of extra fields. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" - * @return array List of extra fields - * - * @url GET extrafields - * - * @throws RestException - */ - public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') - { - $list = array(); - - if ($type == 'thirdparty') $type = 'societe'; - if ($type == 'contact') $type = 'socpeople'; - - $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; - $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - while ($tab = $this->db->fetch_object($resql)) - { - // New usage - $list[$tab->elementtype][$tab->name]['type'] = $tab->type; - $list[$tab->elementtype][$tab->name]['label'] = $tab->label; - $list[$tab->elementtype][$tab->name]['size'] = $tab->size; - $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; - $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; - $list[$tab->elementtype][$tab->name]['list'] = $tab->list; - } - } - } else { - throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); - } - - if (!count($list)) - { - throw new RestException(404, 'No extrafield found'); - } - - return $list; - } - - - /** - * Get the list of towns. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $zipcode To filter on zipcode - * @param string $town To filter on city name - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of towns - * - * @url GET dictionary/towns - * - * @throws RestException - */ - public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql .= " AND t.active = ".$active; - if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; - if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments terms. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_terms - * - * @return array List of payment terms - * - * @throws RestException 400 - */ - public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of shipping methods. - * - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/shipping_methods - * - * @return array List of shipping methods - * - * @throws RestException 400 - */ - public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - //$sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of measuring units. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Measuring unit is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of measuring unit - * - * @url GET dictionary/units - * - * @throws RestException - */ - public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of social networks. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Social network is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of social networks - * - * @url GET dictionary/socialnetworks - * - * @throws RestException - */ - public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - global $conf; - - if (empty($conf->socialnetworks->enabled)) { - throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); - } + private $translations = null; + + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ordering methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" + * + * @url GET dictionary/ordering_methods + * + * @return array [List of ordering methods] + * + * @throws RestException 400 + */ + public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_types + * + * @return array [List of payment types] + * + * @throws RestException 400 + */ + public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of states/provinces. + * + * The names of the states will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by state ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/states + * + * @throws RestException + */ + public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t"; + $sql .= " WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $state = new Cstate($this->db); + if ($state->fetch($obj->rowid) > 0) { + if (empty($filter) || stripos($state->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($state); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of states'); + } + + return $list; + } + + /** + * Get state by ID. + * + * @param int $id ID of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/{id} + * + * @throws RestException + */ + public function getStateByID($id) + { + return $this->_fetchCstate($id, ''); + } + + /** + * Get state by Code. + * + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/byCode/{code} + * + * @throws RestException + */ + public function getStateByCode($code) + { + return $this->_fetchCstate('', $code); + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/countries + * + * @throws RestException + */ + public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql .= " WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang, 'Country'); + + if (empty($filter) || stripos($country->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries'); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/{id} + * + * @throws RestException + */ + public function getCountryByID($id, $lang = '') + { + return $this->_fetchCcountry($id, '', '', $lang); + } + + /** + * Get country by Code. + * + * @param string $code Code of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byCode/{code} + * + * @throws RestException + */ + public function getCountryByCode($code, $lang = '') + { + return $this->_fetchCcountry('', $code, '', $lang); + } + + /** + * Get country by Iso. + * + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byISO/{iso} + * + * @throws RestException + */ + public function getCountryByISO($iso, $lang = '') + { + return $this->_fetchCcountry('', '', $iso, $lang); + } + + /** + * Get state. + * + * @param int $id ID of state + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCstate($id, $code = '') + { + $state = new Cstate($this->db); + + $result = $state->fetch($id, $code); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving state : '.$state->error); + } elseif ($result == 0) { + throw new RestException(404, 'State not found'); + } + + return $this->_cleanObjectDatas($state); + } + + /** + * Get country. + * + * @param int $id ID of country + * @param string $code Code of country + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') + { + $country = new Ccountry($this->db); + + $result = $country->fetch($id, $code, $iso); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } elseif ($result == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang, 'Country'); + + return $this->_cleanObjectDatas($country); + } + + /** + * Get the list of delivery times. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Delivery times is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. + * + * @url GET dictionary/availability + * + * @return array [List of availability] + * + * @throws RestException 400 + */ + public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + unset($object->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the object to the given language. + * + * @param object $object Object with label to translate + * @param string $lang Code of the language the name of the object must be translated to + * @param string $prefix Prefix for translation key + * + * @return void + */ + private function translateLabel($object, $lang, $prefix = 'Country') + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($object->code) { + $key = $prefix.$object->code; + + $translation = $this->translations->trans($key); + if ($translation != $key) { + $object->label = html_entity_decode($translation); + } + } + } + } + + /** + * Get the list of shipment methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * + * @return array List of shipment methods + * + * @url GET dictionary/shipment_methods + * + * @throws RestException + */ + public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of events types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of event + * @param string $module To filter on module events + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of events types + * + * @url GET dictionary/event_types + * + * @throws RestException + */ + public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of Expense Report types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of expense report types + * + * @url GET dictionary/expensereport_types + * + * @throws RestException + */ + public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, label, accountancy_code, active, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of contacts types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of contact + * @param string $module To filter on module contacts + * @param int $active Contact's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of Contacts types + * + * @url GET dictionary/contact_types + * + * @throws RestException + */ + public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of civilities. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module events + * @param int $active Civility is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of civility types + * + * @url GET dictionary/civilities + * + * @throws RestException + */ + public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of currencies. + * + * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of currencies + * + * @url GET dictionary/currencies + * + * @throws RestException + */ + public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.code_iso, t.label, t.unicode"; + if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; + $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; + if (!empty($multicurrency)) { + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; + } + $sql .= " WHERE t.active = ".$active; + if (!empty($multicurrency)) { + $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; + if (!empty($multicurrency) && $multicurrency != 2) { + $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; + } + } + + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of extra fields. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" + * @return array List of extra fields + * + * @url GET extrafields + * + * @throws RestException + */ + public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->admin) { + throw new RestException(401, 'Only an admin user can get list of extrafields'); + } + + if ($type == 'thirdparty') $type = 'societe'; + if ($type == 'contact') $type = 'socpeople'; + + $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + while ($tab = $this->db->fetch_object($resql)) + { + // New usage + $list[$tab->elementtype][$tab->name]['type'] = $tab->type; + $list[$tab->elementtype][$tab->name]['label'] = $tab->label; + $list[$tab->elementtype][$tab->name]['size'] = $tab->size; + $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; + $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; + $list[$tab->elementtype][$tab->name]['list'] = $tab->list; + } + } + } else { + throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); + } + + if (!count($list)) + { + throw new RestException(404, 'No extrafield found'); + } + + return $list; + } + + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of towns + * + * @url GET dictionary/towns + * + * @throws RestException + */ + public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql .= " AND t.active = ".$active; + if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; + if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments terms. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_terms + * + * @return array List of payment terms + * + * @throws RestException 400 + */ + public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of shipping methods. + * + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/shipping_methods + * + * @return array List of shipping methods + * + * @throws RestException 400 + */ + public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + //$sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of measuring units. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Measuring unit is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of measuring unit + * + * @url GET dictionary/units + * + * @throws RestException + */ + public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of social networks. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Social network is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of social networks + * + * @url GET dictionary/socialnetworks + * + * @throws RestException + */ + public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + global $conf; + + if (empty($conf->socialnetworks->enabled)) { + throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); + } $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets categories. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket categories - * - * @url GET dictionary/ticket_categories - * - * @throws RestException - */ - public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets severity. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket severities - * - * @url GET dictionary/ticket_severities - * - * @throws RestException - */ - public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, color, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket types - * - * @url GET dictionary/ticket_types - * - * @throws RestException - */ - public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; - $sql .= " WHERE t.active = ".(int) $active; - // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get properties of company - * - * @url GET /company - * - * @return array|mixed Data without useless information - * - */ - public function getCompany() - { - global $mysoc; - - return $this->_cleanObjectDatas($mysoc); - } - - - /** - * Get value of a setup variables - * - * Note that conf variables that stores security key or password hashes can't be loaded with API. - * - * @param string $constantname Name of conf variable to get - * @return array|mixed Data without useless information - * - * @url GET conf/{constantname} - * - * @throws RestException 403 Forbidden - * @throws RestException 500 Error Bad or unknown value for constantname - */ - public function getConf($constantname) - { - global $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGIN_ALLOWED_FOR_ADMIN_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_ADMIN_CHECK)) { - throw new RestException(403, 'Error API open to admin users only or to the login user defined with constant API_LOGIN_ALLOWED_FOR_ADMIN_CHECK'); - } - - if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { - throw new RestException(500, 'Error Bad or unknown value for constantname'); - } - if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $constantname)) { - throw new RestException(403, 'Forbidden'); - } - - return $conf->global->$constantname; - } - - /** - * Do a test of integrity for files and setup. - * - * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. - * @return array Result of file and setup integrity check - * - * @url GET checkintegrity - * - * @throws RestException 404 Signature file not found - * @throws RestException 500 Technical error - * @throws RestException 503 Forbidden - */ - public function getCheckIntegrity($target) - { - global $langs, $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) - { - throw new RestException(503, 'Error API open to admin users only or to the login user defined with constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); - } - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - - $langs->load("admin"); - - $outexpectedchecksum = ''; - $outcurrentchecksum = ''; - - // Modified or missing files - $file_list = array('missing' => array(), 'updated' => array()); - - // Local file to compare to - $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; - $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; - // Remote file to compare to - $xmlremote = ($target == 'default' ? '' : $target); - if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; - $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; - if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; - if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; - - if ($target == 'local') - { - if (dol_is_file($xmlfile)) - { - $xml = simplexml_load_file($xmlfile); - } else { - throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); - } - } else { - $xmlarray = getURLContent($xmlremote); - - // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) - if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') - { - $xmlfile = $xmlarray['content']; - //print "xmlfilestart".$xmlfile."endxmlfile"; - $xml = simplexml_load_string($xmlfile); - } else { - $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; - throw new RestException(500, $errormsg); - } - } - - - - if ($xml) - { - $checksumconcat = array(); - $file_list = array(); - $out = ''; - - // Forced constants - if (is_object($xml->dolibarr_constants[0])) - { - $out .= load_fiche_titre($langs->trans("ForcedConstants")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - - $i = 0; - foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement - { - $constname = $constant['name']; - $constvalue = (string) $constant; - $constvalue = (empty($constvalue) ? '0' : $constvalue); - // Value found - $value = ''; - if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; - $valueforchecksum = (empty($value) ? '0' : $value); - - $checksumconcat[] = $valueforchecksum; - - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - - if ($i == 0) - { - $out .= ''; - } - $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - } - - // Scan htdocs - if (is_object($xml->dolibarr_htdocs_dir[0])) - { - //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; - $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); - - // Defined qualified files (must be same than into generate_filelist_xml.php) - $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|bak|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|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs - $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); - - // Fill file_list with files in signature, new files, modified files - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list - // Complete with list of new files - foreach ($scanfiles as $keyfile => $valfile) - { - $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); - if (!in_array($tmprelativefilename, $file_list['insignature'])) - { - $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file - $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); - } - } - - // Files missings - $out .= load_fiche_titre($langs->trans("FilesMissing")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); - if (is_array($tmpfilelist) && count($tmpfilelist)) - { - $i = 0; - foreach ($tmpfilelist as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files modified - $out .= load_fiche_titre($langs->trans("FilesModified")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); - if (is_array($tmpfilelist2) && count($tmpfilelist2)) - { - $i = 0; - foreach ($tmpfilelist2 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files added - $out .= load_fiche_titre($langs->trans("FilesAdded")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); - if (is_array($tmpfilelist3) && count($tmpfilelist3)) - { - $i = 0; - foreach ($tmpfilelist3 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - - // Show warning - if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) - { - //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); - } else { - //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); - } - } else { - throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); - } - - - // Scan scripts - - - asort($checksumconcat); // Sort list of checksum - //var_dump($checksumconcat); - $checksumget = md5(join(',', $checksumconcat)); - $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); - - $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); - if ($checksumget == $checksumtoget) - { - if (count($file_list['added'])) - { - $resultcode = 'warning'; - $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; - //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; - $outcurrentchecksum = $checksumget; - } else { - $resultcode = 'ok'; - $resultcomment = 'Success'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - $resultcode = 'error'; - $resultcomment = 'Error'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - throw new RestException(404, 'No signature file known'); - } - - return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); - } + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets categories. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket categories + * + * @url GET dictionary/ticket_categories + * + * @throws RestException + */ + public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets severity. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket severities + * + * @url GET dictionary/ticket_severities + * + * @throws RestException + */ + public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, color, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket types + * + * @url GET dictionary/ticket_types + * + * @throws RestException + */ + public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; + $sql .= " WHERE t.active = ".(int) $active; + // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get properties of company + * + * @url GET /company + * + * @return array|mixed Data without useless information + * + */ + public function getCompany() + { + global $mysoc; + + return $this->_cleanObjectDatas($mysoc); + } + + + /** + * Get value of a setup variables + * + * Note that conf variables that stores security key or password hashes can't be loaded with API. + * + * @param string $constantname Name of conf variable to get + * @return array|mixed Data without useless information + * + * @url GET conf/{constantname} + * + * @throws RestException 403 Forbidden + * @throws RestException 404 Error Bad or unknown value for constantname + */ + public function getConf($constantname) + { + global $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) { + throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ'); + } + + if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { + throw new RestException(404, 'Error Bad or unknown value for constantname'); + } + if (isASecretKey($constantname)) { + throw new RestException(403, 'Forbidden. This parameter cant be read with APIs'); + } + + return $conf->global->$constantname; + } + + /** + * Do a test of integrity for files and setup. + * + * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. + * @return array Result of file and setup integrity check + * + * @url GET checkintegrity + * + * @throws RestException 404 Signature file not found + * @throws RestException 500 Technical error + * @throws RestException 503 Forbidden + */ + public function getCheckIntegrity($target) + { + global $langs, $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) + { + throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); + } + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $langs->load("admin"); + + $outexpectedchecksum = ''; + $outcurrentchecksum = ''; + + // Modified or missing files + $file_list = array('missing' => array(), 'updated' => array()); + + // Local file to compare to + $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; + $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; + // Remote file to compare to + $xmlremote = ($target == 'default' ? '' : $target); + if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; + $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; + if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; + if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; + + if ($target == 'local') + { + if (dol_is_file($xmlfile)) + { + $xml = simplexml_load_file($xmlfile); + } else { + throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); + } + } else { + $xmlarray = getURLContent($xmlremote); + + // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + { + $xmlfile = $xmlarray['content']; + //print "xmlfilestart".$xmlfile."endxmlfile"; + $xml = simplexml_load_string($xmlfile); + } else { + $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + throw new RestException(500, $errormsg); + } + } + + + + if ($xml) + { + $checksumconcat = array(); + $file_list = array(); + $out = ''; + + // Forced constants + if (is_object($xml->dolibarr_constants[0])) + { + $out .= load_fiche_titre($langs->trans("ForcedConstants")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + + $i = 0; + foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement + { + $constname = $constant['name']; + $constvalue = (string) $constant; + $constvalue = (empty($constvalue) ? '0' : $constvalue); + // Value found + $value = ''; + if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; + $valueforchecksum = (empty($value) ? '0' : $value); + + $checksumconcat[] = $valueforchecksum; + + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + + if ($i == 0) + { + $out .= ''; + } + $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + } + + // Scan htdocs + if (is_object($xml->dolibarr_htdocs_dir[0])) + { + //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; + $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); + + // Defined qualified files (must be same than into generate_filelist_xml.php) + $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|bak|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|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs + $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); + + // Fill file_list with files in signature, new files, modified files + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list + // Complete with list of new files + foreach ($scanfiles as $keyfile => $valfile) + { + $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); + if (!in_array($tmprelativefilename, $file_list['insignature'])) + { + $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file + $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); + } + } + + // Files missings + $out .= load_fiche_titre($langs->trans("FilesMissing")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); + if (is_array($tmpfilelist) && count($tmpfilelist)) + { + $i = 0; + foreach ($tmpfilelist as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files modified + $out .= load_fiche_titre($langs->trans("FilesModified")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); + if (is_array($tmpfilelist2) && count($tmpfilelist2)) + { + $i = 0; + foreach ($tmpfilelist2 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files added + $out .= load_fiche_titre($langs->trans("FilesAdded")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); + if (is_array($tmpfilelist3) && count($tmpfilelist3)) + { + $i = 0; + foreach ($tmpfilelist3 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + + // Show warning + if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) + { + //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); + } else { + //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); + } + } else { + throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); + } + + + // Scan scripts + + + asort($checksumconcat); // Sort list of checksum + //var_dump($checksumconcat); + $checksumget = md5(join(',', $checksumconcat)); + $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); + + $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); + if ($checksumget == $checksumtoget) + { + if (count($file_list['added'])) + { + $resultcode = 'warning'; + $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; + //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; + $outcurrentchecksum = $checksumget; + } else { + $resultcode = 'ok'; + $resultcomment = 'Success'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + $resultcode = 'error'; + $resultcomment = 'Error'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + throw new RestException(404, 'No signature file known'); + } + + return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); + } } diff --git a/htdocs/asset/admin/assets_extrafields.php b/htdocs/asset/admin/assets_extrafields.php index be36482c295..0bdbff93569 100644 --- a/htdocs/asset/admin/assets_extrafields.php +++ b/htdocs/asset/admin/assets_extrafields.php @@ -37,7 +37,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'don'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/asset/admin/assets_type_extrafields.php b/htdocs/asset/admin/assets_type_extrafields.php index 2f10938d356..ba42a3374dc 100644 --- a/htdocs/asset/admin/assets_type_extrafields.php +++ b/htdocs/asset/admin/assets_type_extrafields.php @@ -36,7 +36,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'adherent_type'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/asset/admin/setup.php b/htdocs/asset/admin/setup.php index c1afe7ba472..64e2bc2b5ad 100644 --- a/htdocs/asset/admin/setup.php +++ b/htdocs/asset/admin/setup.php @@ -35,7 +35,7 @@ $langs->loadLangs(array("admin", "assets")); if (!$user->admin) accessforbidden(); // Parameters -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); $arrayofparameters = array('FIXEDASSETS_MYPARAM1'=>array('css'=>'minwidth200'), 'FIXEDASSETS_MYPARAM2'=>array('css'=>'minwidth500')); diff --git a/htdocs/asset/card.php b/htdocs/asset/card.php index 540de545baf..7ef3d9c011e 100644 --- a/htdocs/asset/card.php +++ b/htdocs/asset/card.php @@ -37,7 +37,7 @@ $ref = GETPOST('ref', '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 +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'assetcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); @@ -53,7 +53,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { @@ -65,6 +65,9 @@ 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; +$result = restrictedArea($user, 'asset', $id); $permissiontoread = $user->rights->asset->read; $permissiontoadd = $user->rights->asset->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php @@ -320,7 +323,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($user->rights->asset->delete) { - print ''.$langs->trans('Delete').''."\n"; + print ''.$langs->trans('Delete').''."\n"; } else { print ''.$langs->trans('Delete').''."\n"; } @@ -346,7 +349,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $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->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); */ // Show links to link elements diff --git a/htdocs/asset/class/asset.class.php b/htdocs/asset/class/asset.class.php index 3c29fe6e7ce..2cc48489f7f 100644 --- a/htdocs/asset/class/asset.class.php +++ b/htdocs/asset/class/asset.class.php @@ -55,6 +55,10 @@ class Asset extends CommonObject public $picto = 'asset'; + const STATUS_DRAFT = 0; + const STATUS_VALIDATED = 1; + + /** * 'type' if the field format. * 'label' the translation key. @@ -331,7 +335,7 @@ class Asset extends CommonObject $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; - $url = dol_buildpath('/assets/card.php', 1).'?id='.$this->id; + $url = dol_buildpath('/asset/card.php', 1).'?id='.$this->id; if ($option != 'nolink') { @@ -390,31 +394,16 @@ class Asset extends CommonObject // phpcs:enable global $langs; - if ($mode == 0 || $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'); - } + $langs->load("contracts"); + $labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); + $labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + $labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Disabled'); + $labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + + $statusType = 'status0'; + if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + + return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode); } /** diff --git a/htdocs/asset/document.php b/htdocs/asset/document.php index d2890ea5b19..b43ec8d40cf 100644 --- a/htdocs/asset/document.php +++ b/htdocs/asset/document.php @@ -68,6 +68,10 @@ $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); diff --git a/htdocs/asset/info.php b/htdocs/asset/info.php index 900bbc61bf2..801a7c85b36 100644 --- a/htdocs/asset/info.php +++ b/htdocs/asset/info.php @@ -31,19 +31,21 @@ $langs->loadLangs(array("asset")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'asset', $id, ''); +$result = restrictedArea($user, 'asset', $id); $object = new Asset($db); $object->fetch($id); + /* * Actions */ +// None /* diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index 0f6624f1254..d9bfea71510 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -39,7 +39,7 @@ $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk $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') : 'assetslist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'assetlist'; // 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') @@ -47,8 +47,8 @@ $id = GETPOST('id', 'int'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -73,15 +73,18 @@ if (!$sortorder) $sortorder = "ASC"; // Security check $socid = 0; +if ($user->socid) $socid = $user->socid; if ($user->socid > 0) // Protection if external user { //$socid = $user->socid; accessforbidden(); } -//$result = restrictedArea($user, 'asset', $id,''); +// Security check +$result = restrictedArea($user, 'asset', $id); + // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { @@ -271,7 +274,7 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $ { $obj = $db->fetch_object($resql); $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/assets/card.php?id='.$id); + header("Location: ".DOL_URL_ROOT.'/asset/card.php?id='.$id); exit; } diff --git a/htdocs/asset/note.php b/htdocs/asset/note.php index 7b92e1dab92..f19249ce1d2 100644 --- a/htdocs/asset/note.php +++ b/htdocs/asset/note.php @@ -32,7 +32,7 @@ $langs->loadLangs(array("asset", "companies")); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -54,6 +54,10 @@ $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->asset->multidir_output[$object->entity]."/".$object->id; +// Security check +if (!empty($user->socid)) $socid = $user->socid; +$result = restrictedArea($user, 'asset', $id); + $permissionnote = 1; //$permissionnote=$user->rights->asset->creer; // Used by the include of actions_setnotes.inc.php diff --git a/htdocs/asset/type.php b/htdocs/asset/type.php index a2c6bab3f90..1045e9135ee 100644 --- a/htdocs/asset/type.php +++ b/htdocs/asset/type.php @@ -34,7 +34,7 @@ if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/account $langs->load("assets"); $rowid = GETPOST('rowid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -77,6 +77,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter_x' // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('assettypecard', 'globalcard')); +$permissiontoadd = $user->rights->asset->setup_advance; /* * Actions @@ -211,14 +212,6 @@ if (!$rowid && $action != 'create' && $action != 'edit') $param = ''; - $newcardbutton = ''; - if ($user->rights->asset->configurer) - { - $newcardbutton = ''.$langs->trans('NewAssetType').''; - $newcardbutton .= ''; - $newcardbutton .= ''; - } - print '
'; if ($optioncss != '') print ''; print ''; @@ -228,6 +221,8 @@ if (!$rowid && $action != 'create' && $action != 'edit') print ''; print ''; + $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); $moreforfilter = ''; @@ -238,9 +233,9 @@ if (!$rowid && $action != 'create' && $action != 'edit') print ''; print ''.$langs->trans("Ref").''; print ''.$langs->trans("Label").''; - print ''.$langs->trans("AccountancyCodeAsset").''; - print ''.$langs->trans("AccountancyCodeDepreciationAsset").''; - print ''.$langs->trans("AccountancyCodeDepreciationExpense").''; + print ''.$langs->trans("AccountancyCodeAsset").''; + print ''.$langs->trans("AccountancyCodeDepreciationAsset").''; + print ''.$langs->trans("AccountancyCodeDepreciationExpense").''; print ' '; print "\n"; @@ -267,7 +262,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $objp->accountancy_code_asset, 1); - print $accountingaccount->getNomUrl(0, 0, 0, '', 0); + print $accountingaccount->getNomUrl(0, 1, 1, '', 0); } else { print $objp->accountancy_code_asset; } @@ -279,7 +274,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $accountingaccount2 = new AccountingAccount($db); $accountingaccount2->fetch('', $objp->accountancy_code_depreciation_asset, 1); - print $accountingaccount2->getNomUrl(0, 0, 0, '', 0); + print $accountingaccount2->getNomUrl(0, 1, 1, '', 0); } else { print $objp->accountancy_code_depreciation_asset; } @@ -291,7 +286,7 @@ if (!$rowid && $action != 'create' && $action != 'edit') $accountingaccount3 = new AccountingAccount($db); $accountingaccount3->fetch('', $objp->accountancy_code_depreciation_expense, 1); - print $accountingaccount3->getNomUrl(0, 0, 0, '', 0); + print $accountingaccount3->getNomUrl(0, 1, 1, '', 0); } else { print $objp->accountancy_code_depreciation_expense; } @@ -512,7 +507,7 @@ if ($rowid > 0) // Delete if ($user->rights->asset->write) { - print ''; + print ''; } print ""; diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php index 1ac908f361a..dabd05bf745 100644 --- a/htdocs/barcode/printsheet.php +++ b/htdocs/barcode/printsheet.php @@ -36,10 +36,10 @@ $now = dol_now(); $year = dol_print_date($now, '%Y'); $month = dol_print_date($now, '%m'); $day = dol_print_date($now, '%d'); -$forbarcode = GETPOST('forbarcode'); -$fk_barcode_type = GETPOST('fk_barcode_type'); -$mode = GETPOST('mode'); -$modellabel = GETPOST("modellabel"); // Doc template to use +$forbarcode = GETPOST('forbarcode', 'alphanohtml'); +$fk_barcode_type = GETPOST('fk_barcode_type', 'int'); +$mode = GETPOST('mode', 'aZ09'); +$modellabel = GETPOST("modellabel", 'aZ09'); // Doc template to use $numberofsticker = GETPOST('numberofsticker', 'int'); $mesg = ''; @@ -57,8 +57,8 @@ $thirdpartytmp = new Societe($db); if (GETPOST('submitproduct') && GETPOST('submitproduct')) { $action = ''; // We reset because we don't want to build doc - if (GETPOST('productid') > 0) { - $result = $producttmp->fetch(GETPOST('productid')); + if (GETPOST('productid', 'int') > 0) { + $result = $producttmp->fetch(GETPOST('productid', 'int')); if ($result < 0) { setEventMessage($producttmp->error, 'errors'); } @@ -76,9 +76,9 @@ if (GETPOST('submitproduct') && GETPOST('submitproduct')) if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty')) { $action = ''; // We reset because we don't want to build doc - if (GETPOST('socid') > 0) + if (GETPOST('socid', 'int') > 0) { - $thirdpartytmp->fetch(GETPOST('socid')); + $thirdpartytmp->fetch(GETPOST('socid', 'int')); $forbarcode = $thirdpartytmp->barcode; $fk_barcode_type = $thirdpartytmp->barcode_type_code; @@ -381,7 +381,7 @@ if (!empty($user->rights->produit->lire) || !empty($user->rights->service->lire) print ' '.$langs->trans("FillBarCodeTypeAndValueFromProduct").'   '; print '
'; print '
'; - $form->select_produits(GETPOST('productid'), 'productid', '', '', 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth400imp', 1); + $form->select_produits(GETPOST('productid', 'int'), 'productid', '', '', 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth400imp', 1); print '   '; print '
'; } @@ -391,7 +391,7 @@ if (!empty($user->rights->societe->lire)) print ' '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").'   '; print '
'; print '
'; - print $form->select_company(GETPOST('socid'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); + print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300'); print '   '; print '
'; } diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index 1b6ff1fa021..051f8bb049a 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -32,7 +32,7 @@ $langs->loadLangs(array("admin", "other", "blockedlog")); if (!$user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index ab36caedba4..d0bee7c613c 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -35,7 +35,7 @@ $langs->loadLangs(array("admin", "other", "blockedlog", "bills")); if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'blockedloglist'; // 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') @@ -56,8 +56,8 @@ if (($search_start == -1 || empty($search_start)) && !GETPOSTISSET('search_start // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -311,6 +311,7 @@ if (GETPOST('withtab', 'alpha')) $param .= '&withtab='.urlencode(GETPOST('withta //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; print ''; +print ''; print '
'; print $langs->trans("RestrictYearToExport").': '; diff --git a/htdocs/blockedlog/ajax/block-add.php b/htdocs/blockedlog/ajax/block-add.php index 5aa344c0237..1102438f5b5 100644 --- a/htdocs/blockedlog/ajax/block-add.php +++ b/htdocs/blockedlog/ajax/block-add.php @@ -34,7 +34,7 @@ $res = require '../../main.inc.php'; $id = GETPOST('id', 'int'); $element = GETPOST('element', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if ($element === 'facture') { require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 44311f1a580..b8d0304c5eb 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -185,6 +185,13 @@ class BlockedLog // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all POS modules $moduleposenabled = ($conf->cashdesk->enabled || $conf->takepos->enabled || !empty($conf->global->BANK_ENABLE_POS_CASHCONTROL)); if ($moduleposenabled) $this->trackedevents['CASHCONTROL_VALIDATE'] = 'logCASHCONTROL_VALIDATE'; + + if (!empty($conf->global->BLOCKEDLOG_ADD_ACTIONS_SUPPORTED)) { + $tmparrayofmoresupportedevents = explode(',', $conf->global->BLOCKEDLOG_ADD_ACTIONS_SUPPORTED); + foreach ($tmparrayofmoresupportedevents as $val) { + $this->trackedevents[$val] = 'log'.$val; + } + } } /** @@ -368,7 +375,7 @@ class BlockedLog $this->object_data = new stdClass(); // Add fields to exclude $arrayoffieldstoexclude = array( - 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id', + 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'model_pdf', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id', 'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged', 'linkedObjectsIds', 'linkedObjects', @@ -476,7 +483,7 @@ class BlockedLog $this->object_data->ref = $object->ref; $this->object_data->date = $datepayment; $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code'); - $this->object_data->payment_num = ($object->num_paiement ? $object->num_paiement : $object->num_payment); + $this->object_data->payment_num = $object->num_payment; //$this->object_data->fk_account = $object->fk_account; $this->object_data->note = $object->note; //var_dump($this->object_data);exit; diff --git a/htdocs/bom/bom_agenda.php b/htdocs/bom/bom_agenda.php index 43f1604e08c..d8361d30258 100644 --- a/htdocs/bom/bom_agenda.php +++ b/htdocs/bom/bom_agenda.php @@ -37,7 +37,7 @@ $langs->loadLangs(array("mrp", "other")); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 6826204804f..7daf29416c2 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2017-2020 Laurent Destailleur * Copyright (C) 2019 Frédéric France * * This program is free software; you can redistribute it and/or modify @@ -57,11 +57,11 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$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'; @@ -92,18 +92,18 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - $error = 0; + $error = 0; - $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php'; + $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($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__'); + } + } - $triggermodname = 'BOM_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'BOM_MODIFY'; // Name of trigger action code to execute when we modify record // Actions cancel, add, update, delete or clone include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; @@ -149,39 +149,41 @@ if (empty($reshook)) } if ($object->fk_product == $idprod) { - setEventMessages($langs->trans('TheProductXIsAlreadyTheProductToProduce'), null, 'errors'); - $error++; + setEventMessages($langs->trans('TheProductXIsAlreadyTheProductToProduce'), null, 'errors'); + $error++; } if (!$error) { $lastposition = 0; - $bomline = new BOMLine($db); - $bomline->fk_bom = $id; - $bomline->fk_product = $idprod; - $bomline->qty = $qty; - $bomline->qty_frozen = (int) $qty_frozen; - $bomline->disable_stock_change = (int) $disable_stock_change; - $bomline->efficiency = $efficiency; + $bomline = new BOMLine($db); + $bomline->fk_bom = $id; + $bomline->fk_product = $idprod; + $bomline->qty = $qty; + $bomline->qty_frozen = (int) $qty_frozen; + $bomline->disable_stock_change = (int) $disable_stock_change; + $bomline->efficiency = $efficiency; - // Rang to use + // Rang to use $rangmax = $object->line_max(0); $ranktouse = $rangmax + 1; $bomline->position = ($ranktouse + 1); - $result = $bomline->create($user); - if ($result <= 0) - { - setEventMessages($bomline->error, $bomline->errors, 'errors'); - $action = ''; - } else { - unset($_POST['idprod']); - unset($_POST['qty']); - unset($_POST['qty_frozen']); - unset($_POST['disable_stock_change']); - } + $result = $bomline->create($user); + if ($result <= 0) + { + setEventMessages($bomline->error, $bomline->errors, 'errors'); + $action = ''; + } else { + unset($_POST['idprod']); + unset($_POST['qty']); + unset($_POST['qty_frozen']); + unset($_POST['disable_stock_change']); + + $object->fetchLines(); + } } } @@ -218,9 +220,9 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['qty']); unset($_POST['qty_frozen']); - unset($_POST['disable_stock_change']); + unset($_POST['disable_stock_change']); - $object->fetchLines(); + $object->fetchLines(); } } } @@ -290,7 +292,7 @@ if (($id || $ref) && $action == 'edit') print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes'); print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -321,7 +323,7 @@ if (($id || $ref) && $action == 'edit') // Part to show record if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - $res = $object->fetch_optionals(); + $res = $object->fetch_optionals(); $head = bomPrepareHead($object); dol_fiche_head($head, 'card', $langs->trans("BillOfMaterials"), -1, 'bom'); @@ -331,7 +333,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); + $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') @@ -451,7 +453,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $text = $langs->trans('ConfirmSetToDraft', $object->ref); $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetToDraft'), $text, 'confirm_setdraft', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetToDraft'), $text, 'confirm_setdraft', $formquestion, 0, 1, 220); } // Call Hook formConfirm @@ -543,129 +545,129 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (!empty($object->table_element_line)) { - print ' + print ' '; - if (!empty($conf->use_javascript_ajax) && $object->status == 0) { - include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; - } + 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 ''; - } + 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, '/bom/tpl'); - } + 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') - { - // Add products/services form - $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); + // Form to add new line + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') + { + if ($action != 'editline') + { + // Add products/services form + $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); - $parameters = array(); - $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - } - } + $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 '
'; + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) + { + print ''; + } + print '
'; - print "
\n"; + 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'); + 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 '' . $langs->trans('SendMail') . ''."\n"; - //} + if (empty($reshook)) + { + // Send + //if (empty($user->socid)) { + // print '' . $langs->trans('SendMail') . ''."\n"; + //} - // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - print ''.$langs->trans("SetToDraft").''; - } - } + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) + { + if ($permissiontoadd) + { + print ''.$langs->trans("SetToDraft").''; + } + } - // Modify - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - print ''.$langs->trans("Modify").''."\n"; - } else { - print ''.$langs->trans('Modify').''."\n"; - } - } + // Modify + if ($object->status == $object::STATUS_DRAFT) + { + if ($permissiontoadd) + { + print ''.$langs->trans("Modify").''."\n"; + } else { + print ''.$langs->trans('Modify').''."\n"; + } + } - // Validate - 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"); - print ''.$langs->trans("Validate").''; - } - } - } + // Validate + 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"); + print ''.$langs->trans("Validate").''; + } + } + } - // Close / Cancel - if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) - { - print ''.$langs->trans("Disable").''; - } + // Close / Cancel + if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) + { + print ''.$langs->trans("Disable").''; + } - // Re-open - if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) - { - print ''.$langs->trans("ReOpen").''; - } + // Re-open + 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)) - { - print ''.$langs->trans("CreateMO").''; - } - } + // Create MO + if ($conf->mrp->enabled) + { + if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) + { + print ''.$langs->trans("CreateMO").''; + } + } - // Clone - if ($permissiontoadd) - { - print ''.$langs->trans("ToClone").''; - } + // Clone + if ($permissiontoadd) + { + print ''.$langs->trans("ToClone").''; + } - /* + /* if ($user->rights->bom->write) { if ($object->status == 1) @@ -679,14 +681,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } */ - if ($permissiontodelete) - { - print ''.$langs->trans('Delete').''."\n"; - } else { - print ''.$langs->trans('Delete').''."\n"; - } - } - print '
'."\n"; + if ($permissiontodelete) + { + print ''.$langs->trans('Delete').''."\n"; + } else { + print ''.$langs->trans('Delete').''."\n"; + } + } + print '
'."\n"; } @@ -697,41 +699,41 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'presend') { - print '
'; - print ''; // ancre + print '
'; + print ''; // ancre - // Documents - $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref.'/'.$objref.'.pdf'; - $filedir = $conf->bom->dir_output.'/'.$objref; - $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); + // Documents + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->bom->dir_output.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('bom', $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('bom')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('bom')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; - $MAXEVENT = 10; + $MAXEVENT = 10; - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; + $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, 'bom', $socid, 1, '', $MAXEVENT, '', $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, 'bom', $socid, 1, '', $MAXEVENT, '', $morehtmlright); - print '
'; + print '
'; } //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_list.php b/htdocs/bom/bom_list.php index 3ff2b2138b4..121517b2544 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -45,8 +45,8 @@ $id = GETPOST('id', 'int'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -81,7 +81,7 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'bom', $id, ''); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { diff --git a/htdocs/bom/bom_note.php b/htdocs/bom/bom_note.php index dce9bc82b06..df1693e84b0 100644 --- a/htdocs/bom/bom_note.php +++ b/htdocs/bom/bom_note.php @@ -33,7 +33,7 @@ $langs->loadLangs(array("mrp", "companies")); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); diff --git a/htdocs/bom/class/api_boms.class.php b/htdocs/bom/class/api_boms.class.php index a6295d12589..b9123b8c226 100644 --- a/htdocs/bom/class/api_boms.class.php +++ b/htdocs/bom/class/api_boms.class.php @@ -99,7 +99,7 @@ class Boms extends DolibarrApi global $db, $conf; $obj_ret = array(); - $tmpobject = new BOM($db); + $tmpobject = new BOM($this->db); $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; @@ -139,7 +139,7 @@ class Boms extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -147,18 +147,18 @@ class Boms extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $i = 0; while ($i < $num) { - $obj = $db->fetch_object($result); - $bom_static = new BOM($db); + $obj = $this->db->fetch_object($result); + $bom_static = new BOM($this->db); if ($bom_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($bom_static); } diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index d180c00426f..bd67f311d19 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -745,7 +745,7 @@ class BOM extends CommonObject $result = ''; - $label = ''.$langs->trans("BillOfMaterials").''; + $label = img_picto('', $this->picto).' '.$langs->trans("BillOfMaterials").''; $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; if (isset($this->status)) { @@ -934,8 +934,8 @@ class BOM extends CommonObject if (!dol_strlen($modele)) { $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; + if ($this->model_pdf) { + $modele = $this->model_pdf; } elseif (!empty($conf->global->BOM_ADDON_PDF)) { $modele = $conf->global->BOM_ADDON_PDF; } diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 74eb88393df..2a675cc60e1 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -31,8 +31,8 @@ // Protection to avoid direct call of template if (empty($object) || !is_object($object)) { - print "Error: this template page cannot be called directly as an URL"; - exit; + print "Error: this template page cannot be called directly as an URL"; + exit; } @@ -52,34 +52,34 @@ print "\n"; $nolinesbefore = (count($this->lines) == 0 || $forcetoshowtitlelines); if ($nolinesbefore) { - print ''; - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { - print ''; - } - print ''; + print ''; + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; + } + print ''; print '
'.$langs->trans('AddNewLine').''; print ''; print ''.$langs->trans('Qty').''; if ($conf->global->PRODUCT_USE_UNITS) { - print ''; - print ''; - print $langs->trans('Unit'); - print ''; + print ''; + print ''; + print $langs->trans('Unit'); + print ''; } print ''.$form->textwithpicto($langs->trans('QtyFrozen'), $langs->trans("QuantityConsumedInvariable")).''; print ''.$form->textwithpicto($langs->trans('DisableStockChange'), $langs->trans('DisableStockChangeHelp')).''; print ''.$form->textwithpicto($langs->trans('ManufacturingEfficiency'), $langs->trans('ValueOfMeansLoss')).''; print ' '; - print ''; + print ''; } print ''; $coldisplay = 0; // Adds a line numbering column if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { - $coldisplay++; - echo ''; + $coldisplay++; + echo ''; } $coldisplay++; @@ -111,7 +111,7 @@ print ''; if ($conf->global->PRODUCT_USE_UNITS) { - $coldisplay++; + $coldisplay++; print ''; print $form->selectUnits(empty($line->fk_unit) ? $conf->global->PRODUCT_USE_UNITS : $line->fk_unit, "units"); print ''; diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index e1e94dc2076..05682dc3da6 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -111,21 +111,21 @@ print ''; if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { print ''; $coldisplay++; - if (($line->info_bits & 2) == 2 || !empty($disableedit)) { - } else { - print 'id.'">'.img_edit().''; - } - print ''; + if (($line->info_bits & 2) == 2 || !empty($disableedit)) { + } else { + print 'id.'">'.img_edit().''; + } + print ''; - print ''; - $coldisplay++; - if (($line->fk_prev_id == null) && empty($disableremove)) { - //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation - print 'id.'">'; - print img_delete(); - print ''; - } - print ''; + print ''; + $coldisplay++; + if (($line->fk_prev_id == null) && empty($disableremove)) { + //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation + print 'id.'">'; + print img_delete(); + print ''; + } + print ''; if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) { print ''; @@ -146,14 +146,14 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { $coldisplay++; } } else { - print ''; - $coldisplay = $coldisplay + 3; + print ''; + $coldisplay = $coldisplay + 3; } if ($action == 'selectlines') { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print ''; diff --git a/htdocs/bookmarks/admin/bookmark.php b/htdocs/bookmarks/admin/bookmark.php index 2d8501130dc..9aa1989fa2e 100644 --- a/htdocs/bookmarks/admin/bookmark.php +++ b/htdocs/bookmarks/admin/bookmark.php @@ -31,7 +31,7 @@ $langs->load("admin"); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if ($action == 'setvalue') { diff --git a/htdocs/bookmarks/card.php b/htdocs/bookmarks/card.php index bd6d1fc2cf3..93926e4ba92 100644 --- a/htdocs/bookmarks/card.php +++ b/htdocs/bookmarks/card.php @@ -251,7 +251,7 @@ if ($id > 0 && !preg_match('/^add/i', $action)) print ''; } print ''; - if ($action == 'edit') print 'url).'">'; + if ($action == 'edit') print 'url).'">'; else print 'target ? ' target="_blank"' : '').'>'.$object->url.''; print ''; @@ -311,13 +311,13 @@ if ($id > 0 && !preg_match('/^add/i', $action)) // Edit if ($user->rights->bookmark->creer && $action != 'edit') { - print " id."&action=edit\">".$langs->trans("Edit")."\n"; + print ''.$langs->trans("Edit").''."\n"; } // Remove if ($user->rights->bookmark->supprimer && $action != 'edit') { - print " id."&action=delete\">".$langs->trans("Delete")."\n"; + print ''.$langs->trans("Delete").''."\n"; } print ''; diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index a4f0939c054..7f70d74f5d9 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -27,12 +27,12 @@ require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; // Load translation files required by the page $langs->loadLangs(array('bookmarks', 'admin')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bookmarklist'; // To manage different context of search // Security check if (!$user->rights->bookmark->lire) { @@ -42,8 +42,8 @@ $optioncss = GETPOST('optioncss', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -241,11 +241,11 @@ while ($i < min($num, $limit)) print ''; if ($user->rights->bookmark->creer) { - print 'rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"]).'">'.img_edit().""; + print 'rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"]).'">'.img_edit().""; } if ($user->rights->bookmark->supprimer) { - print 'rowid.'">'.img_delete().''; + print 'rowid.'">'.img_delete().''; } else { print " "; } diff --git a/htdocs/cashdesk/facturation.php b/htdocs/cashdesk/facturation.php index e1a42aed012..85347e4c7ff 100644 --- a/htdocs/cashdesk/facturation.php +++ b/htdocs/cashdesk/facturation.php @@ -42,7 +42,7 @@ if (GETPOST('filtre', 'alpha')) { $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx, p.fk_product_type"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; - if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$conf_fkentrepot."'"; + if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; $sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " AND p.tosell = 1"; if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; @@ -92,7 +92,7 @@ if (GETPOST('filtre', 'alpha')) { $sql = "SELECT p.rowid, ref, label, tva_tx, p.fk_product_type"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; - if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$conf_fkentrepot."'"; + if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; $sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " AND p.tosell = 1"; if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; diff --git a/htdocs/cashdesk/facturation_dhtml.php b/htdocs/cashdesk/facturation_dhtml.php index 99e1ed2f942..9ee4bdb856c 100644 --- a/htdocs/cashdesk/facturation_dhtml.php +++ b/htdocs/cashdesk/facturation_dhtml.php @@ -45,7 +45,7 @@ if (dol_strlen($search) >= 0) // If search criteria is on char length at least $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; - if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$conf_fkentrepot."'"; + if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; $sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " AND p.tosell = 1"; $sql .= " AND p.fk_product_type = 0"; diff --git a/htdocs/cashdesk/facturation_verif.php b/htdocs/cashdesk/facturation_verif.php index c62e31b1e3f..16b4bfec017 100644 --- a/htdocs/cashdesk/facturation_verif.php +++ b/htdocs/cashdesk/facturation_verif.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/cashdesk/class/Facturation.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $obj_facturation = unserialize($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']); diff --git a/htdocs/cashdesk/index_verif.php b/htdocs/cashdesk/index_verif.php index 204af8f51f7..e8366e981cc 100644 --- a/htdocs/cashdesk/index_verif.php +++ b/htdocs/cashdesk/index_verif.php @@ -89,7 +89,7 @@ if ($retour >= 0) $sql = "SELECT rowid, lastname, firstname"; $sql .= " FROM ".MAIN_DB_PREFIX."user"; - $sql .= " WHERE login = '".$username."'"; + $sql .= " WHERE login = '".$db->escape($username)."'"; $sql .= " AND entity IN (0,".$conf->entity.")"; $result = $db->query($sql); diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index 3253d6d5d3e..6b8e9af94f1 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -294,9 +294,8 @@ switch ($action) // Add the payment $payment = new Paiement($db); $payment->datepaye = $now; - $payment->bank_account = $conf_fkaccount; $payment->amounts[$invoice->id] = $obj_facturation->amountWithTax(); - $payment->note = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice(); + $payment->note_public = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice(); $payment->paiementid = $invoice->mode_reglement_id; $payment->num_paiement = ''; $payment->num_payment = ''; diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index bd285e5efaf..72151abdcdb 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -39,7 +39,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'categorie'; //Must be the $element of the class that manage extrafield diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 8eb6c3d8eda..096a5497efd 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -88,6 +88,10 @@ if ($action == 'add' && $user->rights->categorie->creer) { header("Location: ".$urlfrom); exit; + } elseif ($backtopage) + { + header("Location: ".$backtopage); + exit; } elseif ($idProdOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type); @@ -235,13 +239,13 @@ if ($user->rights->categorie->creer) // Ref print ''; - print ''.$langs->trans("Ref").''; + print ''.$langs->trans("Ref").''; print''; // Description print ''.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%'); + $doleditor = new DolEditor('description', $description, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_5, '90%'); $doleditor->Create(); print ''; diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 1cbaf4cbe14..5f0a28340f9 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -20,10 +20,12 @@ use Luracast\Restler\RestException; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/api_members.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/api_products.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/api_contacts.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/api_thirdparties.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/api_projects.class.php'; /** * API class for categories @@ -33,724 +35,727 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/api_thirdparties.class.php'; */ class Categories extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'label', - 'type' - ); - - static $TYPES = array( - 0 => 'product', - 1 => 'supplier', - 2 => 'customer', - 3 => 'member', - 4 => 'contact', - 5 => 'account', - //6 => 'project', - //7 => 'user', - //8 => 'bank_line', - //9 => 'warehouse', - //10 => 'actioncomm', - ); - - /** - * @var Categorie $category {@type Categorie} - */ - public $category; - - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->category = new Categorie($this->db); - } - - /** - * Get properties of a category object - * - * Return an array with category informations - * - * @param int $id ID of category - * @param bool $include_childs Include child categories list (true or false) - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id, $include_childs = false) - { - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if ($include_childs) { - $cats = $this->category->get_filles(); - if (!is_array($cats)) { - throw new RestException(500, 'Error when fetching child categories', array_merge(array($this->category->error), $this->category->errors)); - } - $this->category->childs = []; - foreach ($cats as $cat) { - $this->category->childs[] = $this->_cleanObjectDatas($cat); - } - } - - return $this->_cleanObjectDatas($this->category); - } - - /** - * List categories - * - * Get a list of categories - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" - * @return array Array of category objects - * - * @throws RestException - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $sqlfilters = '') - { - global $db, $conf; - - $obj_ret = array(); - - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; - $sql .= ' WHERE t.entity IN ('.getEntity('category').')'; - if (!empty($type)) - { - $sql .= ' AND t.type='.array_search($type, Categories::$TYPES); - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $db->plimit($limit + 1, $offset); - } - - $result = $db->query($sql); - if ($result) - { - $i = 0; - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $category_static = new Categorie($db); - if ($category_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($category_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve category list : '.$db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No category found'); - } - return $obj_ret; - } - - /** - * Create category object - * - * @param array $request_data Request data - * @return int ID of category - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->categorie->creer) { - throw new RestException(401); - } - - // Check mandatory fields - $result = $this->_validate($request_data); - - foreach ($request_data as $field => $value) { - $this->category->$field = $value; - } - if ($this->category->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, 'Error when creating category', array_merge(array($this->category->error), $this->category->errors)); - } - return $this->category->id; - } - - /** - * Update category - * - * @param int $id Id of category to update - * @param array $request_data Datas - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->categorie->creer) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->category->$field = $value; - } - - if ($this->category->update(DolibarrApiAccess::$user) > 0) - { - return $this->get($id); - } else { - throw new RestException(500, $this->category->error); - } - } - - /** - * Delete category - * - * @param int $id Category ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->categorie->supprimer) { - throw new RestException(401); - } - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if (!$this->category->delete(DolibarrApiAccess::$user)) { - throw new RestException(401, 'error when delete category'); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Category deleted' - ) - ); - } - - /** - * List categories of an object - * - * Get the list of categories linked to an object - * - * @param int $id Object ID - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @return array Array of category objects - * - * @throws RestException - * - * @url GET /object/{type}/{id} - */ - public function getListForObject($id, $type, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) - { - if (!in_array($type, [ - Categorie::TYPE_PRODUCT, - Categorie::TYPE_CONTACT, - Categorie::TYPE_CUSTOMER, - Categorie::TYPE_SUPPLIER, - Categorie::TYPE_MEMBER - ])) { - throw new RestException(401); - } - - if ($type == Categorie::TYPE_PRODUCT && !(DolibarrApiAccess::$user->rights->produit->lire || DolibarrApiAccess::$user->rights->service->lire)) { - throw new RestException(401); - } elseif ($type == Categorie::TYPE_CONTACT && !DolibarrApiAccess::$user->rights->contact->lire) { - throw new RestException(401); - } elseif ($type == Categorie::TYPE_CUSTOMER && !DolibarrApiAccess::$user->rights->societe->lire) { - throw new RestException(401); - } elseif ($type == Categorie::TYPE_SUPPLIER && !DolibarrApiAccess::$user->rights->fournisseur->lire) { - throw new RestException(401); - } elseif ($type == Categorie::TYPE_MEMBER && !DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } - - $categories = $this->category->getListForItem($id, $type, $sortfield, $sortorder, $limit, $page); - - if (!is_array($categories)) { - if ($categories == 0) { - throw new RestException(404, 'No category found for this object'); - } - throw new RestException(500, 'Error when fetching object categories', array_merge(array($this->category->error), $this->category->errors)); - } - return $categories; - } - - /** - * Link an object to a category by id - * - * @param int $id ID of category - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param int $object_id ID of object - * - * @return array - * @throws RestException - * - * @url POST {id}/objects/{type}/{object_id} - */ - public function linkObjectById($id, $type, $object_id) - { - if (empty($type) || empty($object_id)) { - throw new RestException(401); - } - - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if ($type === Categorie::TYPE_PRODUCT) { - if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { - throw new RestException(401); - } - $object = new Product($this->db); - } elseif ($type === Categorie::TYPE_CUSTOMER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_SUPPLIER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_CONTACT) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401); - } - $object = new Contact($this->db); - } elseif ($type === Categorie::TYPE_MEMBER) { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } - $object = new Adherent($this->db); - } else { - throw new RestException(401, "this type is not recognized yet."); - } - - if (!empty($object)) { - $result = $object->fetch($object_id); - if ($result > 0) { - $result = $this->category->add_type($object, $type); - if ($result < 0) { - if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { - throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); - } - } - } else { - throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Objects succefully linked to the category' - ) - ); - } - - throw new RestException(401); - } - - /** - * Link an object to a category by ref - * - * @param int $id ID of category - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param string $object_ref Reference of object - * - * @return array - * @throws RestException - * - * @url POST {id}/objects/{type}/ref/{object_ref} - */ - public function linkObjectByRef($id, $type, $object_ref) - { - if (empty($type) || empty($object_ref)) { - throw new RestException(401); - } - - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if ($type === Categorie::TYPE_PRODUCT) { - if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { - throw new RestException(401); - } - $object = new Product($this->db); - } elseif ($type === Categorie::TYPE_CUSTOMER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_SUPPLIER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_CONTACT) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401); - } - $object = new Contact($this->db); - } elseif ($type === Categorie::TYPE_MEMBER) { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } - $object = new Adherent($this->db); - } else { - throw new RestException(401, "this type is not recognized yet."); - } - - if (!empty($object)) { - $result = $object->fetch('', $object_ref); - if ($result > 0) { - $result = $this->category->add_type($object, $type); - if ($result < 0) { - if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { - throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); - } - } - } else { - throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Objects succefully linked to the category' - ) - ); - } - - throw new RestException(401); - } - - /** - * Unlink an object from a category by id - * - * @param int $id ID of category - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param int $object_id ID of the object - * - * @return array - * @throws RestException - * - * @url DELETE {id}/objects/{type}/{object_id} - */ - public function unlinkObjectById($id, $type, $object_id) - { - if (empty($type) || empty($object_id)) { - throw new RestException(401); - } - - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if ($type === Categorie::TYPE_PRODUCT) { - if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { - throw new RestException(401); - } - $object = new Product($this->db); - } elseif ($type === Categorie::TYPE_CUSTOMER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_SUPPLIER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_CONTACT) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401); - } - $object = new Contact($this->db); - } elseif ($type === Categorie::TYPE_MEMBER) { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } - $object = new Adherent($this->db); - } else { - throw new RestException(401, "this type is not recognized yet."); - } - - if (!empty($object)) { - $result = $object->fetch((int) $object_id); - if ($result > 0) { - $result = $this->category->del_type($object, $type); - if ($result < 0) { - throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); - } - } else { - throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Objects succefully unlinked from the category' - ) - ); - } - - throw new RestException(401); - } - - /** - * Unlink an object from a category by ref - * - * @param int $id ID of category - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param string $object_ref Reference of the object - * - * @return array - * @throws RestException - * - * @url DELETE {id}/objects/{type}/ref/{object_ref} - */ - public function unlinkObjectByRef($id, $type, $object_ref) - { - if (empty($type) || empty($object_ref)) { - throw new RestException(401); - } - - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } - - if ($type === Categorie::TYPE_PRODUCT) { - if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { - throw new RestException(401); - } - $object = new Product($this->db); - } elseif ($type === Categorie::TYPE_CUSTOMER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_SUPPLIER) { - if (!DolibarrApiAccess::$user->rights->societe->creer) { - throw new RestException(401); - } - $object = new Societe($this->db); - } elseif ($type === Categorie::TYPE_CONTACT) { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401); - } - $object = new Contact($this->db); - } elseif ($type === Categorie::TYPE_MEMBER) { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } - $object = new Adherent($this->db); - } else { - throw new RestException(401, "this type is not recognized yet."); - } - - if (!empty($object)) { - $result = $object->fetch('', (string) $object_ref); - if ($result > 0) { - $result = $this->category->del_type($object, $type); - if ($result < 0) { - throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); - } - } else { - throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Objects succefully unlinked from the category' - ) - ); - } - - throw new RestException(401); - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Categorie $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); - - // Remove fields not relevent to categories - unset($object->country); - unset($object->country_id); - unset($object->country_code); - unset($object->total_ht); - unset($object->total_ht); - unset($object->total_localtax1); - unset($object->total_localtax2); - unset($object->total_ttc); - unset($object->total_tva); - unset($object->lines); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->civility_id); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->shipping_method_id); - unset($object->fk_delivery_address); - unset($object->cond_reglement); - unset($object->cond_reglement_id); - unset($object->mode_reglement_id); - unset($object->barcode_type_coder); - unset($object->barcode_type_label); - unset($object->barcode_type_code); - unset($object->barcode_type); - unset($object->canvas); - unset($object->cats); - unset($object->motherof); - unset($object->context); - unset($object->socid); - unset($object->thirdparty); - unset($object->contact); - unset($object->contact_id); - unset($object->user); - unset($object->fk_account); - unset($object->fk_project); - unset($object->note); - unset($object->statut); - - return $object; - } - - /** - * Validate fields before create or update object - * - * @param array|null $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $category = array(); - foreach (Categories::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $category[$field] = $data[$field]; - } - return $category; - } - - /** - * Get the list of objects in a category. - * - * @param int $id ID of category - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param int $onlyids Return only ids of objects (consume less memory) - * - * @return mixed - * - * @url GET {id}/objects - */ - public function getObjects($id, $type, $onlyids = 0) - { + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'label', + 'type' + ); + + static $TYPES = array( + 0 => 'product', + 1 => 'supplier', + 2 => 'customer', + 3 => 'member', + 4 => 'contact', + 5 => 'account', + 6 => 'project', + //7 => 'user', + //8 => 'bank_line', + //9 => 'warehouse', + //10 => 'actioncomm', + ); + + /** + * @var Categorie $category {@type Categorie} + */ + public $category; + + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->category = new Categorie($this->db); + } + + /** + * Get properties of a category object + * + * Return an array with category informations + * + * @param int $id ID of category + * @param bool $include_childs Include child categories list (true or false) + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id, $include_childs = false) + { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if ($include_childs) { + $cats = $this->category->get_filles(); + if (!is_array($cats)) { + throw new RestException(500, 'Error when fetching child categories', array_merge(array($this->category->error), $this->category->errors)); + } + $this->category->childs = []; + foreach ($cats as $cat) { + $this->category->childs[] = $this->_cleanObjectDatas($cat); + } + } + + return $this->_cleanObjectDatas($this->category); + } + + /** + * List categories + * + * Get a list of categories + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of category objects + * + * @throws RestException + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $sqlfilters = '') + { + global $db, $conf; + + $obj_ret = array(); + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('category').')'; + if (!empty($type)) + { + $sql .= ' AND t.type='.array_search($type, Categories::$TYPES); + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit + 1, $offset); + } + + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $category_static = new Categorie($this->db); + if ($category_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($category_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No category found'); + } + return $obj_ret; + } + + /** + * Create category object + * + * @param array $request_data Request data + * @return int ID of category + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->categorie->creer) { + throw new RestException(401); + } + + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach ($request_data as $field => $value) { + $this->category->$field = $value; + } + if ($this->category->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, 'Error when creating category', array_merge(array($this->category->error), $this->category->errors)); + } + return $this->category->id; + } + + /** + * Update category + * + * @param int $id Id of category to update + * @param array $request_data Datas + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->categorie->creer) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->category->$field = $value; + } + + if ($this->category->update(DolibarrApiAccess::$user) > 0) { + return $this->get($id); + } else { + throw new RestException(500, $this->category->error); + } + } + + /** + * Delete category + * + * @param int $id Category ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->categorie->supprimer) { + throw new RestException(401); + } + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (!$this->category->delete(DolibarrApiAccess::$user)) { + throw new RestException(401, 'error when delete category'); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Category deleted' + ) + ); + } + + /** + * List categories of an object + * + * Get the list of categories linked to an object + * + * @param int $id Object ID + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact', 'project') + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @return array Array of category objects + * + * @throws RestException + * + * @url GET /object/{type}/{id} + */ + public function getListForObject($id, $type, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + if (!in_array($type, [ + Categorie::TYPE_PRODUCT, + Categorie::TYPE_CONTACT, + Categorie::TYPE_CUSTOMER, + Categorie::TYPE_SUPPLIER, + Categorie::TYPE_MEMBER, + Categorie::TYPE_PROJECT + ])) { + throw new RestException(401); + } + + if ($type == Categorie::TYPE_PRODUCT && !(DolibarrApiAccess::$user->rights->produit->lire || DolibarrApiAccess::$user->rights->service->lire)) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_CONTACT && !DolibarrApiAccess::$user->rights->contact->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_CUSTOMER && !DolibarrApiAccess::$user->rights->societe->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_SUPPLIER && !DolibarrApiAccess::$user->rights->fournisseur->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_MEMBER && !DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } elseif ($type == Categorie::TYPE_PROJECT && !DolibarrApiAccess::$user->rights->projet->lire) { + throw new RestException(401); + } + + $categories = $this->category->getListForItem($id, $type, $sortfield, $sortorder, $limit, $page); + + if (!is_array($categories)) { + if ($categories == 0) { + throw new RestException(404, 'No category found for this object'); + } + throw new RestException(600, 'Error when fetching object categories', array_merge(array($this->category->error), $this->category->errors)); + } + return $categories; + } + + /** + * Link an object to a category by id + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param int $object_id ID of object + * + * @return array + * @throws RestException + * + * @url POST {id}/objects/{type}/{object_id} + */ + public function linkObjectById($id, $type, $object_id) + { + if (empty($type) || empty($object_id)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch($object_id); + if ($result > 0) { + $result = $this->category->add_type($object, $type); + if ($result < 0) { + if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { + throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); + } + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully linked to the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Link an object to a category by ref + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $object_ref Reference of object + * + * @return array + * @throws RestException + * + * @url POST {id}/objects/{type}/ref/{object_ref} + */ + public function linkObjectByRef($id, $type, $object_ref) + { + if (empty($type) || empty($object_ref)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch('', $object_ref); + if ($result > 0) { + $result = $this->category->add_type($object, $type); + if ($result < 0) { + if ($this->category->error != 'DB_ERROR_RECORD_ALREADY_EXISTS') { + throw new RestException(500, 'Error when linking object', array_merge(array($this->category->error), $this->category->errors)); + } + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully linked to the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Unlink an object from a category by id + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param int $object_id ID of the object + * + * @return array + * @throws RestException + * + * @url DELETE {id}/objects/{type}/{object_id} + */ + public function unlinkObjectById($id, $type, $object_id) + { + if (empty($type) || empty($object_id)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch((int) $object_id); + if ($result > 0) { + $result = $this->category->del_type($object, $type); + if ($result < 0) { + throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully unlinked from the category' + ) + ); + } + + throw new RestException(401); + } + + /** + * Unlink an object from a category by ref + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $object_ref Reference of the object + * + * @return array + * @throws RestException + * + * @url DELETE {id}/objects/{type}/ref/{object_ref} + */ + public function unlinkObjectByRef($id, $type, $object_ref) + { + if (empty($type) || empty($object_ref)) { + throw new RestException(401); + } + + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } + + if ($type === Categorie::TYPE_PRODUCT) { + if (!(DolibarrApiAccess::$user->rights->produit->creer || DolibarrApiAccess::$user->rights->service->creer)) { + throw new RestException(401); + } + $object = new Product($this->db); + } elseif ($type === Categorie::TYPE_CUSTOMER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_SUPPLIER) { + if (!DolibarrApiAccess::$user->rights->societe->creer) { + throw new RestException(401); + } + $object = new Societe($this->db); + } elseif ($type === Categorie::TYPE_CONTACT) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401); + } + $object = new Contact($this->db); + } elseif ($type === Categorie::TYPE_MEMBER) { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + $object = new Adherent($this->db); + } else { + throw new RestException(401, "this type is not recognized yet."); + } + + if (!empty($object)) { + $result = $object->fetch('', (string) $object_ref); + if ($result > 0) { + $result = $this->category->del_type($object, $type); + if ($result < 0) { + throw new RestException(500, 'Error when unlinking object', array_merge(array($this->category->error), $this->category->errors)); + } + } else { + throw new RestException(500, 'Error when fetching object', array_merge(array($object->error), $object->errors)); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Objects succefully unlinked from the category' + ) + ); + } + + throw new RestException(401); + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Categorie $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + // Remove fields not relevent to categories + unset($object->country); + unset($object->country_id); + unset($object->country_code); + unset($object->total_ht); + unset($object->total_ht); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); + unset($object->total_tva); + unset($object->lines); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->civility_id); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->shipping_method_id); + unset($object->fk_delivery_address); + unset($object->cond_reglement); + unset($object->cond_reglement_id); + unset($object->mode_reglement_id); + unset($object->barcode_type_coder); + unset($object->barcode_type_label); + unset($object->barcode_type_code); + unset($object->barcode_type); + unset($object->canvas); + unset($object->cats); + unset($object->motherof); + unset($object->context); + unset($object->socid); + unset($object->thirdparty); + unset($object->contact); + unset($object->contact_id); + unset($object->user); + unset($object->fk_account); + unset($object->fk_project); + unset($object->note); + unset($object->statut); + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $category = array(); + foreach (Categories::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $category[$field] = $data[$field]; + } + return $category; + } + + /** + * Get the list of objects in a category. + * + * @param int $id ID of category + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact', 'project') + * @param int $onlyids Return only ids of objects (consume less memory) + * + * @return mixed + * + * @url GET {id}/objects + */ + public function getObjects($id, $type, $onlyids = 0) + { dol_syslog("getObjects($id, $type, $onlyids)", LOG_DEBUG); if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } - if (empty($type)) - { + if (empty($type)) + { throw new RestException(500, 'The "type" parameter is required.'); - } + } - $result = $this->category->fetch($id); - if (!$result) { - throw new RestException(404, 'category not found'); - } + $result = $this->category->fetch($id); + if (!$result) { + throw new RestException(404, 'category not found'); + } if (!DolibarrApi::_checkAccessToResource('categorie', $this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); @@ -763,8 +768,8 @@ class Categories extends DolibarrApi } $objects = $result; - $cleaned_objects = array(); - if ($type == 'member') { + $cleaned_objects = array(); + if ($type == 'member') { $objects_api = new Members(); } elseif ($type == 'customer' || $type == 'supplier') { $objects_api = new Thirdparties(); @@ -772,14 +777,15 @@ class Categories extends DolibarrApi $objects_api = new Products(); } elseif ($type == 'contact') { $objects_api = new Contacts(); + } elseif ($type == 'project') { + $objects_api = new Projects(); } - if (is_object($objects_api)) - { - foreach ($objects as $obj) { - $cleaned_objects[] = $objects_api->_cleanObjectDatas($obj); - } + if (is_object($objects_api)) { + foreach ($objects as $obj) { + $cleaned_objects[] = $objects_api->_cleanObjectDatas($obj); + } } return $cleaned_objects; - } + } } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 6128ab5e2df..1bc9f47ded4 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -52,10 +52,10 @@ class Categorie extends CommonObject const TYPE_USER = 'user'; const TYPE_PROJECT = 'project'; const TYPE_ACCOUNT = 'bank_account'; - const TYPE_BANK_LINE = 'bank_line'; - const TYPE_WAREHOUSE = 'warehouse'; - const TYPE_ACTIONCOMM = 'actioncomm'; - const TYPE_WEBSITE_PAGE = 'website_page'; + const TYPE_BANK_LINE = 'bank_line'; + const TYPE_WAREHOUSE = 'warehouse'; + const TYPE_ACTIONCOMM = 'actioncomm'; + const TYPE_WEBSITE_PAGE = 'website_page'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png @@ -73,15 +73,15 @@ class Categorie extends CommonObject 'member' => 3, 'contact' => 4, 'bank_account' => 5, - 'project' => 6, + 'project' => 6, 'user' => 7, 'bank_line' => 8, 'warehouse' => 9, - 'actioncomm' => 10, + 'actioncomm' => 10, 'website_page' => 11 ); - /** + /** * @var array Code mapping from ID * * @note This array should be removed in future, once previous constants are moved to the string value. Deprecated @@ -97,7 +97,7 @@ class Categorie extends CommonObject 7 => 'user', 8 => 'bank_line', 9 => 'warehouse', - 10 => 'actioncomm', + 10 => 'actioncomm', ); /** @@ -109,10 +109,10 @@ class Categorie extends CommonObject 'customer' => 'soc', 'supplier' => 'soc', 'contact' => 'socpeople', - 'bank_account' => 'account', - ); + 'bank_account' => 'account', + ); - /** + /** * @var array Category tables mapping from type string (llx_categorie_...) when value does not match * * @note Move to const array when PHP 5.6 will be our minimum target @@ -120,10 +120,10 @@ class Categorie extends CommonObject protected $MAP_CAT_TABLE = array( 'customer' => 'societe', 'supplier' => 'fournisseur', - 'bank_account'=> 'account', + 'bank_account'=> 'account', ); - /** + /** * @var array Object class mapping from type string * * @note Move to const array when PHP 5.6 will be our minimum target @@ -137,33 +137,33 @@ class Categorie extends CommonObject 'user' => 'User', 'account' => 'Account', // old for bank account 'bank_account' => 'Account', - 'project' => 'Project', - 'warehouse'=> 'Entrepot', - 'actioncomm' => 'ActionComm', + 'project' => 'Project', + 'warehouse'=> 'Entrepot', + 'actioncomm' => 'ActionComm', 'website_page' => 'WebsitePage' ); - /** - * @var array Title Area mapping from type string - * - * @note Move to const array when PHP 5.6 will be our minimum target - */ - public static $MAP_TYPE_TITLE_AREA = array( - 'product' => 'ProductsCategoriesArea', - 'customer' => 'CustomersCategoriesArea', - 'supplier' => 'SuppliersCategoriesArea', - 'member' => 'MembersCategoriesArea', - 'contact' => 'ContactsCategoriesArea', - 'user' => 'UsersCategoriesArea', - 'account' => 'AccountsCategoriesArea', // old for bank account - 'bank_account' => 'AccountsCategoriesArea', - 'project' => 'ProjectsCategoriesArea', - 'warehouse'=> 'StocksCategoriesArea', - 'actioncomm' => 'ActioncommCategoriesArea', - 'website_page' => 'WebsitePageCategoriesArea' - ); + /** + * @var array Title Area mapping from type string + * + * @note Move to const array when PHP 5.6 will be our minimum target + */ + public static $MAP_TYPE_TITLE_AREA = array( + 'product' => 'ProductsCategoriesArea', + 'customer' => 'CustomersCategoriesArea', + 'supplier' => 'SuppliersCategoriesArea', + 'member' => 'MembersCategoriesArea', + 'contact' => 'ContactsCategoriesArea', + 'user' => 'UsersCategoriesArea', + 'account' => 'AccountsCategoriesArea', // old for bank account + 'bank_account' => 'AccountsCategoriesArea', + 'project' => 'ProjectsCategoriesArea', + 'warehouse'=> 'StocksCategoriesArea', + 'actioncomm' => 'ActioncommCategoriesArea', + 'website_page' => 'WebsitePageCategoriesArea' + ); - /** + /** * @var array Object table mapping from type string (table llx_...) when value of key does not match table name. * * @note Move to const array when PHP 5.6 will be our minimum target @@ -175,7 +175,7 @@ class Categorie extends CommonObject 'contact' => 'socpeople', 'account' => 'bank_account', // old for bank account 'project' => 'projet', - 'warehouse'=> 'entrepot' + 'warehouse'=> 'entrepot' ); /** @@ -189,13 +189,13 @@ class Categorie extends CommonObject public $table_element = 'categorie'; /** - * @var int ID - */ + * @var int ID + */ public $fk_parent; /** - * @var string Category label - */ + * @var string Category label + */ public $label; /** @@ -225,8 +225,8 @@ class Categorie extends CommonObject * @see Categorie::TYPE_USER * @see Categorie::TYPE_PROJECT * @see Categorie::TYPE_BANK_LINE - * @see Categorie::TYPE_WAREHOUSE - * @see Categorie::TYPE_ACTIONCOMM + * @see Categorie::TYPE_WAREHOUSE + * @see Categorie::TYPE_ACTIONCOMM */ public $type; @@ -235,7 +235,7 @@ class Categorie extends CommonObject */ public $cats = array(); - /** + /** * @var array Mother of table */ public $motherof = array(); @@ -464,20 +464,20 @@ class Categorie extends CommonObject if (!$error) { - // Call trigger - $result = $this->call_trigger('CATEGORY_CREATE', $user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result = $this->call_trigger('CATEGORY_CREATE', $user); + if ($result < 0) { $error++; } + // End call triggers } - if (!$error) - { - $this->db->commit(); - return $id; - } else { - $this->db->rollback(); - return -3; - } + if (!$error) + { + $this->db->commit(); + return $id; + } else { + $this->db->rollback(); + return -3; + } } else { $this->db->rollback(); return -2; @@ -550,10 +550,10 @@ class Categorie extends CommonObject if (!$error) { - // Call trigger - $result = $this->call_trigger('CATEGORY_MODIFY', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result = $this->call_trigger('CATEGORY_MODIFY', $user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -570,7 +570,7 @@ class Categorie extends CommonObject * Delete a category from database * * @param User $user Object user that ask to delete - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 KO >0 OK */ public function delete($user, $notrigger = 0) @@ -579,7 +579,7 @@ class Categorie extends CommonObject $error = 0; - // Clean parameters + // Clean parameters $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); dol_syslog(get_class($this)."::remove"); @@ -588,10 +588,10 @@ class Categorie extends CommonObject if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('CATEGORY_DELETE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('CATEGORY_DELETE', $user); + if ($result < 0) $error++; + // End call triggers } /* FIX #1317 : Check for child category and move up 1 level*/ @@ -608,26 +608,26 @@ class Categorie extends CommonObject } } - $arraydelete = array( - 'categorie_societe' => 'fk_categorie', - 'categorie_fournisseur' => 'fk_categorie', - 'categorie_product' => 'fk_categorie', - 'categorie_member' => 'fk_categorie', - 'categorie_contact' => 'fk_categorie', - 'categorie_account' => 'fk_categorie', - 'bank_class' => 'fk_categ', - 'categorie_lang' => 'fk_category', - 'categorie' => 'rowid', - ); - foreach ($arraydelete as $key => $value) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key; - $sql .= " WHERE ".$value." = ".$this->id; - if (!$this->db->query($sql)) { - $this->errors[] = $this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); - $error++; - } - } + $arraydelete = array( + 'categorie_societe' => 'fk_categorie', + 'categorie_fournisseur' => 'fk_categorie', + 'categorie_product' => 'fk_categorie', + 'categorie_member' => 'fk_categorie', + 'categorie_contact' => 'fk_categorie', + 'categorie_account' => 'fk_categorie', + 'bank_class' => 'fk_categ', + 'categorie_lang' => 'fk_category', + 'categorie' => 'rowid', + ); + foreach ($arraydelete as $key => $value) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key; + $sql .= " WHERE ".$value." = ".$this->id; + if (!$this->db->query($sql)) { + $this->errors[] = $this->db->lasterror(); + dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); + $error++; + } + } // Removed extrafields if (!$error) @@ -650,7 +650,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Link an object to the category * @@ -660,7 +660,7 @@ class Categorie extends CommonObject */ public function add_type($obj, $type = '') { - // phpcs:enable + // phpcs:enable global $user, $langs, $conf; $error = 0; @@ -669,9 +669,9 @@ class Categorie extends CommonObject if (empty($type)) $type = $obj->element; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]); $sql .= " (fk_categorie, fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]).")"; $sql .= " VALUES (".$this->id.", ".$obj->id.")"; @@ -689,7 +689,7 @@ class Categorie extends CommonObject { if ($this->db->num_rows($resql) > 0) { - $objparent = $this->db->fetch_object($resql); + $objparent = $this->db->fetch_object($resql); if (!empty($objparent->fk_parent)) { @@ -712,29 +712,29 @@ class Categorie extends CommonObject if ($error) { - $this->db->rollback(); + $this->db->rollback(); return -1; } } - // Call trigger + // 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++; } - // End call triggers + if ($result < 0) { $error++; } + // End call triggers if (!$error) { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } else { - $this->db->rollback(); - return -2; + $this->db->rollback(); + return -2; } } else { - $this->db->rollback(); + $this->db->rollback(); if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error = $this->db->lasterrno(); @@ -746,7 +746,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete object from category * @@ -757,7 +757,7 @@ class Categorie extends CommonObject */ public function del_type($obj, $type) { - // phpcs:enable + // phpcs:enable global $user, $langs, $conf; $error = 0; @@ -771,31 +771,31 @@ class Categorie extends CommonObject dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); } - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type]); $sql .= " WHERE fk_categorie = ".$this->id; $sql .= " AND fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".$obj->id; dol_syslog(get_class($this).'::del_type', LOG_DEBUG); if ($this->db->query($sql)) { - // Call trigger + // 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++; } - // End call triggers + if ($result < 0) { $error++; } + // End call triggers if (!$error) { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } else { - $this->db->rollback(); - return -2; + $this->db->rollback(); + return -2; } } else { - $this->db->rollback(); + $this->db->rollback(); $this->error = $this->db->lasterror(); return -1; } @@ -819,8 +819,8 @@ class Categorie extends CommonObject $objs = array(); - $tmpclass = $this->MAP_OBJ_CLASS[$type]; - $obj = new $tmpclass($this->db); + $classnameforobj = $this->MAP_OBJ_CLASS[$type]; + $obj = new $classnameforobj($this->db); $sql = "SELECT c.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type]); $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as c"; @@ -842,14 +842,16 @@ class Categorie extends CommonObject { while ($rec = $this->db->fetch_array($resql)) { - if ($onlyids) - { - $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]; - } else { - $obj = new $this->MAP_OBJ_CLASS[$type]($this->db); - $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]); - $objs[] = $obj; - } + if ($onlyids) { + $objs[] = $rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]; + } else { + $classnameforobj = $this->MAP_OBJ_CLASS[$type]; + + $obj = new $classnameforobj($this->db); + $obj->fetch($rec['fk_'.(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])]); + + $objs[] = $obj; + } } return $objs; } else { @@ -988,7 +990,7 @@ class Categorie extends CommonObject return $categories; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return direct childs id of a category into an array * @@ -996,7 +998,7 @@ class Categorie extends CommonObject */ public function get_filles() { - // phpcs:enable + // phpcs:enable $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql .= " WHERE fk_parent = ".$this->id; $sql .= " AND entity IN (".getEntity('category').")"; @@ -1018,7 +1020,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the array this->motherof that is array(id_son=>id_parent, ...) * @@ -1026,8 +1028,8 @@ class Categorie extends CommonObject */ protected function load_motherof() { - // phpcs:enable - $this->motherof = array(); + // phpcs:enable + $this->motherof = array(); // Load array[child]=parent $sql = "SELECT fk_parent as id_parent, rowid as id_son"; @@ -1050,7 +1052,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Rebuilding the category tree as an array * Return an array of table('id','id_mere',...) trie selon arbre et avec: @@ -1063,17 +1065,17 @@ class Categorie extends CommonObject * * @param string $type Type of categories ('customer', 'supplier', 'contact', 'product', 'member', ...) * @param int|string|array $markafterid Keep only or removed all categories including the leaf $markafterid in category tree (exclude) or Keep only of category is inside the leaf starting with this id. - * $markafterid can be an : - * - int (id of category) - * - string (categories ids separated by comma) - * - array (list of categories ids) - * @param int $include [=0] Removed or 1=Keep only + * $markafterid can be an : + * - int (id of category) + * - string (categories ids separated by comma) + * - array (list of categories ids) + * @param int $include [=0] Removed or 1=Keep only * @return array|int Array of categories. this->cats and this->motherof are set, -1 on error */ public function get_full_arbo($type, $markafterid = 0, $include = 0) { - // phpcs:enable - global $conf, $langs; + // phpcs:enable + global $conf, $langs; if (!is_numeric($type)) $type = $this->MAP_ID[$type]; if (is_null($type)) { @@ -1081,23 +1083,23 @@ class Categorie extends CommonObject return -1; } - if (is_string($markafterid)) - { - $markafterid = explode(',', $markafterid); - } elseif (is_numeric($markafterid)) - { - if ($markafterid > 0) - { - $markafterid = array($markafterid); - } else { - $markafterid = array(); - } - } elseif (!is_array($markafterid)) - { - $markafterid = array(); - } + if (is_string($markafterid)) + { + $markafterid = explode(',', $markafterid); + } elseif (is_numeric($markafterid)) + { + if ($markafterid > 0) + { + $markafterid = array($markafterid); + } else { + $markafterid = array(); + } + } elseif (!is_array($markafterid)) + { + $markafterid = array(); + } - $this->cats = array(); + $this->cats = array(); // Init this->motherof that is array(id_son=>id_parent, ...) $this->load_motherof(); @@ -1141,27 +1143,27 @@ class Categorie extends CommonObject $this->build_path_from_id_categ($key, 0); // Process a branch from the root category key (this category has no parent) } - // Include or exclude leaf including $markafterid from tree - if (count($markafterid) > 0) - { - $keyfiltercatid = '('.implode('|', $markafterid).')'; + // Include or exclude leaf including $markafterid from tree + if (count($markafterid) > 0) + { + $keyfiltercatid = '('.implode('|', $markafterid).')'; - //print "Look to discard category ".$markafterid."\n"; - $keyfilter1 = '^'.$keyfiltercatid.'$'; - $keyfilter2 = '_'.$keyfiltercatid.'$'; - $keyfilter3 = '^'.$keyfiltercatid.'_'; - $keyfilter4 = '_'.$keyfiltercatid.'_'; - foreach ($this->cats as $key => $val) - { - $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) - || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])); + //print "Look to discard category ".$markafterid."\n"; + $keyfilter1 = '^'.$keyfiltercatid.'$'; + $keyfilter2 = '_'.$keyfiltercatid.'$'; + $keyfilter3 = '^'.$keyfiltercatid.'_'; + $keyfilter4 = '_'.$keyfiltercatid.'_'; + foreach ($this->cats as $key => $val) + { + $test = (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) + || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])); - if (($test && !$include) || (!$test && $include)) - { - unset($this->cats[$key]); - } - } - } + if (($test && !$include) || (!$test && $include)) + { + unset($this->cats[$key]); + } + } + } dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG); $this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false); @@ -1171,7 +1173,7 @@ class Categorie extends CommonObject return $this->cats; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * For category id_categ and its childs available in this->cats, define property fullpath and fulllabel. * It is called by get_full_arbo() @@ -1182,10 +1184,10 @@ class Categorie extends CommonObject * @return void * @see get_full_arbo() */ - public function build_path_from_id_categ($id_categ, $protection = 1000) - { - // phpcs:enable - dol_syslog(get_class($this)."::build_path_from_id_categ id_categ=".$id_categ." protection=".$protection, LOG_DEBUG); + public function build_path_from_id_categ($id_categ, $protection = 1000) + { + // phpcs:enable + dol_syslog(get_class($this)."::build_path_from_id_categ id_categ=".$id_categ." protection=".$protection, LOG_DEBUG); if (!empty($this->cats[$id_categ]['fullpath'])) { @@ -1216,10 +1218,10 @@ class Categorie extends CommonObject $nbunderscore = substr_count($this->cats[$id_categ]['fullpath'], '_'); $this->cats[$id_categ]['level'] = ($nbunderscore ? $nbunderscore : null); - return; - } + return; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Display content of $this->cats * @@ -1227,7 +1229,7 @@ class Categorie extends CommonObject */ public function debug_cats() { - // phpcs:enable + // phpcs:enable // Display $this->cats foreach ($this->cats as $key => $val) { @@ -1242,7 +1244,7 @@ class Categorie extends CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns all categories * @@ -1252,7 +1254,7 @@ class Categorie extends CommonObject */ public function get_all_categories($type = null, $parent = false) { - // phpcs:enable + // phpcs:enable if (!is_numeric($type)) $type = $this->MAP_ID[$type]; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; @@ -1288,11 +1290,11 @@ class Categorie extends CommonObject */ public function get_main_categories($type = null) { - // phpcs:enable - return $this->get_all_categories($type, true); + // phpcs:enable + return $this->get_all_categories($type, true); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Check if no category with same label already exists for this cat's parent or root and for this cat's type * @@ -1300,7 +1302,7 @@ class Categorie extends CommonObject */ public function already_exists() { - // phpcs:enable + // phpcs:enable $type = $this->type; if (!is_numeric($type)) $type = $this->MAP_ID[$type]; @@ -1342,7 +1344,7 @@ class Categorie extends CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns the path of the category, with the names of the categories * separated by $sep (" >> " by default) @@ -1355,7 +1357,7 @@ class Categorie extends CommonObject */ public function print_all_ways($sep = ' >> ', $url = '', $nocolor = 0, $addpicto = 0) { - // phpcs:enable + // phpcs:enable $ways = array(); $allways = $this->get_all_ways(); // Load array of categories @@ -1366,26 +1368,26 @@ class Categorie extends CommonObject $forced_color = ''; foreach ($way as $cat) { - $i++; + $i++; - if (empty($nocolor)) - { - $forced_color = 'toreplace'; - if ($i == count($way)) - { - // Check contrast with background and correct text color - $forced_color = 'categtextwhite'; - if ($cat->color) - { - if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; - } - } - } + if (empty($nocolor)) + { + $forced_color = 'toreplace'; + if ($i == count($way)) + { + // Check contrast with background and correct text color + $forced_color = 'categtextwhite'; + if ($cat->color) + { + if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; + } + } + } if ($url == '') { - $link = ''; - $linkend = ''; - $w[] = $link.($addpicto ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend; + $link = ''; + $linkend = ''; + $w[] = $link.($addpicto ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend; } elseif ($url == 'none') { $link = ''; $linkend = ''; @@ -1403,7 +1405,7 @@ class Categorie extends CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns an array containing the list of parent categories * @@ -1411,7 +1413,7 @@ class Categorie extends CommonObject */ public function get_meres() { - // phpcs:enable + // phpcs:enable $parents = array(); $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie"; @@ -1437,7 +1439,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns in a table all possible paths to get to the category * starting with the major categories represented by Tables of categories @@ -1446,7 +1448,7 @@ class Categorie extends CommonObject */ public function get_all_ways() { - // phpcs:enable + // phpcs:enable $ways = array(); $parents = $this->get_meres(); @@ -1488,60 +1490,60 @@ class Categorie extends CommonObject if ($type === Categorie::TYPE_BANK_LINE) // TODO Remove this with standard category code { - // Load bank groups - $sql = "SELECT c.label, c.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c"; - $sql .= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid"; - $sql .= " ORDER BY c.label"; + // Load bank groups + $sql = "SELECT c.label, c.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c"; + $sql .= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid"; + $sql .= " ORDER BY c.label"; - $res = $this->db->query($sql); - if ($res) - { - while ($obj = $this->db->fetch_object($res)) - { - if ($mode == 'id') { - $cats[] = $obj->rowid; - } elseif ($mode == 'label') { - $cats[] = $obj->label; - } else { - $cat = new Categorie($this->db); - $cat->id = $obj->rowid; - $cat->label = $obj->label; - $cats[] = $cat; - } - } - } else { - dol_print_error($this->db); - return -1; - } + $res = $this->db->query($sql); + if ($res) + { + while ($obj = $this->db->fetch_object($res)) + { + if ($mode == 'id') { + $cats[] = $obj->rowid; + } elseif ($mode == 'label') { + $cats[] = $obj->label; + } else { + $cat = new Categorie($this->db); + $cat->id = $obj->rowid; + $cat->label = $obj->label; + $cats[] = $cat; + } + } + } else { + dol_print_error($this->db); + return -1; + } } else { - $sql = "SELECT ct.fk_categorie, c.label, c.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as ct, ".MAIN_DB_PREFIX."categorie as c"; - $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id." AND c.type = ".$this->MAP_ID[$type]; - $sql .= " AND c.entity IN (".getEntity('category').")"; + $sql = "SELECT ct.fk_categorie, c.label, c.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".(empty($this->MAP_CAT_TABLE[$type]) ? $type : $this->MAP_CAT_TABLE[$type])." as ct, ".MAIN_DB_PREFIX."categorie as c"; + $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".(empty($this->MAP_CAT_FK[$type]) ? $type : $this->MAP_CAT_FK[$type])." = ".(int) $id." AND c.type = ".$this->MAP_ID[$type]; + $sql .= " AND c.entity IN (".getEntity('category').")"; - $res = $this->db->query($sql); - if ($res) - { - while ($obj = $this->db->fetch_object($res)) - { - if ($mode == 'id') { - $cats[] = $obj->rowid; - } elseif ($mode == 'label') { - $cats[] = $obj->label; - } else { - $cat = new Categorie($this->db); - $cat->fetch($obj->fk_categorie); - $cats[] = $cat; - } - } - } else { - dol_print_error($this->db); - return -1; - } - } + $res = $this->db->query($sql); + if ($res) + { + while ($obj = $this->db->fetch_object($res)) + { + if ($mode == 'id') { + $cats[] = $obj->rowid; + } elseif ($mode == 'label') { + $cats[] = $obj->label; + } else { + $cat = new Categorie($this->db); + $cat->fetch($obj->fk_categorie); + $cats[] = $cat; + } + } + } else { + dol_print_error($this->db); + return -1; + } + } - return $cats; + return $cats; } @@ -1551,7 +1553,7 @@ class Categorie extends CommonObject * * @param int $id Id * @param string $nom Name - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated. + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated. * @param boolean $exact Exact string search (true/false) * @param boolean $case Case sensitive (true/false) * @return Categorie[]|int Array of Categorie, -1 if error @@ -1565,15 +1567,15 @@ class Categorie extends CommonObject $cats = array(); - // For backward compatibility - if (is_numeric($type)) { - // We want to reverse lookup - $map_type = array_flip($this->MAP_ID); - $type = $map_type[$type]; - dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING); - } + // For backward compatibility + if (is_numeric($type)) { + // We want to reverse lookup + $map_type = array_flip($this->MAP_ID); + $type = $map_type[$type]; + dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING); + } - // Generation requete recherche + // Generation requete recherche $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql .= " WHERE type = ".$this->MAP_ID[$type]; $sql .= " AND entity IN (".getEntity('category').")"; @@ -1614,9 +1616,10 @@ class Categorie extends CommonObject * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param string $option Sur quoi pointe le lien ('', 'xyz') * @param int $maxlength Max length of text + * @param string $moreparam More param on URL link * @return string Chaine avec URL */ - public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0) + public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $moreparam = '') { global $langs; @@ -1630,20 +1633,20 @@ class Categorie extends CommonObject if (colorIsLight($this->color)) $forced_color = 'categtextblack'; } - $link = ''; + $link = ''; $linkend = ''; $picto = 'category'; - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$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; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Deplace fichier uploade sous le nom $files dans le repertoire sdir * @@ -1653,7 +1656,7 @@ class Categorie extends CommonObject */ public function add_photo($sdir, $file) { - // phpcs:enable + // phpcs:enable require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/"; @@ -1693,7 +1696,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return tableau de toutes les photos de la categorie * @@ -1703,7 +1706,7 @@ class Categorie extends CommonObject */ public function liste_photos($dir, $nbmax = 0) { - // phpcs:enable + // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $nbphoto = 0; @@ -1714,43 +1717,43 @@ class Categorie extends CommonObject if (file_exists($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) - { - $nbphoto++; - $photo = $file; + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) + { + $nbphoto++; + $photo = $file; - // On determine nom du fichier vignette - $photo_vignette = ''; - if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) - { - $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; - } + // On determine nom du fichier vignette + $photo_vignette = ''; + if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) + { + $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0]; + } - // Objet - $obj = array(); - $obj['photo'] = $photo; - if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; - else $obj['photo_vignette'] = ""; + // Objet + $obj = array(); + $obj['photo'] = $photo; + if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + else $obj['photo_vignette'] = ""; - $tabobj[$nbphoto - 1] = $obj; + $tabobj[$nbphoto - 1] = $obj; - // On continue ou on arrete de boucler - if ($nbmax && $nbphoto >= $nbmax) break; - } - } + // On continue ou on arrete de boucler + if ($nbmax && $nbphoto >= $nbmax) break; + } + } - closedir($handle); - } + closedir($handle); + } } return $tabobj; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Efface la photo de la categorie et sa vignette * @@ -1759,10 +1762,10 @@ class Categorie extends CommonObject */ public function delete_photo($file) { - // phpcs:enable - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + // phpcs:enable + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine + $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier @@ -1780,7 +1783,7 @@ class Categorie extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load size of image file * @@ -1789,7 +1792,7 @@ class Categorie extends CommonObject */ public function get_image_size($file) { - // phpcs:enable + // phpcs:enable $infoImg = getimagesize($file); // Recuperation des infos de l'image $this->imgWidth = $infoImg[0]; // Largeur de l'image $this->imgHeight = $infoImg[1]; // Hauteur de l'image @@ -1804,63 +1807,63 @@ class Categorie extends CommonObject */ public function setMultiLangs($user) { - global $langs; + global $langs; - $langs_available = $langs->get_available_languages(); - $current_lang = $langs->getDefaultLang(); + $langs_available = $langs->get_available_languages(); + $current_lang = $langs->getDefaultLang(); - foreach ($langs_available as $key => $value) - { - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; - $sql .= " WHERE fk_category=".$this->id; - $sql .= " AND lang='".$key."'"; + foreach ($langs_available as $key => $value) + { + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; + $sql .= " WHERE fk_category=".$this->id; + $sql .= " AND lang='".$key."'"; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($key == $current_lang) - { - if ($this->db->num_rows($result)) // si aucune ligne dans la base - { - $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; - $sql2 .= " SET label='".$this->db->escape($this->label)."',"; - $sql2 .= " description='".$this->db->escape($this->description)."'"; - $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; - } else { - $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; - $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->label); - $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; - } - dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); - if (!$this->db->query($sql2)) - { - $this->error = $this->db->lasterror(); - return -1; - } - } elseif (isset($this->multilangs["$key"])) - { - if ($this->db->num_rows($result)) // si aucune ligne dans la base - { - $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; - $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; - $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; - $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; - } else { - $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; - $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->multilangs["$key"]["label"]); - $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; - } + if ($key == $current_lang) + { + if ($this->db->num_rows($result)) // si aucune ligne dans la base + { + $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; + $sql2 .= " SET label='".$this->db->escape($this->label)."',"; + $sql2 .= " description='".$this->db->escape($this->description)."'"; + $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; + } else { + $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; + $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->label); + $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; + } + dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); + if (!$this->db->query($sql2)) + { + $this->error = $this->db->lasterror(); + return -1; + } + } elseif (isset($this->multilangs["$key"])) + { + if ($this->db->num_rows($result)) // si aucune ligne dans la base + { + $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang"; + $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',"; + $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'"; + $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'"; + } else { + $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)"; + $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->multilangs["$key"]["label"]); + $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; + } - // on ne sauvegarde pas des champs vides - 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; - } - } - } + // on ne sauvegarde pas des champs vides + 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; + } + } + } // Call trigger $result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user); @@ -1870,7 +1873,7 @@ class Categorie extends CommonObject } // End call triggers - return 1; + return 1; } /** @@ -1880,33 +1883,33 @@ class Categorie extends CommonObject */ public function getMultiLangs() { - global $langs; + global $langs; - $current_lang = $langs->getDefaultLang(); + $current_lang = $langs->getDefaultLang(); - $sql = "SELECT lang, label, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; - $sql .= " WHERE fk_category=".$this->id; + $sql = "SELECT lang, label, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang"; + $sql .= " WHERE fk_category=".$this->id; - $result = $this->db->query($sql); - if ($result) - { - while ($obj = $this->db->fetch_object($result)) - { - //print 'lang='.$obj->lang.' current='.$current_lang.'
'; - 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->multilangs["$obj->lang"]["label"] = $obj->label; - $this->multilangs["$obj->lang"]["description"] = $obj->description; - } - return 1; - } else { - $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql; - return -1; - } + $result = $this->db->query($sql); + if ($result) + { + while ($obj = $this->db->fetch_object($result)) + { + //print 'lang='.$obj->lang.' current='.$current_lang.'
'; + 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->multilangs["$obj->lang"]["label"] = $obj->label; + $this->multilangs["$obj->lang"]["description"] = $obj->description; + } + return 1; + } else { + $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql; + return -1; + } } /** @@ -1917,47 +1920,47 @@ class Categorie extends CommonObject */ public function getLibStatut($mode) { - return ''; + return ''; } - /** - * 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() - { - dol_syslog(get_class($this)."::initAsSpecimen"); + /** + * 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() + { + dol_syslog(get_class($this)."::initAsSpecimen"); - // Initialise parametres - $this->id = 0; - $this->fk_parent = 0; - $this->label = 'SPECIMEN'; - $this->specimen = 1; - $this->description = 'This is a description'; - $this->socid = 1; - $this->type = self::TYPE_PRODUCT; - } + // Initialise parametres + $this->id = 0; + $this->fk_parent = 0; + $this->label = 'SPECIMEN'; + $this->specimen = 1; + $this->description = 'This is a description'; + $this->socid = 1; + $this->type = self::TYPE_PRODUCT; + } - /** - * Function used to replace a thirdparty id with another one. - * - * @param DoliDB $db Database handler - * @param int $origin_id Old thirdparty id - * @param int $dest_id New thirdparty id - * @return bool - */ - public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) - { - $tables = array( - 'categorie_societe' - ); + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old thirdparty id + * @param int $dest_id New thirdparty id + * @return bool + */ + public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) + { + $tables = array( + 'categorie_societe' + ); - return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables, 1); - } + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables, 1); + } /** * Return the addtional SQL JOIN query for filtering a list by a category diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 53a343046b7..7c8c683bf18 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -33,16 +33,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $langs->load("categories"); $id = GETPOST('id', 'int'); -$ref = GETPOST('ref'); -$type = GETPOST('type'); +$ref = GETPOST('ref', 'alphanohtml'); +$type = GETPOST('type', 'alphanohtml'); $action = (GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'edit'); $confirm = GETPOST('confirm'); $cancel = GETPOST('cancel', 'alpha'); $socid = GETPOST('socid', 'int'); -$label = GETPOST('label'); -$description = GETPOST('description'); -$color = GETPOST('color', 'alpha'); +$label = GETPOST('label', 'alphanohtml'); +$description = GETPOST('description', 'restricthtml'); +$color = preg_replace('/[^0-9a-f#]/i', '', GETPOST('color', 'alphanohtml')); $visible = GETPOST('visible'); $parent = GETPOST('parent'); diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index ccdd8be58b9..35420759ded 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -39,6 +39,7 @@ if (!$user->rights->categorie->lire) accessforbidden(); $id = GETPOST('id', 'int'); $type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); $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 @@ -50,6 +51,8 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar $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'); @@ -64,70 +67,69 @@ $arrayofcss = array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.css llxHeader('', $title, '', '', 0, 0, $arrayofjs, $arrayofcss); - $newcardbutton = ''; if (!empty($user->rights->categorie->creer)) { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewCategory'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/categories/card.php?action=create&type='.$type.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?type='.$type)); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewCategory'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/categories/card.php?action=create&type='.$type.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?type='.$type.$moreparam).$moreparam); } print load_fiche_titre($title, $newcardbutton, 'object_category'); -print '
'; +// Search categories +if (empty($nosearch)) { + print '
'; -/* - * Zone recherche produit/service - */ -print '
'; -print ''; -print ''; + print ''; + print ''; + print ''; + print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print '
'.$langs->trans("Search").'
'; -print $langs->trans("Name").':
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Search").'
'; + print $langs->trans("Name").':
'; -print '
'; + print '
'; -/* - * Categories found - */ -if ($catname || $id > 0) -{ - $cats = $categstatic->rechercher($id, $catname, $typetext); - - print ''; - print ''; - - foreach ($cats as $cat) + /* + * Categories found + */ + if ($catname || $id > 0) { - print "\t".''."\n"; - print "\t\t\n"; - print "\t\t\n"; - print "\t\n"; - } - print "
'.$langs->trans("FoundCats").'
"; - $categstatic->id = $cat->id; - $categstatic->ref = $cat->label; - $categstatic->label = $cat->label; - $categstatic->type = $cat->type; - $categstatic->color = $cat->color; - print 'color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'; - print $categstatic->getNomUrl(1, ''); - print ''; - print ""; - print dolGetFirstLineOfText($cat->description); - print "
"; -} else print ' '; + $cats = $categstatic->rechercher($id, $catname, $typetext); + print ''; + print ''; -print ''; + foreach ($cats as $cat) + { + print "\t".''."\n"; + print "\t\t\n"; + print "\t\t\n"; + print "\t\n"; + } + print "
'.$langs->trans("FoundCats").'
"; + $categstatic->id = $cat->id; + $categstatic->ref = $cat->label; + $categstatic->label = $cat->label; + $categstatic->type = $cat->type; + $categstatic->color = $cat->color; + print 'color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'; + print $categstatic->getNomUrl(1, ''); + print ''; + print ""; + print dolGetFirstLineOfText($cat->description); + print "
"; + } else print ' '; + + print '
'; +} print '

'; @@ -156,7 +158,7 @@ foreach ($fulltree as $key => $val) $categstatic->ref = $val['label']; $categstatic->color = $val['color']; $categstatic->type = $type; - $li = $categstatic->getNomUrl(1, '', 60); + $li = $categstatic->getNomUrl(1, '', 60, $moreparam.'&backtolist='.urlencode($_SERVER["PHP_SELF"].'?type='.$type.$moreparam)); $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; @@ -172,7 +174,7 @@ foreach ($fulltree as $key => $val) 'rowid'=>$val['rowid'], 'fk_menu'=>$val['fk_parent'], 'entry'=>''.$counter. - '
color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'.$li.''.img_view().'
' + ''.img_view().'' ); } diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index e8b3da0a525..866a98fd816 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -44,8 +44,8 @@ $confirm = GETPOST('confirm'); if ($id == '' && $label == '') { - dol_print_error('', 'Missing parameter id'); - exit(); + dol_print_error('', 'Missing parameter id'); + exit(); } // Security check @@ -70,34 +70,34 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar 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])) - { - 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]); - } - } - } + 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])) + { + 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]); + } + } + } - if (!empty($file['tmp_name'])) { - $object->add_photo($upload_dir, $file); - } - } + if (!empty($file['tmp_name'])) { + $object->add_photo($upload_dir, $file); + } + } } if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) { - $object->delete_photo($upload_dir."/".$_GET["file"]); + $object->delete_photo($upload_dir."/".$_GET["file"]); } if ($action == 'addthumb' && $_GET["file"]) { - $object->addThumbs($upload_dir."/".$_GET["file"]); + $object->addThumbs($upload_dir."/".$_GET["file"]); } @@ -126,7 +126,7 @@ if ($object->id) $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -137,7 +137,7 @@ if ($object->id) */ 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); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); } print '
'; @@ -159,7 +159,7 @@ if ($object->id) print ''; print "\n"; - print '
'; + print '
'; dol_fiche_end(); @@ -213,62 +213,62 @@ if ($object->id) if (is_array($listofphoto) && count($listofphoto)) { - print '
'; - print ''; + print '
'; + print '
'; - foreach ($listofphoto as $key => $obj) - { - $nbphoto++; + foreach ($listofphoto as $key => $obj) + { + $nbphoto++; - if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print ''; - if ($nbbyrow) print ''; + if ($nbbyrow) print ''; - if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) 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)) + { + print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; + } + if ($user->rights->categorie->creer) + { + print ''; + print img_delete().''; + } + if ($nbbyrow) print ''; + if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; + } - // Ferme tableau - while ($nbphoto % $nbbyrow) - { - print ''; - $nbphoto++; - } + // Ferme tableau + while ($nbphoto % $nbbyrow) + { + print ''; + $nbphoto++; + } - print '
'; + if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '
'; - print ''; + print ''; - // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine - if ($obj['photo_vignette']) - { - $filename = $obj['photo_vignette']; - } else { - $filename = $obj['photo']; - } + // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine + if ($obj['photo_vignette']) + { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } - // Nom affiche - $viewfilename = $obj['photo']; + // Nom affiche + $viewfilename = $obj['photo']; - // Taille de l'image - $object->get_image_size($dir.$filename); - $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; - $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; + // Taille de l'image + $object->get_image_size($dir.$filename); + $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; + $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; - print ''; + print ''; - print ''; - print '
'.$viewfilename; - print '
'; + print ''; + print '
'.$viewfilename; + 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)) - { - print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; - } - if ($user->rights->categorie->creer) - { - print ''; - print img_delete().''; - } - if ($nbbyrow) print '
  
'; + print ''; } if ($nbphoto < 1) @@ -277,7 +277,7 @@ if ($object->id) } } } else { - print $langs->trans("ErrorUnknown"); + print $langs->trans("ErrorUnknown"); } // End of page diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index a8f3510c31b..f4e073c4e1c 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -37,7 +37,7 @@ $langs->loadLangs(array('categories', 'languages')); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $type = GETPOST('type', 'aZ09'); @@ -83,43 +83,43 @@ $cancel != $langs->trans("Cancel") && $current_lang = $langs->getDefaultLang(); // check parameters - $forcelangprod = GETPOST('forcelangprod', 'alpha'); - $libelle = GETPOST('libelle', 'alpha'); - $desc = GETPOST('desc', 'none'); + $forcelangprod = GETPOST('forcelangprod', 'alpha'); + $libelle = GETPOST('libelle', 'alpha'); + $desc = GETPOST('desc', 'restricthtml'); - if (empty($forcelangprod)) { - $error++; - $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); - } + if (empty($forcelangprod)) { + $error++; + $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); + } - if (!$error) { - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (!$error) { + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } - if (!$error) { - // update de l'objet - if ($forcelangprod == $current_lang) { - $object->label = $libelle; - $object->description = dol_htmlcleanlastbr($desc); - } else { - $object->multilangs[$forcelangprod]["label"] = $libelle; - $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); - } + if (!$error) { + // update de l'objet + if ($forcelangprod == $current_lang) { + $object->label = $libelle; + $object->description = dol_htmlcleanlastbr($desc); + } else { + $object->multilangs[$forcelangprod]["label"] = $libelle; + $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); + } - // sauvegarde en base - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } - } + // sauvegarde en base + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } + } - if ($error) { - $action = 'add'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'add'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } // Validation de l'edition @@ -132,13 +132,13 @@ $cancel != $langs->trans("Cancel") && foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet { - $libelle = GETPOST('libelle-'.$key, 'alpha'); - $desc = GETPOST('desc-'.$key); + $libelle = GETPOST('libelle-'.$key, 'alpha'); + $desc = GETPOST('desc-'.$key); - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } if ($key == $current_lang) { $object->label = $libelle; @@ -149,17 +149,17 @@ $cancel != $langs->trans("Cancel") && } } - if (!$error) { - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } + if (!$error) { + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } - if ($error) { - $action = 'edit'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'edit'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } @@ -181,10 +181,10 @@ $head = categories_prepare_head($object, $type); $cnt_trans = 0; if (!empty($object->multilangs)) { - foreach ($object->multilangs as $key => $value) - { - $cnt_trans++; - } + foreach ($object->multilangs as $key => $value) + { + $cnt_trans++; + } } dol_fiche_head($head, 'translation', $langs->trans($title), -1, 'category'); @@ -195,7 +195,7 @@ $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -238,11 +238,11 @@ 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 ($user->rights->produit->creer || $user->rights->service->creer) + { + print ''.$langs->trans('Add').''; + if ($cnt_trans > 0) print ''.$langs->trans('Update').''; + } } print "\n
\n"; @@ -258,20 +258,20 @@ if ($action == 'edit') print ''; print ''; print ''; - print ''; + print ''; if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - print "
".$langs->trans('Language_'.$key)." :
"; + print "
".$langs->trans('Language_'.$key)." :
"; print ''; // Label - $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); + $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); print ''; // Desc - $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); + $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); print ''; // Date start - print ''; - // Date end - print ''; // Location @@ -1413,7 +1598,7 @@ if ($id > 0) print '


'; - print '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; $doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); @@ -293,20 +293,20 @@ if ($action == 'edit') print ''; } elseif ($action != 'add') { - if ($cnt_trans) print '
'; + if ($cnt_trans) print '
'; - if (!empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s = picto_from_langcode($key); + $s = picto_from_langcode($key); print ''; - print ''; + print ''; print ''; print ''; if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) { - print ''; + print ''; } print '
'.($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
'.($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"].'
'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
'; } @@ -329,16 +329,16 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 0e5b50085c9..30b706a4b3a 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -47,14 +47,15 @@ $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk $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') : 'myobjectlist'; // To manage different context of search +$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') + // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -265,7 +266,7 @@ if ($user->rights->categorie->creer) if ($user->rights->categorie->supprimer) { - print "".$langs->trans("Delete").""; + print "".$langs->trans("Delete").""; } print ""; @@ -316,7 +317,7 @@ print ''; $cats = $object->get_filles(); if ($cats < 0) { - dol_print_error($db, $cats->error, $cats->errors); + dol_print_error($db, $object->error, $object->errors); } elseif (count($cats) < 1) { print ''; @@ -431,7 +432,7 @@ if ($type == Categorie::TYPE_PRODUCT) $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($prods < 0) { - dol_print_error($db, $prods->error, $prods->errors); + dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; @@ -510,7 +511,7 @@ if ($type == Categorie::TYPE_SUPPLIER) $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($socs < 0) { - dol_print_error($db, $socs->error, $socs->errors); + dol_print_error($db, $object->error, $object->errors); } else { print ''; print ''; @@ -567,7 +568,7 @@ if ($type == Categorie::TYPE_CUSTOMER) $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($socs < 0) { - dol_print_error($db, $socs->error, $socs->errors); + dol_print_error($db, $object->error, $object->errors); } else { print ''; print ''; @@ -626,7 +627,7 @@ if ($type == Categorie::TYPE_MEMBER) $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($prods < 0) { - dol_print_error($db, $prods->error, $prods->errors); + dol_print_error($db, $object->error, $object->errors); } else { print ''; print ''; @@ -685,7 +686,7 @@ if ($type == Categorie::TYPE_CONTACT) $contacts = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($contacts < 0) { - dol_print_error($db, $contacts->error, $contacts->errors); + dol_print_error($db, $object->error, $object->errors); } else { print ''; print ''; @@ -747,7 +748,7 @@ if ($type == Categorie::TYPE_ACCOUNT) $accounts = $object->getObjectsInCateg($type, 0, $limit, $offset); if ($accounts < 0) { - dol_print_error($db, $accounts->error, $accounts->errors); + dol_print_error($db, $object->error, $object->errors); } else { print ''; print ''; @@ -876,12 +877,14 @@ if ($type == Categorie::TYPE_USER) print ''; print '
'; - $param = '&limit='.$limit.'&id='.$id.'&type='.$type; $num = count($objects); $nbtotalofrecords = ''; $newcardbutton = ''; - print_barre_liste($langs->trans("Users"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'user', 0, $newcardbutton, '', $limit); + $param = '&limit='.$limit.'&id='.$id.'&type='.$type; + $num = count($users); + + print_barre_liste($langs->trans("Users"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, '', 'user', 0, '', '', $limit); print "
'.$langs->trans('Translation').''; - print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); + print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); print '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; - $doleditor = new DolEditor('desc', GETPOST('desc', 'none'), '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor('desc', GETPOST('desc', 'restricthtml'), '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); print '
\n"; - print ''."\n"; + print ''."\n"; if (count($users) > 0) { @@ -915,7 +918,7 @@ if ($type == Categorie::TYPE_USER) } -// List of Project +// List of warehouses if ($type == Categorie::TYPE_WAREHOUSE) { $permission = $user->rights->stock->creer; diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 0c457fb6f47..7353ea881ee 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -39,7 +39,7 @@ $error = 0; $website = GETPOST('website', 'alpha'); $page = GETPOST('page', 'alpha'); $pageid = GETPOST('pageid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if (GETPOST('delete')) { $action = 'delete'; } if (GETPOST('preview')) $action = 'preview'; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 72ffd2b6bba..3c8ed94c2bf 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -37,6 +37,7 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -47,9 +48,9 @@ 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("companies", "other", "commercial", "bills", "orders", "agenda")); +$langs->loadLangs(array("companies", "other", "commercial", "bills", "orders", "agenda", "mails")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $socpeopleassigned = GETPOST('socpeopleassigned', 'array'); @@ -57,15 +58,23 @@ $origin = GETPOST('origin', 'alpha'); $originid = GETPOST('originid', 'int'); $confirm = GETPOST('confirm', 'alpha'); -$fulldayevent = GETPOST('fullday'); +$fulldayevent = GETPOST('fullday', 'alpha'); -$aphour = GETPOST('aphour'); -$apmin = GETPOST('apmin'); -$p2hour = GETPOST('p2hour'); -$p2min = GETPOST('p2min'); +$aphour = GETPOST('aphour', 'int'); +$apmin = GETPOST('apmin', 'int'); +$p2hour = GETPOST('p2hour', 'int'); +$p2min = GETPOST('p2min', 'int'); -$datep = dol_mktime($fulldayevent ? '00' : $aphour, $fulldayevent ? '00' : $apmin, 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); -$datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2min, $fulldayevent ? '59' : '0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); +$addreminder = GETPOST('addreminder', 'alpha'); +$offsetvalue = GETPOST('offsetvalue', 'int'); +$offsetunit = GETPOST('offsetunittype_duration', 'aZ09'); +$remindertype = GETPOST('selectremindertype', 'aZ09'); +$modelmail = GETPOST('actioncommsendmodel_mail', 'int'); + +//var_dump($_POST); exit; + +$datep = dol_mktime($fulldayevent ? '00' : $aphour, $fulldayevent ? '00' : $apmin, 0, GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int')); +$datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2min, $fulldayevent ? '59' : '0', GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int')); // Security check $socid = GETPOST('socid', 'int'); @@ -111,6 +120,12 @@ $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'); +$TRemindTypes = array(); +if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) $TRemindTypes['email'] = $langs->trans('EMail'); +if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) $TRemindTypes['browser'] = $langs->trans('BrowserPush'); + +$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')); + /* * Actions @@ -248,10 +263,10 @@ if (empty($reshook) && $action == 'add') if (!$error) { // Initialisation objet actioncomm - $object->priority = GETPOST("priority") ?GETPOST("priority") : 0; + $object->priority = GETPOSTISSET("priority") ? GETPOST("priority", "int") : 0; $object->fulldayevent = (!empty($fulldayevent) ? 1 : 0); - $object->location = GETPOST("location"); - $object->label = trim(GETPOST('label')); + $object->location = GETPOST("location", 'alphanohtml'); + $object->label = GETPOST('label', 'alphanohtml'); $object->fk_element = GETPOST("fk_element", 'int'); $object->elementtype = GETPOST("elementtype", 'alpha'); if (!GETPOST('label')) @@ -311,7 +326,7 @@ if (empty($reshook) && $action == 'add') if (GETPOST("doneby") > 0) $object->userdoneid = GETPOST("doneby", "int"); } - $object->note_private = trim(GETPOST("note", "none")); + $object->note_private = trim(GETPOST("note", "restricthtml")); if (isset($_POST["contactid"])) $object->contact = $contact; @@ -378,7 +393,44 @@ if (empty($reshook) && $action == 'add') $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. - $db->commit(); + //Create reminders + if ($addreminder == 'on'){ + $actionCommReminder = new ActionCommReminder($db); + + $dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit); + + $actionCommReminder->dateremind = $dateremind; + $actionCommReminder->typeremind = $remindertype; + $actionCommReminder->offsetunit = $offsetunit; + $actionCommReminder->offsetvalue = $offsetvalue; + $actionCommReminder->status = $actionCommReminder::STATUS_TODO; + $actionCommReminder->fk_actioncomm = $object->id; + 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) + { + $actionCommReminder->fk_user = $userassigned['id']; + $res = $actionCommReminder->create($user); + + if ($res <= 0){ + // If error + $db->rollback(); + $langs->load("errors"); + $error = $langs->trans('ErrorReminderActionCommCreation'); + setEventMessages($error, null, 'errors'); + $action = 'create'; $donotclearsession = 1; + break; + } + } + } + + if ($error) { + $db->rollback(); + } else { + $db->commit(); + } + if (!empty($backtopage)) { dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : '')); @@ -439,7 +491,7 @@ if (empty($reshook) && $action == 'update') $object->datep = $datep; $object->datef = $datef; $object->percentage = $percentage; - $object->priority = GETPOST("priority", "alphanohtml"); + $object->priority = GETPOST("priority", "int"); $object->fulldayevent = GETPOST("fullday") ? 1 : 0; $object->location = GETPOST('location', "alphanohtml"); $object->socid = GETPOST("socid", "int"); @@ -452,7 +504,7 @@ if (empty($reshook) && $action == 'update') $object->contact_id = key($object->socpeopleassigned); } $object->fk_project = GETPOST("projectid", 'int'); - $object->note_private = trim(GETPOST("note", "none")); + $object->note_private = trim(GETPOST("note", "restricthtml")); $object->fk_element = GETPOST("fk_element", "int"); $object->elementtype = GETPOST("elementtype", "alphanohtml"); @@ -587,9 +639,51 @@ if (empty($reshook) && $action == 'update') $categories = GETPOST('categories', 'array'); $object->setCategories($categories); + $object->loadReminders(); + if (!empty($object->reminders) && $object->datep > dol_now()) + { + foreach ($object->reminders as $reminder) + { + $reminder->delete($user); + } + $object->reminders = array(); + } + + //Create reminders + if ($addreminder == 'on' && $object->datep > dol_now()){ + $actionCommReminder = new ActionCommReminder($db); + + $dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit); + + $actionCommReminder->dateremind = $dateremind; + $actionCommReminder->typeremind = $remindertype; + $actionCommReminder->offsetunit = $offsetunit; + $actionCommReminder->offsetvalue = $offsetvalue; + $actionCommReminder->status = $actionCommReminder::STATUS_TODO; + $actionCommReminder->fk_actioncomm = $object->id; + 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) + { + $actionCommReminder->fk_user = $userassigned['id']; + $res = $actionCommReminder->create($user); + + if ($res <= 0){ + // If error + $langs->load("errors"); + $error = $langs->trans('ErrorReminderActionCommCreation'); + setEventMessages($error, null, 'errors'); + $action = 'create'; $donotclearsession = 1; + break; + } + } + } + unset($_SESSION['assignedtouser']); - $db->commit(); + if (!$error) $db->commit(); + else $db->rollback(); } else { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); @@ -748,6 +842,7 @@ if (empty($reshook)) { } + /* * View */ @@ -755,6 +850,13 @@ if (empty($reshook)) { $form = new Form($db); $formproject = new FormProjets($db); +$arrayrecurrulefreq = array( + 'no'=>$langs->trans("OnceOnly"), + 'MONTHLY'=>$langs->trans("EveryMonth"), + 'WEEKLY'=>$langs->trans("EveryWeek"), + //'DAYLY'=>$langs->trans("EveryDay") +); + $help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); @@ -791,7 +893,6 @@ if ($action == 'create') $("#p2").removeAttr("disabled"); } } - setdatefields(); $("#fullday").change(function() { console.log("setdatefields"); setdatefields(); @@ -805,11 +906,25 @@ if ($action == 'create') { $("#doneby").val(-1); } - }); - $("#actioncode").change(function() { + }); + $("#actioncode").change(function() { if ($("#actioncode").val() == \'AC_RDV\') $("#dateend").addClass("fieldrequired"); else $("#dateend").removeClass("fieldrequired"); - }); + }); + $("#aphour,#apmin").change(function() { + if ($("#actioncode").val() == \'AC_RDV\') { + console.log("Start date was changed, we modify end date "+(parseInt($("#aphour").val()))+" "+$("#apmin").val()+" -> "+("00" + (parseInt($("#aphour").val()) + 1)).substr(-2,2)); + $("#p2hour").val(("00" + (parseInt($("#aphour").val()) + 1)).substr(-2,2)); + $("#p2min").val($("#apmin").val()); + $("#p2day").val($("#apday").val()); + $("#p2month").val($("#apmonth").val()); + $("#p2year").val($("#apyear").val()); + $("#p2").val($("#ap").val()); + } + }); + if ($("#actioncode").val() == \'AC_RDV\') $("#dateend").addClass("fieldrequired"); + else $("#dateend").removeClass("fieldrequired"); + setdatefields(); })'; print ''."\n"; } @@ -832,8 +947,8 @@ if ($action == 'create') if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print ''; } @@ -843,45 +958,56 @@ if ($action == 'create') // Full day print ''; - // Date start - $datep = ($datep ? $datep : $object->datep); - if (GETPOST('datep', 'int', 1)) $datep = dol_stringtotime(GETPOST('datep', 'int', 1), 0); - print ''; + print '     -     '; + //print ' - '; + if (GETPOST("afaire") == 1) { + print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend'); + } else { + print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend'); + } + print ''; // Date end - $datef = ($datef ? $datef : $object->datef); - if (GETPOST('datef', 'int', 1)) $datef = dol_stringtotime(GETPOST('datef', 'int', 1), 0); - if (empty($datef) && !empty($datep) && !empty($conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS)) - { - $datef = dol_time_plus_duree($datep, $conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS, 'h'); - } - print ''; + print ''; + print '';*/ // Dev in progress $userepeatevent = ($conf->global->MAIN_FEATURES_LEVEL == 2 ? 1 : 0); if ($userepeatevent) { // Repeat - print ''; + print ''; } // Assigned to @@ -972,7 +1098,7 @@ if ($action == 'create') }*/ print ''; - // Realised by + // Done by if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { print ''; @@ -1022,7 +1148,7 @@ if ($action == 'create') print ''; } @@ -1034,7 +1160,7 @@ if ($action == 'create') $projectid = GETPOST('projectid', 'int'); print ''; print ''; + if (! empty($conf->global->AGENDA_SUPPORT_PRIORITY_IN_EVENTS)) { + print ''; + } // Description print ''; @@ -1106,12 +1234,77 @@ if ($action == 'create') print '
'.$langs->trans("Users").' '.count($users).'
'.$langs->trans("Users").' '.$num.'
'.$langs->trans("Type").''; - $default = (empty($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT) ? '' : $conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT); - $formactions->select_type_actions(GETPOST("actioncode", 'aZ09') ?GETPOST("actioncode", 'aZ09') : ($object->type_code ? $object->type_code : $default), "actioncode", "systemauto", 0, -1); + $default = (empty($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT) ? 'AC_RDV' : $conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT); + $formactions->select_type_actions(GETPOSTISSET("actioncode") ? GETPOST("actioncode", 'aZ09') : ($object->type_code ? $object->type_code : $default), "actioncode", "systemauto", 0, -1); print '
'.$langs->trans("EventOnFullDay").'
'.$langs->trans("DateActionStart").''; + $datep = ($datep ? $datep : $object->datep); + if (GETPOST('datep', 'int', 1)) $datep = dol_stringtotime(GETPOST('datep', 'int', 1), 0); + $datef = ($datef ? $datef : $object->datef); + if (GETPOST('datef', 'int', 1)) $datef = dol_stringtotime(GETPOST('datef', 'int', 1), 0); + if (empty($datef) && !empty($datep)) + { + if (GETPOST("actioncode", 'aZ09') == 'AC_RDV' || empty($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT)) { + $datef = dol_time_plus_duree($datep, (empty($conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS) ? 1 : $conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS), 'h'); + } + } + + // Date start + print '
'; + print ''.$langs->trans("DateActionStart").''; + print ' - '; + print ''.$langs->trans("DateActionEnd").''; + print ''; if (GETPOST("afaire") == 1) { print $form->selectDate($datep, 'ap', 1, 1, 0, "action", 1, 2, 0, 'fulldaystart'); // Empty value not allowed for start date and hours if "todo" } else { print $form->selectDate($datep, 'ap', 1, 1, 1, "action", 1, 2, 0, 'fulldaystart'); } - print '
'.$langs->trans("DateActionEnd").''; + /*print '
'; + print ''.$langs->trans("DateActionEnd").''; + print ''; if (GETPOST("afaire") == 1) { print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 2, 0, 'fulldayend'); } else { print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 2, 0, 'fulldayend'); } - print '
'.$langs->trans("RepeatEvent").''; + print '
'; print ''; - $arrayrecurrulefreq = array( - 'no'=>$langs->trans("No"), - 'MONTHLY'=>$langs->trans("EveryMonth"), - 'WEEKLY'=>$langs->trans("EveryWeek"), - //'DAYLY'=>$langs->trans("EveryDay") - ); $selectedrecurrulefreq = 'no'; $selectedrecurrulebymonthday = ''; $selectedrecurrulebyday = ''; @@ -942,7 +1068,7 @@ if ($action == 'create') // Location if (empty($conf->global->AGENDA_DISABLE_LOCATION)) { - print '
'.$langs->trans("Location").'
'.$langs->trans("Location").'
'.$langs->trans("ActionDoneBy").''; @@ -1011,9 +1137,9 @@ if ($action == 'create') $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); //For external user force the company to user company if (!empty($user->socid)) { - print $form->select_company($user->socid, 'socid', '', 1, 1, 0, $events, 0, 'minwidth300'); + print img_picto('', 'company', 'class="paddingrightonly"').$form->select_company($user->socid, 'socid', '', 1, 1, 0, $events, 0, 'minwidth300'); } else { - print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth300'); + print img_picto('', 'company', 'class="paddingrightonly"').$form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth300'); } } print '
'.$langs->trans("ActionOnContact").''; $preselectedids = GETPOST('socpeopleassigned', 'array'); if (GETPOST('contactid', 'int')) $preselectedids[GETPOST('contactid', 'int')] = GETPOST('contactid', 'int'); - print $form->selectcontacts(GETPOST('socid', 'int'), $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'quatrevingtpercent', false, 0, array(), false, 'multiple', 'contactid'); + print img_picto('', 'contact', 'class="paddingrightonly"').$form->selectcontacts(GETPOST('socid', 'int'), $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'quatrevingtpercent', false, 0, array(), false, 'multiple', 'contactid'); print '
'.$langs->trans("Project").''; - + print img_picto('', 'project', 'class="paddingrightonly"'); $numproject = $formproject->select_projects((!empty($societe->id) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth500'); print ' '; @@ -1057,7 +1183,7 @@ if ($action == 'create') print '
'.$langs->trans("Task").''; - + print img_picto('', 'projecttask', 'class="paddingrightonly"'); $projectsListId = false; if (!empty($projectid)) { $projectsListId = $projectid; } $tid = GETPOST("projecttaskid") ?GETPOST("projecttaskid") : ''; @@ -1084,14 +1210,16 @@ if ($action == 'create') } // Priority - print '
'.$langs->trans("Priority").''; - print ''; - print '
'.$langs->trans("Priority").''; + print ''; + print '
'.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('note', (GETPOST('note', 'none') ? GETPOST('note', 'none') : $object->note_private), '', 180, 'dolibarr_notes', 'In', true, true, $conf->fckeditor->enabled, ROWS_4, '90%'); + $doleditor = new DolEditor('note', (GETPOSTISSET('note') ? GETPOST('note', 'restricthtml') : $object->note_private), '', 120, 'dolibarr_notes', 'In', true, true, $conf->fckeditor->enabled, ROWS_4, '90%'); $doleditor->Create(); print '
'; - dol_fiche_end(); + + if ($conf->global->AGENDA_REMINDER_EMAIL || $conf->global->AGENDA_REMINDER_BROWSER) + { + //checkbox create reminder + print '
'; + print '
'; + print '

'; + + print ''; + + print "\n".''."\n"; + } + + dol_fiche_end(); print '
'; - print ''; + print ''; print '     '; - print ''; + if (empty($backtopage)) { + print ''; + } else { + print ''; + } print '
'; print ""; @@ -1157,7 +1350,7 @@ if ($id > 0) $object->contact_id = GETPOST("contactid", 'int'); $object->fk_project = GETPOST("projectid", 'int'); - $object_private = GETPOST("note", 'none'); + $object_private = GETPOST("note", 'restricthtml'); } if ($result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) @@ -1248,7 +1441,7 @@ if ($id > 0) print '
'.$langs->trans("EventOnFullDay").'fulldayevent ? ' checked' : '').'>
'.$langs->trans("DateActionStart").''; + print '
'.$langs->trans("DateActionStart").' - '.$langs->trans("DateActionEnd").''; if (GETPOST("afaire") == 1) { print $form->selectDate($datep ? $datep : $object->datep, 'ap', 1, 1, 0, "action", 1, 1, 0, 'fulldaystart'); } elseif (GETPOST("afaire") == 2) { @@ -1256,9 +1449,7 @@ if ($id > 0) } else { print $form->selectDate($datep ? $datep : $object->datep, 'ap', 1, 1, 1, "action", 1, 1, 0, 'fulldaystart'); } - print '
'.$langs->trans("DateActionEnd").''; + print ' - '; if (GETPOST("afaire") == 1) { print $form->selectDate($datef ? $datef : $object->datef, 'p2', 1, 1, 1, "action", 1, 1, 0, 'fulldayend'); } elseif (GETPOST("afaire") == 2) { @@ -1273,14 +1464,8 @@ if ($id > 0) if ($userepeatevent) { // Repeat - print '
'.$langs->trans("RepeatEvent").''; + print '
'; print ''; - $arrayrecurrulefreq = array( - 'no'=>$langs->trans("No"), - 'MONTHLY'=>$langs->trans("EveryMonth"), - 'WEEKLY'=>$langs->trans("EveryWeek"), - //'DAYLY'=>$langs->trans("EveryDay"), - ); $selectedrecurrulefreq = 'no'; $selectedrecurrulebymonthday = ''; $selectedrecurrulebyday = ''; @@ -1328,7 +1513,7 @@ if ($id > 0) // Status print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; $percent = GETPOST("percentage") ? GETPOST("percentage") : $object->percentage; - $formactions->form_select_status_action('formaction', $percent, 1); + $formactions->form_select_status_action('formaction', $percent, 1, 'complete', 0, 0, 'maxwidth200'); print '
'; + print '
'; if ($conf->societe->enabled) { @@ -1425,14 +1610,14 @@ if ($id > 0) $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); // TODO Refresh also list of project if $conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY not defined with list linked to socid ? // FIXME If we change company, we may get a project that does not match - print $form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth200'); + print img_picto('', 'company', 'class="paddingrightonly"').$form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth200'); print ''; print ''; // related contact print ''; print ''; @@ -1444,6 +1629,7 @@ if ($id > 0) $langs->load("projects"); print ''; + if (! empty($conf->global->AGENDA_SUPPORT_PRIORITY_IN_EVENTS)) { + print ''; + } // Object linked if (!empty($object->fk_element) && !empty($object->elementtype)) @@ -1518,6 +1706,86 @@ if ($id > 0) print '
'.$langs->trans("ActionOnContact").''; print '
'; - print $form->selectcontacts($object->socid, array_keys($object->socpeopleassigned), 'socpeopleassigned[]', 1, '', '', 1, 'quatrevingtpercent', false, 0, 0, array(), 'multiple', 'contactid'); + print img_picto('', 'contact', 'class="paddingrightonly"').$form->selectcontacts($object->socid, array_keys($object->socpeopleassigned), 'socpeopleassigned[]', 1, '', '', 1, 'quatrevingtpercent', false, 0, 0, array(), 'multiple', 'contactid'); print '
'; print '
'.$langs->trans("Project").''; + print img_picto('', 'project', 'class="paddingrightonly"'); $numprojet = $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, 'maxwidth500'); if ($numprojet == 0) { @@ -1453,9 +1639,11 @@ if ($id > 0) } // Priority - print '
'.$langs->trans("Priority").''; - print ''; - print '
'.$langs->trans("Priority").''; + print ''; + print '
'; + // Reminders + if ($conf->global->AGENDA_REMINDER_EMAIL || $conf->global->AGENDA_REMINDER_BROWSER) + { + $filteruserid = $user->id; + if ($user->rights->agenda->allactions->read) $filteruserid = 0; + $object->loadReminders('', $filteruserid, false); + + print '
'; + + if (count($object->reminders) > 0) { + $checked = 'checked'; + $keys = array_keys($object->reminders); + $firstreminderId = array_shift($keys); + + $actionCommReminder = $object->reminders[$firstreminderId]; + } else { + $checked = ''; + $actionCommReminder = new ActionCommReminder($db); + $actionCommReminder->offsetvalue = 10; + $actionCommReminder->offsetunit = 'i'; + $actionCommReminder->typeremind = 'email'; + } + + print ''.$langs->trans("AddReminder").''; + + print '
'; + + print ''; + + //Reminder + print ''; + + //Time Type + print ''; + + //Reminder Type + $TRemindTypes = array(); + if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) $TRemindTypes['email'] = $langs->trans('EMail'); + if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) $TRemindTypes['browser'] = $langs->trans('BrowserPush'); + print ''; + + $hide = ''; + if ($actionCommReminder->typeremind == 'browser') $hide = 'style="display:none;"'; + + //Mail Model + print ''; + + print '
'.$langs->trans("ReminderTime").''; + print ''; + print '
'.$langs->trans("TimeType").''; + print $form->selectTypeDuration('offsetunit', $actionCommReminder->offsetunit); + print '
'.$langs->trans("ReminderType").''; + print $form->selectarray('selectremindertype', $TRemindTypes, $actionCommReminder->typeremind); + print '
'.$langs->trans("EMailTemplates").''; + print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1); + print '
'; + + print "\n".''."\n"; + } + dol_fiche_end(); print '
'; @@ -1607,6 +1875,7 @@ if ($id > 0) dol_banner_tab($object, 'id', $linkback, ($user->socid ? 0 : 1), 'id', 'ref', $morehtmlref); print '
'; + print '
'; print '
'; @@ -1616,17 +1885,17 @@ if ($id > 0) // Type if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - print ''.$langs->trans("Type").''.$langs->trans($object->type).''; + print ''.$langs->trans("Type").''.$langs->trans($object->type).''; } // Full day event - print ''.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).''; + print ''.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).''; $rowspan = 4; if (empty($conf->global->AGENDA_DISABLE_LOCATION)) $rowspan++; // Date start - print ''.$langs->trans("DateActionStart").''; + print ''.$langs->trans("DateActionStart").''; if (!$object->fulldayevent) print dol_print_date($object->datep, 'dayhour'); else print dol_print_date($object->datep, 'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); @@ -1634,7 +1903,7 @@ if ($id > 0) print ''; // Date end - print ''.$langs->trans("DateActionEnd").''; + print ''.$langs->trans("DateActionEnd").''; if (!$object->fulldayevent) print dol_print_date($object->datef, 'dayhour'); else print dol_print_date($object->datef, 'day'); if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now - $delay_warning)) print img_warning($langs->trans("Late")); @@ -1643,11 +1912,11 @@ if ($id > 0) // Location if (empty($conf->global->AGENDA_DISABLE_LOCATION)) { - print ''.$langs->trans("Location").''.$object->location.''; + print ''.$langs->trans("Location").''.$object->location.''; } // Assigned to - print ''.$langs->trans("ActionAssignedTo").''; + print ''.$langs->trans("ActionAssignedTo").''; $listofuserid = array(); if (empty($donotclearsession)) { @@ -1697,7 +1966,7 @@ if ($id > 0) // Done by if ($conf->global->AGENDA_ENABLE_DONEBY) { - print ''.$langs->trans("ActionDoneBy").''; + print ''.$langs->trans("ActionDoneBy").''; if ($object->userdoneid > 0) { $tmpuser = new User($db); @@ -1706,16 +1975,19 @@ if ($id > 0) } print ''; } + // Categories if ($conf->categorie->enabled) { - print ''.$langs->trans("Categories").''; + print ''.$langs->trans("Categories").''; print $form->showCategories($object->id, Categorie::TYPE_ACTIONCOMM, 1); print ""; } print ''; - print '
'; + print '
'; + + print '
'; print '
'; print ''; @@ -1723,7 +1995,7 @@ if ($id > 0) if ($conf->societe->enabled) { // Related company - print ''; - print ''; @@ -1774,24 +2046,60 @@ if ($id > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print ''; $link = dolGetElementUrl($object->fk_element, $object->elementtype, 1); - print ''; } // Description - print ''; // Other attributes - $cols = 3; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Reminders + if ($conf->global->AGENDA_REMINDER_EMAIL || $conf->global->AGENDA_REMINDER_BROWSER) + { + $filtreuserid = $user->id; + if ($user->rights->agenda->allactions->read) $filtreuserid = 0; + $object->loadReminders('', $filteruserid, false); + + print ''; + } + print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : (''.$langs->trans("None").'')); + print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : (''.$langs->trans("None").'')); if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { if ($object->thirdparty->fetch($object->thirdparty->id)) @@ -1735,7 +2007,7 @@ if ($id > 0) // Related contact print '
'.$langs->trans("ActionOnContact").''; + print ''; if (!empty($object->socpeopleassigned)) { @@ -1763,7 +2035,7 @@ if ($id > 0) } // Priority - print '
'.$langs->trans("Priority").''; + print '
'.$langs->trans("Priority").''; print ($object->priority ? $object->priority : ''); print '
'.$langs->trans("LinkedObject").''; + print ''; if (empty($link)) print ''.$langs->trans("ObjectDeleted").''; else print $link; print '
'.$langs->trans("Description").''; + print '
'.$langs->trans("Description").''; print dol_string_onlythesehtmltags(dol_htmlentitiesbr($object->note_private)); print '
'.$langs->trans("Reminders").''; + + if (count($object->reminders) > 0) { + $tmpuserstatic = new User($db); + + foreach ($object->reminders as $actioncommreminderid => $actioncommreminder) { + print $TRemindTypes[$actioncommreminder->typeremind]; + if ($actioncommreminder->fk_user > 0) { + $tmpuserstatic->fetch($actioncommreminder->fk_user); + print ' ('.$tmpuserstatic->getNomUrl(0, '', 0, 0, 16).')'; + } + print ' - '.$actioncommreminder->offsetvalue.' '.$TDurationTypes[$actioncommreminder->offsetunit]; + if ($actioncommreminder->status == $actioncommreminder::STATUS_TODO) { + print ' - '; + print $langs->trans("NotSent"); + print ' '; + } elseif ($actioncommreminder->status == $actioncommreminder::STATUS_DONE) { + print ' - '; + print $langs->trans("Done"); + print ' '; + } + print '
'; + } + } + + print '
'; print '
'; + print '
'; + print '
'; dol_fiche_end(); } @@ -1828,7 +2136,7 @@ if ($id > 0) if ($user->rights->agenda->allactions->delete || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->delete)) { - print ''; + print ''; } else { print ''; } diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 4fb80592adf..97896448a3f 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -28,6 +28,9 @@ */ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php'; /** @@ -35,307 +38,311 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class ActionComm extends CommonObject { - /** - * @var string ID to identify managed object - */ - public $element = 'action'; + /** + * @var string ID to identify managed object + */ + public $element = 'action'; - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'actioncomm'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'actioncomm'; - /** - * @var string Name of id column - */ - public $table_rowid = 'id'; + /** + * @var string Name of id column + */ + public $table_rowid = 'id'; - /** - * @var string Name of icon for actioncomm object. Filename of icon is object_action.png - */ - public $picto = 'action'; + /** + * @var string Name of icon for actioncomm object. Filename of icon is object_action.png + */ + public $picto = 'action'; - /** - * @var int 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - */ - public $ismultientitymanaged = 1; + /** + * @var int 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 1; - /** - * @var integer 0=Default - * 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user - * 2=Same than 1 but accept record if fksoc is empty - */ - public $restrictiononfksoc = 2; + /** + * @var integer 0=Default + * 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user + * 2=Same than 1 but accept record if fksoc is empty + */ + public $restrictiononfksoc = 2; - /** - * @var int Id of the event - */ - public $id; + /** + * @var int Id of the event + */ + public $id; - /** - * @var int Id of the event. Use $id as possible - */ - public $ref; + /** + * @var int Id of the event. Use $id as possible + */ + public $ref; - /** - * @var int Id into parent table llx_c_actioncomm (used only if option to use type is set) - */ - public $type_id; + /** + * @var int Id into parent table llx_c_actioncomm (used only if option to use type is set) + */ + public $type_id; - /** - * @var string Code into parent table llx_c_actioncomm (used only if option to use type is set). With default setup, should be AC_OTH_AUTO or AC_OTH. - */ - public $type_code; + /** + * @var string Code into parent table llx_c_actioncomm (used only if option to use type is set). With default setup, should be AC_OTH_AUTO or AC_OTH. + */ + public $type_code; - /** - * @var string Type label - */ - public $type_label; + /** + * @var string Type label + */ + public $type_label; - /** - * @var string Label into parent table llx_c_actioncomm (used only if option to use type is set) - */ - public $type; + /** + * @var string Label into parent table llx_c_actioncomm (used only if option to use type is set) + */ + public $type; - /** - * @var string Color into parent table llx_c_actioncomm (used only if option to use type is set) - */ - public $type_color; + /** + * @var string Color into parent table llx_c_actioncomm (used only if option to use type is set) + */ + public $type_color; - /** - * @var string Free code to identify action. Ie: Agenda trigger add here AC_TRIGGERNAME ('AC_COMPANY_CREATE', 'AC_PROPAL_VALIDATE', ...) - */ - public $code; + /** + * @var string Free code to identify action. Ie: Agenda trigger add here AC_TRIGGERNAME ('AC_COMPANY_CREATE', 'AC_PROPAL_VALIDATE', ...) + */ + public $code; - /** - * @var string Agenda event label - */ - public $label; + /** + * @var string Agenda event label + */ + public $label; - /** - * @var integer Date creation record (datec) - */ - public $datec; + /** + * @var integer Date creation record (datec) + */ + public $datec; - /** - * @var integer Date end record (datef) - */ - public $datef; + /** + * @var integer Date end record (datef) + */ + public $datef; - /** - * @var integer Duration (duree) - */ - public $duree; + /** + * @var integer Duration (duree) + */ + public $duree; - /** - * @var integer Date modification record (tms) - */ - public $datem; + /** + * @var integer Date modification record (tms) + */ + public $datem; - /** - * @var User Object user that create action - * @deprecated - * @see $authorid - */ - public $author; + /** + * @var User Object user that create action + * @deprecated + * @see $authorid + */ + public $author; - /** - * @var User Object user that modified action - * @deprecated - * @see $usermodid - */ - public $usermod; + /** + * @var User Object user that modified action + * @deprecated + * @see $usermodid + */ + public $usermod; - /** - * @var int Id user that create action - */ - public $authorid; + /** + * @var int Id user that create action + */ + public $authorid; - /** - * @var int Id user that modified action - */ - public $usermodid; + /** + * @var int Id user that modified action + */ + public $usermodid; - /** - * @var integer Date action start (datep) - */ - public $datep; + /** + * @var integer Date action start (datep) + */ + public $datep; - /** - * @var integer Date action end (datep2) - */ - public $datep2; + /** + * @var integer Date action end (datep2) + */ + public $datep2; - /** - * @var int -1=Unkown duration - * @deprecated - */ - public $durationp = -1; + /** + * @var int -1=Unkown duration + * @deprecated + */ + public $durationp = -1; - /** - * @var int 1=Event on full day - */ - public $fulldayevent = 0; + /** + * @var int 1=Event on full day + */ + public $fulldayevent = 0; - /** - * @var integer Percentage - */ - public $percentage; + /** + * @var integer Percentage + */ + public $percentage; - /** - * @var string Location - */ - public $location; + /** + * @var string Location + */ + public $location; - /** - * @var int Transparency (ical standard). Used to say if people assigned to event are busy or not by event. 0=available, 1=busy, 2=busy (refused events) - */ - public $transparency; + /** + * @var int Transparency (ical standard). Used to say if people assigned to event are busy or not by event. 0=available, 1=busy, 2=busy (refused events) + */ + public $transparency; - /** - * @var int (0 By default) - */ - public $priority; + /** + * @var int (0 By default) + */ + public $priority; - /** - * @var int[] Array of user ids - */ - public $userassigned = array(); + /** + * @var int[] Array of user ids + */ + public $userassigned = array(); - /** - * @var int Id of user owner = fk_user_action into table - */ - public $userownerid; + /** + * @var int Id of user owner = fk_user_action into table + */ + public $userownerid; - /** - * @var int Id of user done (deprecated) - * @deprecated - */ - public $userdoneid; + /** + * @var int Id of user done (deprecated) + * @deprecated + */ + public $userdoneid; - /** - * @var int[] Array of contact ids - */ - public $socpeopleassigned = array(); + /** + * @var int[] Array of contact ids + */ + public $socpeopleassigned = array(); - /** - * @var int[] Array of other contact emails (not user, not contact) - */ - public $otherassigned = array(); + /** + * @var int[] Array of other contact emails (not user, not contact) + */ + public $otherassigned = array(); + /** + * @var array Array of reminders + */ + public $reminders = array(); - /** - * @var User Object user of owner - * @deprecated - * @see $userownerid - */ - public $usertodo; + /** + * @var User Object user of owner + * @deprecated + * @see $userownerid + */ + public $usertodo; - /** - * @var User Object user that did action - * @deprecated - * @see $userdoneid - */ - public $userdone; + /** + * @var User Object user that did action + * @deprecated + * @see $userdoneid + */ + public $userdone; - /** - * @var int thirdparty id linked to action - */ - public $socid; + /** + * @var int thirdparty id linked to action + */ + public $socid; - /** - * @var int socpeople id linked to action - */ - public $contactid; + /** + * @var int socpeople id linked to action + */ + public $contactid; - /** - * @var Societe|null Company linked to action (optional) - * @deprecated - * @see $socid - */ - public $societe; + /** + * @var Societe|null Company linked to action (optional) + * @deprecated + * @see $socid + */ + public $societe; - /** - * @var Contact|null Contact linked to action (optional) - * @deprecated - * @see $contactid - */ - public $contact; + /** + * @var Contact|null Contact linked to action (optional) + * @deprecated + * @see $contactid + */ + public $contact; - // Properties for links to other objects - /** - * @var int Id of linked object - */ - public $fk_element; // Id of record + // Properties for links to other objects + /** + * @var int Id of linked object + */ + public $fk_element; // Id of record - /** - * @var int Id of record alternative for API - */ - public $elementid; + /** + * @var int Id of record alternative for API + */ + public $elementid; - /** - * @var string Type of record. This if property ->element of object linked to. - */ - public $elementtype; + /** + * @var string Type of record. This if property ->element of object linked to. + */ + public $elementtype; - /** - * @var string Ical name - */ - public $icalname; + /** + * @var string Ical name + */ + public $icalname; - /** - * @var string Ical color - */ - public $icalcolor; + /** + * @var string Ical color + */ + public $icalcolor; - /** - * @var string Extraparam - */ - public $extraparams; + /** + * @var string Extraparam + */ + public $extraparams; - /** - * @var array Actions - */ - public $actions = array(); + /** + * @var array Actions + */ + public $actions = array(); - /** - * @var string Email msgid - */ - public $email_msgid; + /** + * @var string Email msgid + */ + public $email_msgid; - /** - * @var string Email from - */ - public $email_from; + /** + * @var string Email from + */ + public $email_from; - /** - * @var string Email sender - */ - public $email_sender; + /** + * @var string Email sender + */ + public $email_sender; - /** - * @var string Email to - */ - public $email_to; + /** + * @var string Email to + */ + public $email_to; - /** - * @var string Email tocc - */ - public $email_tocc; - /** - * @var string Email tobcc - */ - public $email_tobcc; + /** + * @var string Email tocc + */ + public $email_tocc; + /** + * @var string Email tobcc + */ + public $email_tobcc; - /** - * @var string Email subject - */ - public $email_subject; + /** + * @var string Email subject + */ + public $email_subject; - /** - * @var string Email errors to - */ - public $errors_to; + /** + * @var string Email errors to + */ + public $errors_to; /** * Typical value for a event that is in a todo state @@ -352,186 +359,186 @@ class ActionComm extends CommonObject */ const EVENT_FINISHED = 100; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB $db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } - /** - * Add an action/event into database. - * $this->type_id OR $this->type_code must be set. - * - * @param User $user Object user making action - * @param int $notrigger 1 = disable triggers, 0 = enable triggers - * @return int Id of created event, < 0 if KO - */ - public function create(User $user, $notrigger = 0) - { - global $langs, $conf, $hookmanager; + /** + * Add an action/event into database. + * $this->type_id OR $this->type_code must be set. + * + * @param User $user Object user making action + * @param int $notrigger 1 = disable triggers, 0 = enable triggers + * @return int Id of created event, < 0 if KO + */ + public function create(User $user, $notrigger = 0) + { + global $langs, $conf, $hookmanager; - $error = 0; - $now = dol_now(); + $error = 0; + $now = dol_now(); - // Check parameters - if (!isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0 - { - dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING); - $this->errors[] = 'ErrorPropertyUserowneridNotDefined'; - return -1; - } + // Check parameters + if (!isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0 + { + dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING); + $this->errors[] = 'ErrorPropertyUserowneridNotDefined'; + return -1; + } - // Clean parameters - $this->label = dol_trunc(trim($this->label), 128); - $this->location = dol_trunc(trim($this->location), 128); - $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private)); - if (empty($this->percentage)) $this->percentage = 0; - if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; - if (empty($this->fulldayevent)) $this->fulldayevent = 0; - if (empty($this->transparency)) $this->transparency = 0; - if ($this->percentage > 100) $this->percentage = 100; - //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if (!empty($this->datep) && !empty($this->datef)) $this->durationp = ($this->datef - $this->datep); // deprecated - //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date); - if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) $this->datef = $this->datep; - //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date; - if (!isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0; - // For backward compatibility - if ($this->elementtype == 'facture') $this->elementtype = 'invoice'; - if ($this->elementtype == 'commande') $this->elementtype = 'order'; - if ($this->elementtype == 'contrat') $this->elementtype = 'contract'; + // Clean parameters + $this->label = dol_trunc(trim($this->label), 128); + $this->location = dol_trunc(trim($this->location), 128); + $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private)); + if (empty($this->percentage)) $this->percentage = 0; + if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; + if (empty($this->fulldayevent)) $this->fulldayevent = 0; + if (empty($this->transparency)) $this->transparency = 0; + if ($this->percentage > 100) $this->percentage = 100; + //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; + if (!empty($this->datep) && !empty($this->datef)) $this->durationp = ($this->datef - $this->datep); // deprecated + //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date); + if (!empty($this->datep) && !empty($this->datef) && $this->datep > $this->datef) $this->datef = $this->datep; + //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date; + if (!isset($this->fk_project) || $this->fk_project < 0) $this->fk_project = 0; + // For backward compatibility + if ($this->elementtype == 'facture') $this->elementtype = 'invoice'; + if ($this->elementtype == 'commande') $this->elementtype = 'order'; + if ($this->elementtype == 'contrat') $this->elementtype = 'contract'; - if (!is_array($this->userassigned) && !empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array - { - $tmpid = $this->userassigned; - $this->userassigned = array(); - $this->userassigned[$tmpid] = array('id'=>$tmpid, 'transparency'=>$this->transparency); - } + if (!is_array($this->userassigned) && !empty($this->userassigned)) // For backward compatibility when userassigned was an int instead fo array + { + $tmpid = $this->userassigned; + $this->userassigned = array(); + $this->userassigned[$tmpid] = array('id'=>$tmpid, 'transparency'=>$this->transparency); + } - $userownerid = $this->userownerid; - $userdoneid = $this->userdoneid; + $userownerid = $this->userownerid; + $userdoneid = $this->userdoneid; - // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...). - if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned)) - $this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency)); + // Be sure assigned user is defined as an array of array('id'=>,'mandatory'=>,...). + if (empty($this->userassigned) || count($this->userassigned) == 0 || !is_array($this->userassigned)) + $this->userassigned = array($userownerid=>array('id'=>$userownerid, 'transparency'=>$this->transparency)); - if (!$this->type_id || !$this->type_code) - { - $key = empty($this->type_id) ? $this->type_code : $this->type_id; + if (!$this->type_id || !$this->type_code) + { + $key = empty($this->type_id) ? $this->type_code : $this->type_id; - // Get id from code - $cactioncomm = new CActionComm($this->db); - $result = $cactioncomm->fetch($key); + // Get id from code + $cactioncomm = new CActionComm($this->db); + $result = $cactioncomm->fetch($key); - if ($result > 0) - { - $this->type_id = $cactioncomm->id; - $this->type_code = $cactioncomm->code; - } elseif ($result == 0) - { - $this->error = 'Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"'; - return -1; - } else { - $this->error = $cactioncomm->error; - return -1; - } - } - $code = empty($this->code) ? $this->type_code : $this->code; + if ($result > 0) + { + $this->type_id = $cactioncomm->id; + $this->type_code = $cactioncomm->code; + } elseif ($result == 0) + { + $this->error = 'Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"'; + return -1; + } else { + $this->error = $cactioncomm->error; + return -1; + } + } + $code = empty($this->code) ? $this->type_code : $this->code; - // Check parameters - if (!$this->type_id) - { - $this->error = "ErrorWrongParameters"; - return -1; - } + // Check parameters + if (!$this->type_id) + { + $this->error = "ErrorWrongParameters"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm"; - $sql .= "(datec,"; - $sql .= "datep,"; - $sql .= "datep2,"; - $sql .= "durationp,"; // deprecated - $sql .= "fk_action,"; - $sql .= "code,"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm"; + $sql .= "(datec,"; + $sql .= "datep,"; + $sql .= "datep2,"; + $sql .= "durationp,"; // deprecated + $sql .= "fk_action,"; + $sql .= "code,"; $sql .= "ref_ext,"; - $sql .= "fk_soc,"; - $sql .= "fk_project,"; - $sql .= "note,"; - $sql .= "fk_contact,"; - $sql .= "fk_user_author,"; - $sql .= "fk_user_action,"; - $sql .= "fk_user_done,"; - $sql .= "label,percent,priority,fulldayevent,location,"; - $sql .= "transparency,"; - $sql .= "fk_element,"; - $sql .= "elementtype,"; - $sql .= "entity,"; - $sql .= "extraparams,"; + $sql .= "fk_soc,"; + $sql .= "fk_project,"; + $sql .= "note,"; + $sql .= "fk_contact,"; + $sql .= "fk_user_author,"; + $sql .= "fk_user_action,"; + $sql .= "fk_user_done,"; + $sql .= "label,percent,priority,fulldayevent,location,"; + $sql .= "transparency,"; + $sql .= "fk_element,"; + $sql .= "elementtype,"; + $sql .= "entity,"; + $sql .= "extraparams,"; // Fields emails - $sql .= "email_msgid,"; - $sql .= "email_from,"; - $sql .= "email_sender,"; - $sql .= "email_to,"; - $sql .= "email_tocc,"; - $sql .= "email_tobcc,"; - $sql .= "email_subject,"; - $sql .= "errors_to"; - $sql .= ") VALUES ("; - $sql .= "'".$this->db->idate($now)."', "; - $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", "; - $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", "; - $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated - $sql .= (isset($this->type_id) ? $this->type_id : "null").","; - $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", "; - $sql .= ($this->ref_ext ? ("'".$this->db->idate($this->ref_ext)."'") : "null").", "; - $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", "; - $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", "; - $sql .= " '".$this->db->escape($this->note_private)."', "; - $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; - $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", "; - $sql .= ($userownerid > 0 ? $userownerid : "null").", "; - $sql .= ($userdoneid > 0 ? $userdoneid : "null").", "; - $sql .= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."', "; - $sql .= "'".$this->db->escape($this->transparency)."', "; - $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", "; - $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", "; - $sql .= $conf->entity.","; - $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", "; - // Fields emails - $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", "; - $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", "; - $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", "; - $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", "; - $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", "; - $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", "; - $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", "; - $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null"); - $sql .= ")"; + $sql .= "email_msgid,"; + $sql .= "email_from,"; + $sql .= "email_sender,"; + $sql .= "email_to,"; + $sql .= "email_tocc,"; + $sql .= "email_tobcc,"; + $sql .= "email_subject,"; + $sql .= "errors_to"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($now)."', "; + $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", "; + $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", "; + $sql .= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '') ? "'".$this->db->escape($this->durationp)."'" : "null").", "; // deprecated + $sql .= (isset($this->type_id) ? $this->type_id : "null").","; + $sql .= ($code ? ("'".$this->db->escape($code)."'") : "null").", "; + $sql .= (!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").", "; + $sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", "; + $sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", "; + $sql .= " '".$this->db->escape($this->note_private)."', "; + $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned + $sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", "; + $sql .= ($userownerid > 0 ? $userownerid : "null").", "; + $sql .= ($userdoneid > 0 ? $userdoneid : "null").", "; + $sql .= "'".$this->db->escape($this->label)."','".$this->db->escape($this->percentage)."','".$this->db->escape($this->priority)."','".$this->db->escape($this->fulldayevent)."','".$this->db->escape($this->location)."', "; + $sql .= "'".$this->db->escape($this->transparency)."', "; + $sql .= (!empty($this->fk_element) ? $this->fk_element : "null").", "; + $sql .= (!empty($this->elementtype) ? "'".$this->db->escape($this->elementtype)."'" : "null").", "; + $sql .= $conf->entity.","; + $sql .= (!empty($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").", "; + // Fields emails + $sql .= (!empty($this->email_msgid) ? "'".$this->db->escape($this->email_msgid)."'" : "null").", "; + $sql .= (!empty($this->email_from) ? "'".$this->db->escape($this->email_from)."'" : "null").", "; + $sql .= (!empty($this->email_sender) ? "'".$this->db->escape($this->email_sender)."'" : "null").", "; + $sql .= (!empty($this->email_to) ? "'".$this->db->escape($this->email_to)."'" : "null").", "; + $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", "; + $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", "; + $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", "; + $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null"); + $sql .= ")"; - dol_syslog(get_class($this)."::add", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); + dol_syslog(get_class($this)."::add", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); - // Now insert assigned users + // Now insert assigned users if (!$error) { //dol_syslog(var_export($this->userassigned, true)); foreach ($this->userassigned as $key => $val) { - if (!is_array($val)) // For backward compatibility when val=id - { - $val = array('id'=>$val); - } + if (!is_array($val)) // For backward compatibility when val=id + { + $val = array('id'=>$val); + } - if ($val['id'] > 0) - { + if ($val['id'] > 0) + { $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")"; @@ -540,10 +547,10 @@ class ActionComm extends CommonObject { $error++; dol_syslog('Error to process userassigned: '.$this->db->lasterror(), LOG_ERR); - $this->errors[] = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } //var_dump($sql);exit; - } + } } } @@ -567,54 +574,54 @@ class ActionComm extends CommonObject } } - if (!$error) - { - // Actions on extra fields - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + // Actions on extra fields + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('ACTION_CREATE', $user); - if ($result < 0) { $error++; } - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('ACTION_CREATE', $user); + if ($result < 0) { $error++; } + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return -1; + } + } - /** - * Load an object from its id and create a new one in database - * - * @param User $fuser Object user making action + /** + * Load an object from its id and create a new one in database + * + * @param User $fuser Object user making action * @param int $socid Id of thirdparty - * @return int New id of clone - */ - public function createFromClone(User $fuser, $socid) - { - global $db, $conf, $hookmanager; + * @return int New id of clone + */ + public function createFromClone(User $fuser, $socid) + { + global $db, $conf, $hookmanager; - $error = 0; - $now = dol_now(); + $error = 0; + $now = dol_now(); - $this->db->begin(); + $this->db->begin(); // Load source object $objFrom = clone $this; @@ -626,170 +633,173 @@ class ActionComm extends CommonObject //$this->fetch_userassigned(); $this->fetchResources(); - $this->id = 0; + $this->id = 0; - // Create clone + // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($fuser); - if ($result < 0) $error++; + if ($result < 0) $error++; - if (!$error) - { - // Hook of thirdparty module - 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 (!$error) + { + // Hook of thirdparty module + 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++; + } - // Call trigger - $result = $this->call_trigger('ACTION_CLONE', $fuser); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result = $this->call_trigger('ACTION_CLONE', $fuser); + if ($result < 0) { $error++; } + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Load object from database - * - * @param int $id Id of action to get - * @param string $ref Ref of action to get - * @param string $ref_ext Ref ext to get - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '', $ref_ext = '') - { - global $langs; + /** + * Load object from database + * + * @param int $id Id of action to get + * @param string $ref Ref of action to get + * @param string $ref_ext Ref ext to get + * @param string $email_msgid Email msgid + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '') + { + global $langs; - $sql = "SELECT a.id,"; - $sql .= " a.id as ref,"; - $sql .= " a.entity,"; - $sql .= " a.ref_ext,"; - $sql .= " a.datep,"; - $sql .= " a.datep2,"; - $sql .= " a.durationp,"; // deprecated - $sql .= " a.datec,"; - $sql .= " a.tms as datem,"; - $sql .= " a.code, a.label, a.note,"; - $sql .= " a.fk_soc,"; - $sql .= " a.fk_project,"; - $sql .= " a.fk_user_author, a.fk_user_mod,"; - $sql .= " a.fk_user_action, a.fk_user_done,"; - $sql .= " a.fk_contact, a.percent as percentage,"; - $sql .= " a.fk_element as elementid, a.elementtype,"; - $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; - $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; - $sql .= " s.nom as socname,"; - $sql .= " u.firstname, u.lastname as lastname"; - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; - $sql .= " WHERE "; - if ($ref) $sql .= " a.id=".$ref; // No field ref, we use id - elseif ($ref_ext) $sql .= " a.ref_ext='".$this->db->escape($ref_ext)."'"; - else $sql .= " a.id=".$id; + $sql = "SELECT a.id,"; + $sql .= " a.id as ref,"; + $sql .= " a.entity,"; + $sql .= " a.ref_ext,"; + $sql .= " a.datep,"; + $sql .= " a.datep2,"; + $sql .= " a.durationp,"; // deprecated + $sql .= " a.datec,"; + $sql .= " a.tms as datem,"; + $sql .= " a.code, a.label, a.note,"; + $sql .= " a.fk_soc,"; + $sql .= " a.fk_project,"; + $sql .= " a.fk_user_author, a.fk_user_mod,"; + $sql .= " a.fk_user_action, a.fk_user_done,"; + $sql .= " a.fk_contact, a.percent as percentage,"; + $sql .= " a.fk_element as elementid, a.elementtype,"; + $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; + $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; + $sql .= " s.nom as socname,"; + $sql .= " u.firstname, u.lastname as lastname"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; + $sql .= " WHERE "; + if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id + elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; + elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'"; + else $sql .= " a.id = ".((int) $id); - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->id; - $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_ext = $obj->ref_ext; + $this->id = $obj->id; + $this->entity = $obj->entity; + $this->ref = $obj->ref; + $this->ref_ext = $obj->ref_ext; - // Properties of parent table llx_c_actioncomm - $this->type_id = $obj->type_id; - $this->type_code = $obj->type_code; - $this->type_color = $obj->type_color; - $this->type_picto = $obj->type_picto; - $transcode = $langs->trans("Action".$obj->type_code); - $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); - $transcode = $langs->trans("Action".$obj->type_code.'Short'); - $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); + // Properties of parent table llx_c_actioncomm + $this->type_id = $obj->type_id; + $this->type_code = $obj->type_code; + $this->type_color = $obj->type_color; + $this->type_picto = $obj->type_picto; + $transcode = $langs->trans("Action".$obj->type_code); + $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label); + $transcode = $langs->trans("Action".$obj->type_code.'Short'); + $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : ''); $this->code = $obj->code; - $this->label = $obj->label; - $this->datep = $this->db->jdate($obj->datep); - $this->datef = $this->db->jdate($obj->datep2); + $this->label = $obj->label; + $this->datep = $this->db->jdate($obj->datep); + $this->datef = $this->db->jdate($obj->datep2); - $this->datec = $this->db->jdate($obj->datec); - $this->datem = $this->db->jdate($obj->datem); + $this->datec = $this->db->jdate($obj->datec); + $this->datem = $this->db->jdate($obj->datem); - $this->note = $obj->note; // deprecated - $this->note_private = $obj->note; - $this->percentage = $obj->percentage; + $this->note = $obj->note; // deprecated + $this->note_private = $obj->note; + $this->percentage = $obj->percentage; - $this->authorid = $obj->fk_user_author; - $this->usermodid = $obj->fk_user_mod; + $this->authorid = $obj->fk_user_author; + $this->usermodid = $obj->fk_user_mod; - if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning - $this->author->id = $obj->fk_user_author; // deprecated - $this->author->firstname = $obj->firstname; // deprecated - $this->author->lastname = $obj->lastname; // deprecated - if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning - $this->usermod->id = $obj->fk_user_mod; // deprecated + if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning + $this->author->id = $obj->fk_user_author; // deprecated + $this->author->firstname = $obj->firstname; // deprecated + $this->author->lastname = $obj->lastname; // deprecated + if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning + $this->usermod->id = $obj->fk_user_mod; // deprecated - $this->userownerid = $obj->fk_user_action; - $this->userdoneid = $obj->fk_user_done; - $this->priority = $obj->priority; - $this->fulldayevent = $obj->fulldayevent; - $this->location = $obj->location; - $this->transparency = $obj->transparency; + $this->userownerid = $obj->fk_user_action; + $this->userdoneid = $obj->fk_user_done; + $this->priority = $obj->priority; + $this->fulldayevent = $obj->fulldayevent; + $this->location = $obj->location; + $this->transparency = $obj->transparency; - $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working - $this->contact_id = $obj->fk_contact; // To have fetch_contact method working - $this->fk_project = $obj->fk_project; // To have fetch_projet method working + $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working + $this->contact_id = $obj->fk_contact; // To have fetch_contact method working + $this->fk_project = $obj->fk_project; // To have fetch_projet method working - //$this->societe->id = $obj->fk_soc; // deprecated - //$this->contact->id = $obj->fk_contact; // deprecated + //$this->societe->id = $obj->fk_soc; // deprecated + //$this->contact->id = $obj->fk_contact; // deprecated - $this->fk_element = $obj->elementid; - $this->elementid = $obj->elementid; - $this->elementtype = $obj->elementtype; + $this->fk_element = $obj->elementid; + $this->elementid = $obj->elementid; + $this->elementtype = $obj->elementtype; - $this->fetchResources(); - } - $this->db->free($resql); - } else { - $this->error = $this->db->lasterror(); - return -1; - } + $this->fetchResources(); + } + $this->db->free($resql); + } else { + $this->error = $this->db->lasterror(); + return -1; + } - return $num; - } + return $num; + } - /** - * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event - * - * @return int <0 if KO, >0 if OK - */ - public function fetchResources() - { - $this->userassigned = array(); - $this->socpeopleassigned = array(); + /** + * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event + * + * @return int <0 if KO, >0 if OK + */ + public function fetchResources() + { + $this->userassigned = array(); + $this->socpeopleassigned = array(); - $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; + $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency'; $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources'; $sql .= ' WHERE fk_actioncomm = '.$this->id; $sql .= " AND element_type IN ('user', 'socpeople')"; @@ -799,9 +809,9 @@ class ActionComm extends CommonObject // If owner is known, we must but id first into list if ($this->userownerid > 0) $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); // Set first so will be first into list. - while ($obj = $this->db->fetch_object($resql)) - { - if ($obj->fk_element > 0) + while ($obj = $this->db->fetch_object($resql)) + { + if ($obj->fk_element > 0) { switch ($obj->element_type) { case 'user': @@ -813,86 +823,86 @@ class ActionComm extends CommonObject break; } } - } + } - return 1; + return 1; } else { dol_print_error($this->db); return -1; } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Initialize this->userassigned array with list of id of user assigned to event - * - * @param bool $override Override $this->userownerid when empty. TODO This should be false by default. True is here to fix corrupted data. - * @return int <0 if KO, >0 if OK - */ - public function fetch_userassigned($override = true) - { - // phpcs:enable - $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency"; - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources"; - $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".$this->id; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Initialize this->userassigned array with list of id of user assigned to event + * + * @param bool $override Override $this->userownerid when empty. TODO This should be false by default. True is here to fix corrupted data. + * @return int <0 if KO, >0 if OK + */ + public function fetch_userassigned($override = true) + { + // phpcs:enable + $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources"; + $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".$this->id; - $resql2 = $this->db->query($sql); - if ($resql2) - { - $this->userassigned = array(); + $resql2 = $this->db->query($sql); + if ($resql2) + { + $this->userassigned = array(); - // If owner is known, we must but id first into list - if ($this->userownerid > 0) - { - // Set first so will be first into list. - $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); - } + // If owner is known, we must but id first into list + if ($this->userownerid > 0) + { + // Set first so will be first into list. + $this->userassigned[$this->userownerid] = array('id'=>$this->userownerid); + } - while ($obj = $this->db->fetch_object($resql2)) - { - if ($obj->fk_element > 0) - { - $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, - 'mandatory'=>$obj->mandatory, - 'answer_status'=>$obj->answer_status, - 'transparency'=>$obj->transparency); - } + while ($obj = $this->db->fetch_object($resql2)) + { + if ($obj->fk_element > 0) + { + $this->userassigned[$obj->fk_element] = array('id'=>$obj->fk_element, + 'mandatory'=>$obj->mandatory, + 'answer_status'=>$obj->answer_status, + 'transparency'=>$obj->transparency); + } - if ($override === true) - { - // If not defined (should not happened, we fix this) - if (empty($this->userownerid)) - { - $this->userownerid = $obj->fk_element; - } - } - } + if ($override === true) + { + // If not defined (should not happened, we fix this) + if (empty($this->userownerid)) + { + $this->userownerid = $obj->fk_element; + } + } + } - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Delete event from database - * - * @param int $notrigger 1 = disable triggers, 0 = enable triggers - * @return int <0 if KO, >0 if OK - */ - public function delete($notrigger = 0) - { - global $user; + /** + * Delete event from database + * + * @param int $notrigger 1 = disable triggers, 0 = enable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($notrigger = 0) + { + global $user; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $this->db->begin(); + $this->db->begin(); - // remove categorie association - if (!$error) { + // remove categorie association + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_actioncomm"; $sql .= " WHERE fk_actioncomm=".$this->id; @@ -901,148 +911,160 @@ class ActionComm extends CommonObject $this->error = $this->db->lasterror(); $error++; } - } + } - // remove actioncomm_resources - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources"; - $sql .= " WHERE fk_actioncomm=".$this->id; + // remove actioncomm_resources + if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources"; + $sql .= " WHERE fk_actioncomm=".$this->id; - $res = $this->db->query($sql); - if (!$res) { - $this->error = $this->db->lasterror(); - $error++; - } - } + $res = $this->db->query($sql); + if (!$res) { + $this->error = $this->db->lasterror(); + $error++; + } + } - // Removed extrafields - if (!$error) { - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); - } - } + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + $sql .= " WHERE fk_actioncomm = ".$this->id; - // remove actioncomm - if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm"; - $sql .= " WHERE id=".$this->id; + $res = $this->db->query($sql); + if (!$res) { + $this->error = $this->db->lasterror(); + $error++; + } + } - $res = $this->db->query($sql); - if (!$res) { - $this->error = $this->db->lasterror(); - $error++; - } - } + // Removed extrafields + if (!$error) { + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); + } + } - if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('ACTION_DELETE', $user); - if ($result < 0) { $error++; } - // End call triggers - } + // remove actioncomm + if (!$error) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm"; + $sql .= " WHERE id=".$this->id; - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -2; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } + $res = $this->db->query($sql); + if (!$res) { + $this->error = $this->db->lasterror(); + $error++; + } + } - /** - * Update action into database - * If percentage = 100, on met a jour date 100% - * - * @param User $user Object user making change - * @param int $notrigger 1 = disable triggers, 0 = enable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0) - { - global $langs, $conf, $hookmanager; + if (!$error) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('ACTION_DELETE', $user); + if ($result < 0) { $error++; } + // End call triggers + } - $error = 0; + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return -1; + } + } - // Clean parameters - $this->label = trim($this->label); - $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private)); - if (empty($this->percentage)) $this->percentage = 0; - if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; - if (empty($this->transparency)) $this->transparency = 0; - if (empty($this->fulldayevent)) $this->fulldayevent = 0; - if ($this->percentage > 100) $this->percentage = 100; - //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated - //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date); - if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep; - //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date; - if ($this->fk_project < 0) $this->fk_project = 0; + /** + * Update action into database + * If percentage = 100, on met a jour date 100% + * + * @param User $user Object user making change + * @param int $notrigger 1 = disable triggers, 0 = enable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0) + { + global $langs, $conf, $hookmanager; - // Check parameters - if ($this->percentage == 0 && $this->userdoneid > 0) - { - $this->error = "ErrorCantSaveADoneUserWithZeroPercentage"; - return -1; - } + $error = 0; - $socid = (($this->socid > 0) ? $this->socid : 0); - $contactid = (($this->contact_id > 0) ? $this->contact_id : 0); + // Clean parameters + $this->label = trim($this->label); + $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private)); + if (empty($this->percentage)) $this->percentage = 0; + if (empty($this->priority) || !is_numeric($this->priority)) $this->priority = 0; + if (empty($this->transparency)) $this->transparency = 0; + if (empty($this->fulldayevent)) $this->fulldayevent = 0; + if ($this->percentage > 100) $this->percentage = 100; + //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; + if ($this->datep && $this->datef) $this->durationp = ($this->datef - $this->datep); // deprecated + //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date); + if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef = $this->datep; + //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date; + if ($this->fk_project < 0) $this->fk_project = 0; + + // Check parameters + if ($this->percentage == 0 && $this->userdoneid > 0) + { + $this->error = "ErrorCantSaveADoneUserWithZeroPercentage"; + return -1; + } + + $socid = (($this->socid > 0) ? $this->socid : 0); + $contactid = (($this->contact_id > 0) ? $this->contact_id : 0); $userownerid = ($this->userownerid ? $this->userownerid : 0); $userdoneid = ($this->userdoneid ? $this->userdoneid : 0); - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm "; - $sql .= " SET percent = '".$this->db->escape($this->percentage)."'"; - if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'"; - $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null'); - $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null'); - $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated - $sql .= ", note = '".$this->db->escape($this->note_private)."'"; - $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null"); - $sql .= ", fk_soc =".($socid > 0 ? $socid : "null"); - $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null"); - $sql .= ", priority = '".$this->db->escape($this->priority)."'"; - $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'"; - $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null"); - $sql .= ", transparency = '".$this->db->escape($this->transparency)."'"; - $sql .= ", fk_user_mod = ".$user->id; - $sql .= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'" : "null"); - $sql .= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'" : "null"); - if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null"); - if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null"); - $sql .= " WHERE id=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm "; + $sql .= " SET percent = '".$this->db->escape($this->percentage)."'"; + if ($this->type_id > 0) $sql .= ", fk_action = '".$this->db->escape($this->type_id)."'"; + $sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", datep = ".(strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : 'null'); + $sql .= ", datep2 = ".(strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : 'null'); + $sql .= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '' ? "'".$this->db->escape($this->durationp)."'" : "null"); // deprecated + $sql .= ", note = '".$this->db->escape($this->note_private)."'"; + $sql .= ", fk_project =".($this->fk_project > 0 ? $this->fk_project : "null"); + $sql .= ", fk_soc =".($socid > 0 ? $socid : "null"); + $sql .= ", fk_contact =".($contactid > 0 ? $contactid : "null"); + $sql .= ", priority = '".$this->db->escape($this->priority)."'"; + $sql .= ", fulldayevent = '".$this->db->escape($this->fulldayevent)."'"; + $sql .= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'" : "null"); + $sql .= ", transparency = '".$this->db->escape($this->transparency)."'"; + $sql .= ", fk_user_mod = ".$user->id; + $sql .= ", fk_user_action = ".($userownerid > 0 ? "'".$this->db->escape($userownerid)."'" : "null"); + $sql .= ", fk_user_done = ".($userdoneid > 0 ? "'".$this->db->escape($userdoneid)."'" : "null"); + if (!empty($this->fk_element)) $sql .= ", fk_element=".($this->fk_element ? $this->db->escape($this->fk_element) : "null"); + if (!empty($this->elementtype)) $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null"); + $sql .= " WHERE id=".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - if ($this->db->query($sql)) - { + dol_syslog(get_class($this)."::update", LOG_DEBUG); + if ($this->db->query($sql)) + { $action = 'update'; - // Actions on extra fields - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + // Actions on extra fields + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - // Now insert assignedusers + // Now insert assignedusers if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'"; @@ -1050,10 +1072,10 @@ class ActionComm extends CommonObject foreach ($this->userassigned as $key => $val) { - if (!is_array($val)) // For backward compatibility when val=id - { - $val = array('id'=>$val); - } + if (!is_array($val)) // For backward compatibility when val=id + { + $val = array('id'=>$val); + } $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; $sql .= " VALUES(".$this->id.", 'user', ".$val['id'].", ".(empty($val['mandatory']) ? '0' : $val['mandatory']).", ".(empty($val['transparency']) ? '0' : $val['transparency']).", ".(empty($val['answer_status']) ? '0' : $val['answer_status']).")"; @@ -1061,7 +1083,7 @@ class ActionComm extends CommonObject if (!$resql) { $error++; - $this->errors[] = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); } //var_dump($sql);exit; } @@ -1089,263 +1111,272 @@ class ActionComm extends CommonObject } } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('ACTION_MODIFY', $user); - if ($result < 0) { $error++; } - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('ACTION_MODIFY', $user); + if ($result < 0) { $error++; } + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR); - return -2; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + dol_syslog(get_class($this)."::update ".join(',', $this->errors), LOG_ERR); + return -2; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return -1; + } + } - /** - * Load all objects with filters. - * @todo WARNING: This make a fetch on all records instead of making one request with a join. - * - * @param DoliDb $db Database handler - * @param int $socid Filter by thirdparty - * @param int $fk_element Id of element action is linked to - * @param string $elementtype Type of element action is linked to - * @param string $filter Other filter - * @param string $sortfield Sort on this field - * @param string $sortorder ASC or DESC - * @param string $limit Limit number of answers - * @return array|string Error string if KO, array with actions if OK - */ - public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0) - { - global $conf, $langs; + /** + * Load all objects with filters. + * @todo WARNING: This make a fetch on all records instead of making one request with a join. + * + * @param DoliDb $db Not used + * @param int $socid Filter by thirdparty + * @param int $fk_element Id of element action is linked to + * @param string $elementtype Type of element action is linked to + * @param string $filter Other filter + * @param string $sortfield Sort on this field + * @param string $sortorder ASC or DESC + * @param string $limit Limit number of answers + * @return array|string Error string if KO, array with actions if OK + */ + public static function getActions($db, $socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0) + { + global $conf, $langs; - $resarray = array(); + $resarray = array(); - dol_syslog(get_class()."::getActions", LOG_DEBUG); + dol_syslog(get_class()."::getActions", LOG_DEBUG); - $sql = "SELECT a.id"; - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; - if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid; - if (!empty($elementtype)) - { - if ($elementtype == 'project') $sql .= ' AND a.fk_project = '.$fk_element; - else $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$elementtype."'"; - } - if (!empty($filter)) $sql .= $filter; + $sql = "SELECT a.id"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; + if (!empty($socid)) $sql .= " AND a.fk_soc = ".$socid; + if (!empty($elementtype)) + { + if ($elementtype == 'project') { + $sql .= ' AND a.fk_project = '.$fk_element; + } + elseif ($elementtype == 'contact') { + $sql .= ' AND a.id IN'; + $sql .= " (SELECT fk_actioncomm FROM ".MAIN_DB_PREFIX."actioncomm_resources WHERE"; + $sql .= " element_type = 'socpeople' AND fk_element = ".$fk_element.')'; + } + else { + $sql .= " AND a.fk_element = ".(int) $fk_element." AND a.elementtype = '".$db->escape($elementtype)."'"; + } + } + if (!empty($filter)) $sql .= $filter; if ($sortorder && $sortfield) $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($limit, 0); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); - if ($num) - { - for ($i = 0; $i < $num; $i++) - { - $obj = $db->fetch_object($resql); - $actioncommstatic = new ActionComm($db); - $actioncommstatic->fetch($obj->id); - $resarray[$i] = $actioncommstatic; - } - } - $db->free($resql); - return $resarray; - } else { - return $db->lasterror(); - } - } + if ($num) + { + for ($i = 0; $i < $num; $i++) + { + $obj = $db->fetch_object($resql); + $actioncommstatic = new ActionComm($db); + $actioncommstatic->fetch($obj->id); + $resarray[$i] = $actioncommstatic; + } + } + $db->free($resql); + return $resarray; + } else { + return $db->lasterror(); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param int $load_state_board Charge indicateurs this->nb de tableau de bord - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - public function load_board($user, $load_state_board = 0) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param int $load_state_board Charge indicateurs this->nb de tableau de bord + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user, $load_state_board = 0) + { + // phpcs:enable + global $conf, $langs; - if (empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; - else { - $this->nb = array(); - $sql = "SELECT count(a.id) as nb"; - } - $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; - if (!$user->rights->societe->client->voir && !$user->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 .= " WHERE 1 = 1"; - if (empty($load_state_board)) $sql .= " AND a.percent >= 0 AND a.percent < 100"; - $sql .= " AND a.entity IN (".getEntity('agenda').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; - if ($user->socid) $sql .= " AND a.fk_soc = ".$user->socid; - if (!$user->rights->agenda->allactions->read) $sql .= " AND (a.fk_user_author = ".$user->id." OR a.fk_user_action = ".$user->id." OR a.fk_user_done = ".$user->id.")"; + if (empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; + else { + $this->nb = array(); + $sql = "SELECT count(a.id) as nb"; + } + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; + if (!$user->rights->societe->client->voir && !$user->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 .= " WHERE 1 = 1"; + if (empty($load_state_board)) $sql .= " AND a.percent >= 0 AND a.percent < 100"; + $sql .= " AND a.entity IN (".getEntity('agenda').")"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; + if ($user->socid) $sql .= " AND a.fk_soc = ".$user->socid; + if (!$user->rights->agenda->allactions->read) $sql .= " AND (a.fk_user_author = ".$user->id." OR a.fk_user_action = ".$user->id." OR a.fk_user_done = ".$user->id.")"; - $resql = $this->db->query($sql); - if ($resql) - { - if (empty($load_state_board)) { - $agenda_static = new ActionComm($this->db); - $response = new WorkboardResponse(); - $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ActionsToDo"); - $response->labelShort = $langs->trans("ActionsToDoShort"); - $response->url = DOL_URL_ROOT.'/comm/action/list.php?action=show_list&actioncode=0&status=todo&mainmenu=agenda'; - if ($user->rights->agenda->allactions->read) $response->url .= '&filtert=-1'; - $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"'); - } - // This assignment in condition is not a bug. It allows walking the results. - while ($obj = $this->db->fetch_object($resql)) - { - if (empty($load_state_board)) { - $response->nbtodo++; - $agenda_static->datep = $this->db->jdate($obj->dp); - if ($agenda_static->hasDelay()) $response->nbtodolate++; - } else $this->nb["actionscomm"] = $obj->nb; - } + $resql = $this->db->query($sql); + if ($resql) + { + if (empty($load_state_board)) { + $agenda_static = new ActionComm($this->db); + $response = new WorkboardResponse(); + $response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ActionsToDo"); + $response->labelShort = $langs->trans("ActionsToDoShort"); + $response->url = DOL_URL_ROOT.'/comm/action/list.php?action=show_list&actioncode=0&status=todo&mainmenu=agenda'; + if ($user->rights->agenda->allactions->read) $response->url .= '&filtert=-1'; + $response->img = img_object('', "action", 'class="inline-block valigntextmiddle"'); + } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj = $this->db->fetch_object($resql)) + { + if (empty($load_state_board)) { + $response->nbtodo++; + $agenda_static->datep = $this->db->jdate($obj->dp); + if ($agenda_static->hasDelay()) $response->nbtodolate++; + } else $this->nb["actionscomm"] = $obj->nb; + } - $this->db->free($resql); - if (empty($load_state_board)) return $response; - else return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } + $this->db->free($resql); + if (empty($load_state_board)) return $response; + else return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - /** - * Charge les informations d'ordre info dans l'objet facture - * - * @param int $id Id de la facture a charger - * @return void - */ - public function info($id) - { - $sql = 'SELECT '; - $sql .= ' a.id,'; - $sql .= ' datec,'; - $sql .= ' tms as datem,'; - $sql .= ' fk_user_author,'; - $sql .= ' fk_user_mod'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; - $sql .= ' WHERE a.id = '.$id; + /** + * Charge les informations d'ordre info dans l'objet facture + * + * @param int $id Id de la facture a charger + * @return void + */ + public function info($id) + { + $sql = 'SELECT '; + $sql .= ' a.id,'; + $sql .= ' datec,'; + $sql .= ' tms as datem,'; + $sql .= ' fk_user_author,'; + $sql .= ' fk_user_mod'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; + $sql .= ' WHERE a.id = '.$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->id; - 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) - { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_mod); - $this->user_modification = $muser; - } + 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->id; + 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) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_mod); + $this->user_modification = $muser; + } - $this->date_creation = $this->db->jdate($obj->datec); - if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->date_creation = $this->db->jdate($obj->datec); + if (!empty($obj->fk_user_mod)) $this->date_modification = $this->db->jdate($obj->datem); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * Return label of status - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @param int $hidenastatus 1=Show nothing if status is "Not applicable" - * @return string String with status - */ - public function getLibStatut($mode, $hidenastatus = 0) - { - return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep); - } + /** + * Return label of status + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @param int $hidenastatus 1=Show nothing if status is "Not applicable" + * @return string String with status + */ + public function getLibStatut($mode, $hidenastatus = 0) + { + return $this->LibStatut($this->percentage, $mode, $hidenastatus, $this->datep); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return label of action status - * - * @param int $percent Percent - * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto - * @param int $hidenastatus 1=Show nothing if status is "Not applicable" - * @param int $datestart Date start of event - * @return string Label - */ - public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of action status + * + * @param int $percent Percent + * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto + * @param int $hidenastatus 1=Show nothing if status is "Not applicable" + * @param int $datestart Date start of event + * @return string Label + */ + public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '') + { + // phpcs:enable + global $langs; - $labelStatus = $langs->trans('StatusNotApplicable'); - if ($percent == -1 && !$hidenastatus) $labelStatus = $langs->trans('StatusNotApplicable'); - elseif ($percent == 0) $labelStatus = $langs->trans('StatusActionToDo').' (0%)'; - elseif ($percent > 0 && $percent < 100) $labelStatus = $langs->trans('StatusActionInProcess').' ('.$percent.'%)'; - elseif ($percent >= 100) $labelStatus = $langs->trans('StatusActionDone').' (100%)'; + $labelStatus = $langs->trans('StatusNotApplicable'); + if ($percent == -1 && !$hidenastatus) $labelStatus = $langs->trans('StatusNotApplicable'); + elseif ($percent == 0) $labelStatus = $langs->trans('StatusActionToDo').' (0%)'; + elseif ($percent > 0 && $percent < 100) $labelStatus = $langs->trans('StatusActionInProcess').' ('.$percent.'%)'; + elseif ($percent >= 100) $labelStatus = $langs->trans('StatusActionDone').' (100%)'; - $labelStatusShort = $langs->trans('StatusNotApplicable'); - if ($percent == -1 && !$hidenastatus) $labelStatusShort = $langs->trans('NA'); - elseif ($percent == 0) $labelStatusShort = '0%'; - elseif ($percent > 0 && $percent < 100) $labelStatusShort = $percent.'%'; - elseif ($percent >= 100) $labelStatusShort = '100%'; + $labelStatusShort = $langs->trans('StatusNotApplicable'); + if ($percent == -1 && !$hidenastatus) $labelStatusShort = $langs->trans('NA'); + elseif ($percent == 0) $labelStatusShort = '0%'; + elseif ($percent > 0 && $percent < 100) $labelStatusShort = $percent.'%'; + elseif ($percent >= 100) $labelStatusShort = '100%'; - $statusType = 'status9'; - if ($percent == -1 && !$hidenastatus) $statusType = 'status9'; - if ($percent == 0) $statusType = 'status1'; - if ($percent > 0 && $percent < 100) $statusType = 'status3'; - if ($percent >= 100) $statusType = 'status6'; + $statusType = 'status9'; + if ($percent == -1 && !$hidenastatus) $statusType = 'status9'; + if ($percent == 0) $statusType = 'status1'; + if ($percent > 0 && $percent < 100) $statusType = 'status3'; + if ($percent >= 100) $statusType = 'status6'; - return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); - } + return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); + } - /** - * Return URL of event - * Use $this->id, $this->type_code, $this->label and $this->type_label - * - * @param int $withpicto 0 = No picto, 1 = Include picto into link, 2 = Only picto - * @param int $maxlength Max number of charaters into label. If negative, use the ref as label. - * @param string $classname Force style class on a link - * @param string $option '' = Link to action, 'birthday'= Link to contact, 'holiday' = Link to leave - * @param int $overwritepicto 1 = Overwrite picto - * @param int $notooltip 1 = Disable tooltip - * @param int $save_lastsearch_value -1 = Auto, 0 = No save of lastsearch_values when clicking, 1 = Save lastsearch_values whenclicking - * @return string Chaine avec URL - */ - public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1) - { - global $conf, $langs, $user, $hookmanager, $action; + /** + * Return URL of event + * Use $this->id, $this->type_code, $this->label and $this->type_label + * + * @param int $withpicto 0 = No picto, 1 = Include picto into link, 2 = Only picto + * @param int $maxlength Max number of charaters into label. If negative, use the ref as label. + * @param string $classname Force style class on a link + * @param string $option '' = Link to action, 'birthday'= Link to contact, 'holiday' = Link to leave + * @param int $overwritepicto 1 = Overwrite picto + * @param int $notooltip 1 = Disable tooltip + * @param int $save_lastsearch_value -1 = Auto, 0 = No save of lastsearch_values when clicking, 1 = Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + public function getNomUrl($withpicto = 0, $maxlength = 0, $classname = '', $option = '', $overwritepicto = 0, $notooltip = 0, $save_lastsearch_value = -1) + { + global $conf, $langs, $user, $hookmanager, $action; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips $canread = 0; if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1; // Can read my event @@ -1353,10 +1384,10 @@ class ActionComm extends CommonObject if ($user->rights->agenda->allactions->read) $canread = 1; // Can read all event of other if (!$canread) { - $option = 'nolink'; + $option = 'nolink'; } - $label = $this->label; + $label = $this->label; if (empty($label)) $label = $this->libelle; // For backward compatibility $result = ''; @@ -1369,10 +1400,10 @@ class ActionComm extends CommonObject } if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); + if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); } - $tooltip = ''.$langs->trans('Action').''; + $tooltip = img_picto('', $this->picto).' '.$langs->trans('Action').''; if (!empty($this->ref)) $tooltip .= '
'.$langs->trans('Ref').': '.$this->ref; if (!empty($label)) @@ -1381,23 +1412,25 @@ class ActionComm extends CommonObject $tooltip .= '
'.$langs->trans('Type').': '.$labeltype; if (!empty($this->location)) $tooltip .= '
'.$langs->trans('Location').': '.$this->location; + if (isset($this->transparency)) + $tooltip .= '
'.$langs->trans('Busy').': '.yn($this->transparency); if (!empty($this->note_private)) - $tooltip .= '
'.$langs->trans('Note').': '.(dol_textishtml($this->note_private) ? str_replace(array("\r", "\n"), "", $this->note_private) : str_replace(array("\r", "\n"), '
', $this->note_private)); + $tooltip .= '
'.$langs->trans('Note').': '.(dol_textishtml($this->note_private) ? str_replace(array("\r", "\n"), "", $this->note_private) : str_replace(array("\r", "\n"), '
', $this->note_private)); $linkclose = ''; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color) $linkclose = ' style="background-color:#'.$this->type_color.'"'; if (empty($notooltip)) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowAction"); - $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"'; - $linkclose .= ' class="'.$classname.' classfortooltip"'; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowAction"); + $linkclose .= ' alt="'.dol_escape_htmltag($tooltip, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1).'"'; + $linkclose .= ' class="'.$classname.' classfortooltip"'; - /* + /* $hookmanager->initHooks(array('actiondao')); $parameters=array('id'=>$this->id); $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks @@ -1409,7 +1442,7 @@ class ActionComm extends CommonObject if ($option == 'birthday') $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id; elseif ($option == 'holiday') - $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id; else $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id; if ($option !== 'nolink') { @@ -1428,170 +1461,170 @@ class ActionComm extends CommonObject $linkend = ''; } - if ($withpicto == 2) - { - $libelle = $label; - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype; - $libelleshort = ''; - } else { - $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : '')); - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype; - if ($maxlength < 0) $libelleshort = $this->ref; - else $libelleshort = dol_trunc($libelle, $maxlength); - } + if ($withpicto == 2) + { + $libelle = $label; + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle = $labeltype; + $libelleshort = ''; + } else { + $libelle = (empty($this->libelle) ? $label : $this->libelle.(($label && $label != $this->libelle) ? ' '.$label : '')); + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle = $labeltype; + if ($maxlength < 0) $libelleshort = $this->ref; + else $libelleshort = dol_trunc($libelle, $maxlength); + } - if ($withpicto) - { - if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () - { - if ($labeltype) - { - $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')'); - } - } - } + if ($withpicto) + { + if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () + { + if ($labeltype) + { + $libelle .= (preg_match('/'.preg_quote($labeltype, '/').'/', $libelle) ? '' : ' ('.$langs->transnoentities("Action".$this->type_code).')'); + } + } + } - $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - $result .= $libelleshort; - $result .= $linkend; + $result .= $linkstart; + if ($withpicto) $result .= img_object(($notooltip ? '' : $langs->trans("ShowAction").': '.$libelle), ($overwritepicto ? $overwritepicto : 'action'), ($notooltip ? 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"' : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + $result .= $libelleshort; + $result .= $linkend; - global $action; - $hookmanager->initHooks(array('actiondao')); - $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; + global $action; + $hookmanager->initHooks(array('actiondao')); + $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 $result; + } - /** - * Sets object to supplied categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param int[]|int $categories Category or categories IDs - * @return void - */ - public function setCategories($categories) - { - // Handle single category - if (!is_array($categories)) { - $categories = array($categories); - } + /** + * Sets object to supplied categories. + * + * Deletes object from existing categories not supplied. + * Adds it to non existing supplied categories. + * Existing categories are left untouch. + * + * @param int[]|int $categories Category or categories IDs + * @return void + */ + public function setCategories($categories) + { + // Handle single category + if (!is_array($categories)) { + $categories = array($categories); + } - // Get current categories - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $c = new Categorie($this->db); - $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id'); + // Get current categories + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $c = new Categorie($this->db); + $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id'); - // Diff - if (is_array($existing)) { - $to_del = array_diff($existing, $categories); - $to_add = array_diff($categories, $existing); - } else { - $to_del = array(); // Nothing to delete - $to_add = $categories; - } + // Diff + if (is_array($existing)) { + $to_del = array_diff($existing, $categories); + $to_add = array_diff($categories, $existing); + } else { + $to_del = array(); // Nothing to delete + $to_add = $categories; + } - // Process - foreach ($to_del as $del) { - if ($c->fetch($del) > 0) { - $c->del_type($this, Categorie::TYPE_ACTIONCOMM); - } - } - foreach ($to_add as $add) { - if ($c->fetch($add) > 0) { - $c->add_type($this, Categorie::TYPE_ACTIONCOMM); - } - } - return; - } + // Process + foreach ($to_del as $del) { + if ($c->fetch($del) > 0) { + $c->del_type($this, Categorie::TYPE_ACTIONCOMM); + } + } + foreach ($to_add as $add) { + if ($c->fetch($add) > 0) { + $c->add_type($this, Categorie::TYPE_ACTIONCOMM); + } + } + return; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Export events from database into a cal file. - * - * @param string $format The format of the export 'vcal', 'ical/ics' or 'rss' - * @param string $type The type of the export 'event' or 'journal' - * @param integer $cachedelay Do not rebuild file if date older than cachedelay seconds - * @param string $filename The name for the exported file. - * @param array $filters Array of filters. Example array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...) - * @param integer $exportholiday 0 = don't integrate holidays into the export, 1 = integrate holidays into the export - * @return integer -1 = error on build export file, 0 = export okay - */ - public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0) - { - global $hookmanager; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Export events from database into a cal file. + * + * @param string $format The format of the export 'vcal', 'ical/ics' or 'rss' + * @param string $type The type of the export 'event' or 'journal' + * @param integer $cachedelay Do not rebuild file if date older than cachedelay seconds + * @param string $filename The name for the exported file. + * @param array $filters Array of filters. Example array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...) + * @param integer $exportholiday 0 = don't integrate holidays into the export, 1 = integrate holidays into the export + * @return integer -1 = error on build export file, 0 = export okay + */ + public function build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholiday = 0) + { + global $hookmanager; - // phpcs:enable - global $conf, $langs, $dolibarr_main_url_root, $mysoc; + // phpcs:enable + global $conf, $langs, $dolibarr_main_url_root, $mysoc; - require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php"; - require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; - require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; - dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); + dol_syslog(get_class($this)."::build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); - // Check parameters - if (empty($format)) return -1; + // Check parameters + if (empty($format)) return -1; - // Clean parameters - if (!$filename) - { - $extension = 'vcs'; - if ($format == 'ical') $extension = 'ics'; - $filename = $format.'.'.$extension; - } + // Clean parameters + if (!$filename) + { + $extension = 'vcs'; + if ($format == 'ical') $extension = 'ics'; + $filename = $format.'.'.$extension; + } - // Create dir and define output file (definitive and temporary) - $result = dol_mkdir($conf->agenda->dir_temp); - $outputfile = $conf->agenda->dir_temp.'/'.$filename; + // Create dir and define output file (definitive and temporary) + $result = dol_mkdir($conf->agenda->dir_temp); + $outputfile = $conf->agenda->dir_temp.'/'.$filename; - $result = 0; + $result = 0; - $buildfile = true; - $login = ''; $logina = ''; $logind = ''; $logint = ''; + $buildfile = true; + $login = ''; $logina = ''; $logind = ''; $logint = ''; - $now = dol_now(); + $now = dol_now(); - if ($cachedelay) - { - $nowgmt = dol_now(); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) - { - dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); - $buildfile = false; - } - } + if ($cachedelay) + { + $nowgmt = dol_now(); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) + { + dol_syslog(get_class($this)."::build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); + $buildfile = false; + } + } - if ($buildfile) - { - // Build event array - $eventarray = array(); + if ($buildfile) + { + // Build event array + $eventarray = array(); - $sql = "SELECT a.id,"; - $sql .= " a.datep,"; // Start - $sql .= " a.datep2,"; // End - $sql .= " a.durationp,"; // deprecated - $sql .= " a.datec, a.tms as datem,"; - $sql .= " a.label, a.code, a.note, a.fk_action as type_id,"; - $sql .= " a.fk_soc,"; - $sql .= " a.fk_user_author, a.fk_user_mod,"; - $sql .= " a.fk_user_action,"; - $sql .= " a.fk_contact, a.percent as percentage,"; - $sql .= " a.fk_element, a.elementtype,"; - $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; - $sql .= " u.firstname, u.lastname, u.email,"; - $sql .= " s.nom as socname,"; - $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label"; - $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; + $sql = "SELECT a.id,"; + $sql .= " a.datep,"; // Start + $sql .= " a.datep2,"; // End + $sql .= " a.durationp,"; // deprecated + $sql .= " a.datec, a.tms as datem,"; + $sql .= " a.label, a.code, a.note, a.fk_action as type_id,"; + $sql .= " a.fk_soc,"; + $sql .= " a.fk_user_author, a.fk_user_mod,"; + $sql .= " a.fk_user_action,"; + $sql .= " a.fk_contact, a.percent as percentage,"; + $sql .= " a.fk_element, a.elementtype,"; + $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; + $sql .= " u.firstname, u.lastname, u.email,"; + $sql .= " s.nom as socname,"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label"; + $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; $parameters = array('filters' => $filters); $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook @@ -1600,129 +1633,129 @@ class ActionComm extends CommonObject // We must filter on assignement table if ($filters['logint']) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; $sql .= " WHERE a.fk_action=c.id"; - $sql .= " AND a.entity IN (".getEntity('agenda').")"; - foreach ($filters as $key => $value) - { - if ($key == 'notolderthan' && $value != '') $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'"; - if ($key == 'year') $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'"; - if ($key == 'id') $sql .= " AND a.id=".(is_numeric($value) ? $value : 0); - if ($key == 'idfrom') $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0); - if ($key == 'idto') $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0); - if ($key == 'project') $sql .= " AND a.fk_project=".(is_numeric($value) ? $value : 0); - if ($key == 'actiontype') $sql .= " AND c.type = '".$this->db->escape($value)."'"; - if ($key == 'notactiontype') $sql .= " AND c.type <> '".$this->db->escape($value)."'"; - // We must filter on assignement table + $sql .= " AND a.entity IN (".getEntity('agenda').")"; + foreach ($filters as $key => $value) + { + if ($key == 'notolderthan' && $value != '') $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'"; + if ($key == 'year') $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'"; + if ($key == 'id') $sql .= " AND a.id=".(is_numeric($value) ? $value : 0); + if ($key == 'idfrom') $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0); + if ($key == 'idto') $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0); + if ($key == 'project') $sql .= " AND a.fk_project=".(is_numeric($value) ? $value : 0); + if ($key == 'actiontype') $sql .= " AND c.type = '".$this->db->escape($value)."'"; + if ($key == 'notactiontype') $sql .= " AND c.type <> '".$this->db->escape($value)."'"; + // We must filter on assignement table if ($key == 'logint') $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; - if ($key == 'logina') - { - $logina = $value; - $condition = '='; - if (preg_match('/^!/', $logina)) - { - $logina = preg_replace('/^!/', '', $logina); - $condition = '<>'; - } - $userforfilter = new User($this->db); - $result = $userforfilter->fetch('', $logina); - if ($result > 0) $sql .= " AND a.fk_user_author ".$condition." ".$userforfilter->id; - elseif ($result < 0 || $condition == '=') $sql .= " AND a.fk_user_author = 0"; - } - if ($key == 'logint') - { - $logint = $value; - $condition = '='; - if (preg_match('/^!/', $logint)) - { - $logint = preg_replace('/^!/', '', $logint); - $condition = '<>'; - } - $userforfilter = new User($this->db); - $result = $userforfilter->fetch('', $logint); - if ($result > 0) $sql .= " AND ar.fk_element = ".$userforfilter->id; - elseif ($result < 0 || $condition == '=') $sql .= " AND ar.fk_element = 0"; - } - } + if ($key == 'logina') + { + $logina = $value; + $condition = '='; + if (preg_match('/^!/', $logina)) + { + $logina = preg_replace('/^!/', '', $logina); + $condition = '<>'; + } + $userforfilter = new User($this->db); + $result = $userforfilter->fetch('', $logina); + if ($result > 0) $sql .= " AND a.fk_user_author ".$condition." ".$userforfilter->id; + elseif ($result < 0 || $condition == '=') $sql .= " AND a.fk_user_author = 0"; + } + if ($key == 'logint') + { + $logint = $value; + $condition = '='; + if (preg_match('/^!/', $logint)) + { + $logint = preg_replace('/^!/', '', $logint); + $condition = '<>'; + } + $userforfilter = new User($this->db); + $result = $userforfilter->fetch('', $logint); + if ($result > 0) $sql .= " AND ar.fk_element = ".$userforfilter->id; + elseif ($result < 0 || $condition == '=') $sql .= " AND ar.fk_element = 0"; + } + } - $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import + $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import $parameters = array('filters' => $filters); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; - $sql .= " ORDER by datep"; - //print $sql;exit; + $sql .= " ORDER by datep"; + //print $sql;exit; - dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - // Note: Output of sql request is encoded in $conf->file->character_set_client - // This assignment in condition is not a bug. It allows walking the results. + dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + // Note: Output of sql request is encoded in $conf->file->character_set_client + // This assignment in condition is not a bug. It allows walking the results. $diff = 0; - while ($obj = $this->db->fetch_object($resql)) - { - $qualified = true; + while ($obj = $this->db->fetch_object($resql)) + { + $qualified = true; - // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author' - $event = array(); - $event['uid'] = 'dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"]; - $event['type'] = $type; - $datestart = $this->db->jdate($obj->datep) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); + // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author' + $event = array(); + $event['uid'] = 'dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"]; + $event['type'] = $type; + $datestart = $this->db->jdate($obj->datep) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); - // fix for -> Warning: A non-numeric value encountered - if (is_numeric($this->db->jdate($obj->datep2))) - { - $dateend = $this->db->jdate($obj->datep2) - - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); - } else { - // use start date as fall-back to avoid import erros on empty end date - $dateend = $datestart; - } + // fix for -> Warning: A non-numeric value encountered + if (is_numeric($this->db->jdate($obj->datep2))) + { + $dateend = $this->db->jdate($obj->datep2) + - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); + } else { + // use start date as fall-back to avoid import erros on empty end date + $dateend = $datestart; + } - $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0; - $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : ""); - $event['desc'] = $obj->note; - $event['startdate'] = $datestart; - $event['enddate'] = $dateend; // Not required with type 'journal' - $event['duration'] = $duration; // Not required with type 'journal' - $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname); - $event['priority'] = $obj->priority; - $event['fulldayevent'] = $obj->fulldayevent; - $event['location'] = $obj->location; - $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy) - $event['category'] = $obj->type_label; - $event['email'] = $obj->email; + $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0; + $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : ""); + $event['desc'] = $obj->note; + $event['startdate'] = $datestart; + $event['enddate'] = $dateend; // Not required with type 'journal' + $event['duration'] = $duration; // Not required with type 'journal' + $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname); + $event['priority'] = $obj->priority; + $event['fulldayevent'] = $obj->fulldayevent; + $event['location'] = $obj->location; + $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy) + $event['category'] = $obj->type_label; + $event['email'] = $obj->email; // 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 - $url = $urlwithroot.'/comm/action/card.php?id='.$obj->id; - $event['url'] = $url; - $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); - $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); + $url = $urlwithroot.'/comm/action/card.php?id='.$obj->id; + $event['url'] = $url; + $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); + $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); - // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties - $this->id = $obj->id; - $this->fetch_userassigned(false); + // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties + $this->id = $obj->id; + $this->fetch_userassigned(false); - $assignedUserArray = array(); + $assignedUserArray = array(); - foreach ($this->userassigned as $key => $value) - { - $assignedUser = new User($this->db); - $assignedUser->fetch($value['id']); + foreach ($this->userassigned as $key => $value) + { + $assignedUser = new User($this->db); + $assignedUser->fetch($value['id']); - $assignedUserArray[$key] = $assignedUser; - } + $assignedUserArray[$key] = $assignedUser; + } - $event['assignedUsers'] = $assignedUserArray; + $event['assignedUsers'] = $assignedUserArray; - if ($qualified && $datestart) - { - $eventarray[] = $event; - } - $diff++; - } + if ($qualified && $datestart) + { + $eventarray[] = $event; + } + $diff++; + } $parameters = array('filters' => $filters, 'eventarray' => &$eventarray); $reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook @@ -1730,175 +1763,175 @@ class ActionComm extends CommonObject { $eventarray = $hookmanager->resArray; } - } else { - $this->error = $this->db->lasterror(); - return -1; - } + } else { + $this->error = $this->db->lasterror(); + return -1; + } if ($exportholiday == 1) - { - $langs->load("holidays"); - $title = $langs->trans("Holidays"); + { + $langs->load("holidays"); + $title = $langs->trans("Holidays"); - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.email, 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.email, 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) - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $event = array(); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $event = array(); - if ($obj->halfday == -1) - { - $event['fulldayevent'] = false; + if ($obj->halfday == -1) + { + $event['fulldayevent'] = false; - $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0); - $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0); - } elseif ($obj->halfday == 1) - { - $event['fulldayevent'] = false; + $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0); + $timestampEnd = dol_stringtotime($obj->date_end." 12:00:00", 0); + } elseif ($obj->halfday == 1) + { + $event['fulldayevent'] = false; - $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0); - $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0); - } else { - $event['fulldayevent'] = true; + $timestampStart = dol_stringtotime($obj->date_start." 12:00:00", 0); + $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0); + } else { + $event['fulldayevent'] = true; - $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0); - $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0); - } + $timestampStart = dol_stringtotime($obj->date_start." 00:00:00", 0); + $timestampEnd = dol_stringtotime($obj->date_end." 23:59:59", 0); + } - if (!empty($conf->global->AGENDA_EXPORT_FIX_TZ)) - { - $timestampStart = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600); - $timestampEnd = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600); - } + if (!empty($conf->global->AGENDA_EXPORT_FIX_TZ)) + { + $timestampStart = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600); + $timestampEnd = - ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600); + } - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; - $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid; + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; + $url = $urlwithroot.'/holiday/card.php?id='.$obj->rowid; - $event['uid'] = 'dolibarrholiday-'.$this->db->database_name.'-'.$obj->rowid."@".$_SERVER["SERVER_NAME"]; - $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname); - $event['type'] = 'event'; - $event['category'] = "Holiday"; - $event['transparency'] = 'OPAQUE'; - $event['email'] = $obj->email; - $event['created'] = $timestampStart; - $event['modified'] = $timestampStart; - $event['startdate'] = $timestampStart; - $event['enddate'] = $timestampEnd; - $event['duration'] = $timestampEnd - $timestampStart; - $event['url'] = $url; + $event['uid'] = 'dolibarrholiday-'.$this->db->database_name.'-'.$obj->rowid."@".$_SERVER["SERVER_NAME"]; + $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname); + $event['type'] = 'event'; + $event['category'] = "Holiday"; + $event['transparency'] = 'OPAQUE'; + $event['email'] = $obj->email; + $event['created'] = $timestampStart; + $event['modified'] = $timestampStart; + $event['startdate'] = $timestampStart; + $event['enddate'] = $timestampEnd; + $event['duration'] = $timestampEnd - $timestampStart; + $event['url'] = $url; - if ($obj->status == 2) - { - // 2 = leave wait for approval - $event['summary'] = $title." - ".$obj->lastname." (wait for approval)"; - } else { - // 3 = leave approved - $event['summary'] = $title." - ".$obj->lastname; - } + if ($obj->status == 2) + { + // 2 = leave wait for approval + $event['summary'] = $title." - ".$obj->lastname." (wait for approval)"; + } else { + // 3 = leave approved + $event['summary'] = $title." - ".$obj->lastname; + } - $eventarray[] = $event; + $eventarray[] = $event; - $i++; - } - } - } + $i++; + } + } + } - $langs->load("agenda"); + $langs->load("agenda"); - // Define title and desc - $more = ''; - if ($login) $more = $langs->transnoentities("User").' '.$login; - if ($logina) $more = $langs->transnoentities("ActionsAskedBy").' '.$logina; - if ($logint) $more = $langs->transnoentities("ActionsToDoBy").' '.$logint; - if ($logind) $more = $langs->transnoentities("ActionsDoneBy").' '.$logind; - if ($more) - { - $title = 'Dolibarr actions '.$mysoc->name.' - '.$more; - $desc = $more; - $desc .= ' ('.$mysoc->name.' - built by Dolibarr)'; - } else { - $title = 'Dolibarr actions '.$mysoc->name; - $desc = $langs->transnoentities('ListOfActions'); - $desc .= ' ('.$mysoc->name.' - built by Dolibarr)'; - } + // Define title and desc + $more = ''; + if ($login) $more = $langs->transnoentities("User").' '.$login; + if ($logina) $more = $langs->transnoentities("ActionsAskedBy").' '.$logina; + if ($logint) $more = $langs->transnoentities("ActionsToDoBy").' '.$logint; + if ($logind) $more = $langs->transnoentities("ActionsDoneBy").' '.$logind; + if ($more) + { + $title = 'Dolibarr actions '.$mysoc->name.' - '.$more; + $desc = $more; + $desc .= ' ('.$mysoc->name.' - built by Dolibarr)'; + } else { + $title = 'Dolibarr actions '.$mysoc->name; + $desc = $langs->transnoentities('ListOfActions'); + $desc .= ' ('.$mysoc->name.' - built by Dolibarr)'; + } - // Create temp file - $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads - @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK)); + // Create temp file + $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp'); // Temporary file (allow call of function by different threads + @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK)); - // Write file - if ($format == 'vcal') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); - elseif ($format == 'ical') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); - elseif ($format == 'rss') $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp); + // Write file + if ($format == 'vcal') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); + elseif ($format == 'ical') $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); + elseif ($format == 'rss') $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp); - if ($result >= 0) - { - if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1; - else { - $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile; - dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR); - dol_delete_file($outputfiletmp, 0, 1); - $result = -1; - } - } else { - dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); - dol_delete_file($outputfiletmp, 0, 1); - $langs->load("errors"); - $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile); - } - } + if ($result >= 0) + { + if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1; + else { + $this->error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile; + dol_syslog(get_class($this)."::build_exportfile ".$this->error, LOG_ERR); + dol_delete_file($outputfiletmp, 0, 1); + $result = -1; + } + } else { + dol_syslog(get_class($this)."::build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); + dol_delete_file($outputfiletmp, 0, 1); + $langs->load("errors"); + $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile); + } + } - return $result; - } + return $result; + } - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return int >0 if ok - */ - public function initAsSpecimen() - { - global $user; + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return int >0 if ok + */ + public function initAsSpecimen() + { + global $user; - $now = dol_now(); + $now = dol_now(); - // Initialise parametres - $this->id = 0; - $this->specimen = 1; + // Initialise parametres + $this->id = 0; + $this->specimen = 1; - $this->type_code = 'AC_OTH'; - $this->code = 'AC_SPECIMEN_CODE'; - $this->label = 'Label of event Specimen'; - $this->datec = $now; - $this->datem = $now; - $this->datep = $now; - $this->datef = $now; - $this->fulldayevent = 0; - $this->percentage = 0; - $this->location = 'Location'; - $this->transparency = 1; // 1 means opaque - $this->priority = 1; - //$this->note_public = "This is a 'public' note."; + $this->type_code = 'AC_OTH'; + $this->code = 'AC_SPECIMEN_CODE'; + $this->label = 'Label of event Specimen'; + $this->datec = $now; + $this->datem = $now; + $this->datep = $now; + $this->datef = $now; + $this->fulldayevent = 0; + $this->percentage = 0; + $this->location = 'Location'; + $this->transparency = 1; // 1 means opaque + $this->priority = 1; + //$this->note_public = "This is a 'public' note."; $this->note_private = "This is a 'private' note."; - $this->userownerid = $user->id; - $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1); - return 1; - } + $this->userownerid = $user->id; + $this->userassigned[$user->id] = array('id'=>$user->id, 'transparency'=> 1); + return 1; + } /** * Function used to replace a thirdparty id with another one. @@ -1917,64 +1950,225 @@ class ActionComm extends CommonObject return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } - /** - * Is the action delayed? - * - * @return bool - */ - public function hasDelay() - { - global $conf; + /** + * Is the action delayed? + * + * @return bool + */ + public function hasDelay() + { + global $conf; - $now = dol_now(); + $now = dol_now(); - return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); - } + return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay)); + } - /** - * Send reminders by emails - * CAN BE A CRON TASK - * - * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) - */ - public function sendEmailsReminder() - { - global $conf, $langs; + /** + * Load event reminder of events + * + * @param string $type Type of reminder 'browser' or 'email' + * @param int $fk_user Id of user + * @param bool $onlypast true = get only past reminder, false = get all reminders linked to this + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function loadReminders($type = '', $fk_user = 0, $onlypast = true) + { + global $conf, $langs, $user; - $error = 0; - $this->output = ''; + $error = 0; + + $this->reminders = array(); + + //Select all action comm reminders for event + $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + $sql .= " WHERE fk_actioncomm = ".$this->id; + if ($onlypast) { + $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'"; + } + if ($type) { + $sql .= " AND typeremind ='".$this->db->escape($type)."'"; + } + if ($fk_user > 0) { + $sql .= " AND fk_user = ".((int) $fk_user); + } + if (empty($conf->global->AGENDA_REMINDER_EMAIL)) $sql .= " AND typeremind != 'email'"; + if (empty($conf->global->AGENDA_REMINDER_BROWSER)) $sql .= " AND typeremind != 'browser'"; + + $sql .= $this->db->order("dateremind", "ASC"); + $resql = $this->db->query($sql); + + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + $tmpactioncommreminder = new ActionCommReminder($this->db); + $tmpactioncommreminder->id = $obj->id; + $tmpactioncommreminder->typeremind = $obj->typeremind; + $tmpactioncommreminder->dateremind = $obj->dateremind; + $tmpactioncommreminder->offsetvalue = $obj->offsetvalue; + $tmpactioncommreminder->offsetunit = $obj->offsetunit; + $tmpactioncommreminder->status = $obj->status; + $tmpactioncommreminder->fk_user = $obj->fk_user; + + $this->reminders[$obj->id] = $tmpactioncommreminder; + } + } else { + $this->error = $this->db->lasterror(); + $error++; + } + + return count($this->reminders); + } + + + /** + * Send reminders by emails + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function sendEmailsReminder() + { + global $conf, $langs, $user; + + $error = 0; + $this->output = ''; $this->error = ''; + $nbMailSend = 0; + $errorsMsg = array(); - if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. + if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible. { $langs->load("agenda"); $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda")); return 0; } if (empty($conf->global->AGENDA_REMINDER_EMAIL)) - { - $langs->load("agenda"); - $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); - return 0; - } + { + $langs->load("agenda"); + $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda")); + return 0; + } - $now = dol_now(); + $now = dol_now(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $this->db->begin(); + $this->db->begin(); - // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done + //Select all action comm reminder + $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + $sql .= " WHERE typeremind = 'email' AND status = 0"; + $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'"; + $sql .= $this->db->order("dateremind", "ASC"); + $resql = $this->db->query($sql); - // Delete also very old past events (we do not keep more than 1 month record in past) - $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'"; - $this->db->query($sql); + if ($resql) { + $formmail = new FormMail($this->db); + $actionCommReminder = new ActionCommReminder($this->db); - $this->db->commit(); + while ($obj = $this->db->fetch_object($resql)) { + $res = $actionCommReminder->fetch($obj->id); + if ($res < 0) { + $error++; + $errorsMsg[] = "Failed to load invoice ActionComm Reminder"; + } - return $error; - } + if (!$error) + { + //Select email template + $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1); + + // Load event + $res = $this->fetch($actionCommReminder->fk_actioncomm); + if ($res > 0) + { + // PREPARE EMAIL + + // Make substitution in email content + $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this); + + complete_substitutions_array($substitutionarray, $langs, $this); + + // Content + $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray); + + //Topic + $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder')); + + // Recipient + $recipient = new User($this->db); + $res = $recipient->fetch($actionCommReminder->fk_user); + if ($res > 0 && !empty($recipient->email)) $to = $recipient->email; + else { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } + + // Sender + $from = $conf->global->MAIN_MAIL_EMAIL_FROM; + if (empty($from)) { + $errorsMsg[] = "Failed to load recipient"; + $error++; + } + + // Errors Recipient + $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO; + + // Mail Creation + $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', ''); + + // Sending Mail + if ($cMailFile->sendfile()) + { + $actionCommReminder->status = $actionCommReminder::STATUS_DONE; + $res = $actionCommReminder->update($user); + if ($res < 0) + { + $errorsMsg[] = "Failed to update status of ActionComm Reminder"; + $error++; + break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first. + } else { + $nbMailSend++; + } + } else { + $errorsMsg[] = $cMailFile->error.' : '.$to; + $error++; + } + } else { + $error++; + } + } + } + } else { + $error++; + } + + if (!$error) + { + // Delete also very old past events (we do not keep more than 1 month record in past) + $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; + $sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'"; + $resql = $this->db->query($sql); + + if (!$resql) { + $errorsMsg[] = 'Failed to delete old reminders'; + //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind. + } + } + + if (!$error) { + $this->output = 'Nb of emails sent : '.$nbMailSend; + $this->db->commit(); + return 0; + } + else { + $this->db->rollback(); + $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error; + return $error; + } + } /** * Udpate the percent value of a event with the given id diff --git a/htdocs/comm/action/class/actioncommreminder.class.php b/htdocs/comm/action/class/actioncommreminder.class.php index d3f4fb3f238..16384edfcde 100644 --- a/htdocs/comm/action/class/actioncommreminder.class.php +++ b/htdocs/comm/action/class/actioncommreminder.class.php @@ -50,6 +50,9 @@ class ActionCommReminder extends CommonObject */ public $picto = 'generic'; + const STATUS_TODO = 0; + const STATUS_DONE = 1; + /** * 'type' if the field format. @@ -74,12 +77,15 @@ class ActionCommReminder extends CommonObject */ public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), - 'dateremind' => array('type'=>'datetime', 'label'=>'DateRemind', 'visible'=>1, 'enabled'=>1, 'position'=>60, 'notnull'=>1, 'index'=>1,), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), + 'dateremind' => array('type'=>'datetime', 'label'=>'DateRemind', 'visible'=>1, 'enabled'=>1, 'position'=>60, 'notnull'=>1, 'index'=>1,), 'typeremind' => array('type'=>'varchar(32)', 'label'=>'TypeRemind', 'visible'=>-1, 'enabled'=>1, 'position'=>55, 'notnull'=>1, 'comment'=>"email, browser, sms",), 'fk_user' => array('type'=>'integer', 'label'=>'User', 'visible'=>-1, 'enabled'=>1, 'position'=>65, 'notnull'=>1, 'index'=>1,), 'offsetvalue' => array('type'=>'integer', 'label'=>'OffsetValue', 'visible'=>1, 'enabled'=>1, 'position'=>56, 'notnull'=>1,), - 'offsetunit' => array('type'=>'varchar(1)', 'label'=>'OffsetUnit', 'visible'=>1, 'enabled'=>1, 'position'=>57, 'notnull'=>1, 'comment'=>"m, h, d, w",), - 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>0, 'arrayofkeyval'=>array('0'=>'ToDo', '1'=>'Done')), + 'offsetunit' => array('type'=>'varchar(1)', 'label'=>'OffsetUnit', 'visible'=>1, 'enabled'=>1, 'position'=>57, 'notnull'=>1, 'comment'=>"y, m, d, w, h, i",), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>58, 'notnull'=>1, 'default'=>0, 'index'=>0, 'arrayofkeyval'=>array('0'=>'ToDo', '1'=>'Done')), + 'fk_actioncomm' => array('type'=>'integer', 'label'=>'Project', 'visible'=>1, 'enabled'=>1, 'position'=>59, 'notnull'=>1, 'index'=>1,), + 'fk_email_template' => array('type'=>'integer', 'label'=>'EmailTemplate', 'visible'=>1, 'enabled'=>1, 'position'=>60, 'notnull'=>0), ); /** @@ -87,6 +93,11 @@ class ActionCommReminder extends CommonObject */ public $rowid; + /** + * @var int Entity + */ + public $entity; + public $dateremind; public $typeremind; @@ -103,6 +114,16 @@ class ActionCommReminder extends CommonObject */ public $status; + /** + * @var int Project + */ + public $fk_actioncomm; + + /** + * @var int Template Mail + */ + public $fk_email_template; + // END MODULEBUILDER PROPERTIES diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index 43d880b3866..473c87e22a0 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -148,7 +148,7 @@ class AgendaEvents extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -156,27 +156,27 @@ class AgendaEvents extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { $i = 0; - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) { - $obj = $db->fetch_object($result); - $actioncomm_static = new ActionComm($db); + $obj = $this->db->fetch_object($result); + $actioncomm_static = new ActionComm($this->db); if ($actioncomm_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($actioncomm_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve Agenda Event list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No Agenda Event found'); diff --git a/htdocs/comm/action/class/cactioncomm.class.php b/htdocs/comm/action/class/cactioncomm.class.php index 147a6ff7ef0..6e86a556a1a 100644 --- a/htdocs/comm/action/class/cactioncomm.class.php +++ b/htdocs/comm/action/class/cactioncomm.class.php @@ -139,7 +139,7 @@ class CActionComm $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; $sql .= " WHERE 1=1"; if ($active != '') $sql .= " AND active=".$active; - if (!empty($excludetype)) $sql .= " AND type <> '".$excludetype."'"; + if (!empty($excludetype)) $sql .= " AND type <> '".$this->db->escape($excludetype)."'"; if ($morefilter) $sql .= " AND ".$morefilter; $sql .= " ORDER BY module, position, type"; diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 028de1e6fb7..bed4054e018 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -40,7 +40,7 @@ if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/clas $langs->loadLangs(array('companies', 'commercial', 'other', 'bills')); $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 97d732f6908..a48dc03aea2 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -76,10 +76,10 @@ 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; + $filtert = $user->id; } -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $resourceid = GETPOST("search_resourceid", "int"); $year = GETPOST("year", "int") ?GETPOST("year", "int") : date("Y"); $month = GETPOST("month", "int") ?GETPOST("month", "int") : date("m"); @@ -91,19 +91,19 @@ $type = GETPOST("search_type", 'aZ09') ?GETPOST("search_type", 'aZ09') : GETPOST $maxprint = (isset($_GET["maxprint"]) ?GETPOST("maxprint") : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') -$dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); +$dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); if ($dateselect > 0) { - $day=GETPOST('dateselectday', 'int'); - $month=GETPOST('dateselectmonth', 'int'); - $year=GETPOST('dateselectyear', 'int'); + $day = GETPOST('dateselectday', 'int'); + $month = GETPOST('dateselectmonth', 'int'); + $year = GETPOST('dateselectyear', 'int'); } // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) if (GETPOST('search_actioncode', 'array')) { - $actioncode = GETPOST('search_actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + $actioncode = GETPOST('search_actioncode', 'array', 3); + 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)); } @@ -118,14 +118,14 @@ if ($action == 'default') // When action is default, we want a calendar view and { $action = (($defaultview != 'show_list') ? $defaultview : 'show_month'); } -if (GETPOST('viewcal', 'none') && GETPOST('action', 'alpha') != 'show_day' && GETPOST('action', 'alpha') != 'show_week') { - $action = 'show_month'; $day = ''; +if (GETPOST('viewcal', 'restricthtml') && GETPOST('action', 'alpha') != 'show_day' && GETPOST('action', 'alpha') != 'show_week') { + $action = 'show_month'; $day = ''; } // View by month -if (GETPOST('viewweek', 'none') || GETPOST('action', 'alpha') == 'show_week') { - $action = 'show_week'; $week = ($week ? $week : date("W")); $day = ($day ? $day : date("d")); +if (GETPOST('viewweek', 'restricthtml') || GETPOST('action', 'alpha') == 'show_week') { + $action = 'show_week'; $week = ($week ? $week : date("W")); $day = ($day ? $day : date("d")); } // View by week -if (GETPOST('viewday', 'none') || GETPOST('action', 'alpha') == 'show_day') { - $action = 'show_day'; $day = ($day ? $day : date("d")); +if (GETPOST('viewday', 'restricthtml') || GETPOST('action', 'alpha') == 'show_day') { + $action = 'show_day'; $day = ($day ? $day : date("d")); } // View by day // Load translation files required by the page @@ -141,46 +141,46 @@ $hookmanager->initHooks(array('agenda')); if (GETPOST("viewlist", 'alpha') || $action == 'show_list') { - $param = ''; - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { - if ($key == 'token') continue; - $param .= '&'.$key.'='.urlencode($val); - } - } - if (! preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; - //print $param; - header("Location: ".DOL_URL_ROOT.'/comm/action/list.php?'.$param); - exit; + $param = ''; + if (is_array($_POST)) + { + foreach ($_POST as $key => $val) + { + if ($key == 'token') continue; + $param .= '&'.$key.'='.urlencode($val); + } + } + if (!preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list'; + //print $param; + header("Location: ".DOL_URL_ROOT.'/comm/action/list.php?'.$param); + exit; } if (GETPOST("viewperuser", 'alpha') || $action == 'show_peruser') { - $param = ''; - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { - if ($key == 'token') continue; - $param .= '&'.$key.'='.urlencode($val); - } - } - //print $param; - header("Location: ".DOL_URL_ROOT.'/comm/action/peruser.php?'.$param); - exit; + $param = ''; + if (is_array($_POST)) + { + foreach ($_POST as $key => $val) + { + if ($key == 'token') continue; + $param .= '&'.$key.'='.urlencode($val); + } + } + //print $param; + header("Location: ".DOL_URL_ROOT.'/comm/action/peruser.php?'.$param); + exit; } if ($action == 'delete_action') { - $event = new ActionComm($db); - $event->fetch($actionid); - $event->fetch_optionals(); - $event->fetch_userassigned(); - $event->oldcopy = clone $event; + $event = new ActionComm($db); + $event->fetch($actionid); + $event->fetch_optionals(); + $event->fetch_userassigned(); + $event->oldcopy = clone $event; - $result = $event->delete(); + $result = $event->delete(); } @@ -226,21 +226,21 @@ $listofextcals = array(); // Define list of external calendars (global admin setup) if (empty($conf->global->AGENDA_DISABLE_EXT)) { - $i = 0; - while ($i < $MAXAGENDA) - { - $i++; - $source = 'AGENDA_EXT_SRC'.$i; - $name = 'AGENDA_EXT_NAME'.$i; - $offsettz = 'AGENDA_EXT_OFFSETTZ'.$i; - $color = 'AGENDA_EXT_COLOR'.$i; - $buggedfile = 'AGENDA_EXT_BUGGEDFILE'.$i; - if (!empty($conf->global->$source) && !empty($conf->global->$name)) - { - // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' - $listofextcals[] = array('src'=>$conf->global->$source, 'name'=>$conf->global->$name, 'offsettz'=>$conf->global->$offsettz, 'color'=>$conf->global->$color, 'buggedfile'=>(isset($conf->global->buggedfile) ? $conf->global->buggedfile : 0)); - } - } + $i = 0; + while ($i < $MAXAGENDA) + { + $i++; + $source = 'AGENDA_EXT_SRC'.$i; + $name = 'AGENDA_EXT_NAME'.$i; + $offsettz = 'AGENDA_EXT_OFFSETTZ'.$i; + $color = 'AGENDA_EXT_COLOR'.$i; + $buggedfile = 'AGENDA_EXT_BUGGEDFILE'.$i; + if (!empty($conf->global->$source) && !empty($conf->global->$name)) + { + // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' + $listofextcals[] = array('src'=>$conf->global->$source, 'name'=>$conf->global->$name, 'offsettz'=>$conf->global->$offsettz, 'color'=>$conf->global->$color, 'buggedfile'=>(isset($conf->global->buggedfile) ? $conf->global->buggedfile : 0)); + } + } } // Define list of external calendars (user setup) if (empty($user->conf->AGENDA_DISABLE_EXT)) @@ -251,7 +251,7 @@ if (empty($user->conf->AGENDA_DISABLE_EXT)) $i++; $source = 'AGENDA_EXT_SRC_'.$user->id.'_'.$i; $name = 'AGENDA_EXT_NAME_'.$user->id.'_'.$i; - $offsettz = 'AGENDA_EXT_OFFSETTZ_'.$user->id.'_'.$i; + $offsettz = 'AGENDA_EXT_OFFSETTZ_'.$user->id.'_'.$i; $color = 'AGENDA_EXT_COLOR_'.$user->id.'_'.$i; $enabled = 'AGENDA_EXT_ENABLED_'.$user->id.'_'.$i; $buggedfile = 'AGENDA_EXT_BUGGEDFILE_'.$user->id.'_'.$i; @@ -265,65 +265,65 @@ if (empty($user->conf->AGENDA_DISABLE_EXT)) if (empty($action) || $action == 'show_month') { - $prev = dol_get_prev_month($month, $year); - $prev_year = $prev['year']; - $prev_month = $prev['month']; - $next = dol_get_next_month($month, $year); - $next_year = $next['year']; - $next_month = $next['month']; + $prev = dol_get_prev_month($month, $year); + $prev_year = $prev['year']; + $prev_month = $prev['month']; + $next = dol_get_next_month($month, $year); + $next_year = $next['year']; + $next_month = $next['month']; - $max_day_in_prev_month = date("t", dol_mktime(0, 0, 0, $prev_month, 1, $prev_year)); // Nb of days in previous month - $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); // Nb of days in next month - // tmpday is a negative or null cursor to know how many days before the 1st to show on month view (if tmpday=0, 1st is monday) - $tmpday = -date("w", dol_mktime(12, 0, 0, $month, 1, $year, true)) + 2; // date('w') is 0 fo sunday - $tmpday += ((isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1) - 1); - if ($tmpday >= 1) $tmpday -= 7; // If tmpday is 0 we start with sunday, if -6, we start with monday of previous week. - // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $max_day_in_prev_month + $tmpday, $prev_year); - $next_day = 7 - ($max_day_in_month + 1 - $tmpday) % 7; - if ($next_day < 6) $next_day += 7; - $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); + $max_day_in_prev_month = date("t", dol_mktime(0, 0, 0, $prev_month, 1, $prev_year)); // Nb of days in previous month + $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); // Nb of days in next month + // tmpday is a negative or null cursor to know how many days before the 1st to show on month view (if tmpday=0, 1st is monday) + $tmpday = -date("w", dol_mktime(12, 0, 0, $month, 1, $year, true)) + 2; // date('w') is 0 fo sunday + $tmpday += ((isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1) - 1); + if ($tmpday >= 1) $tmpday -= 7; // If tmpday is 0 we start with sunday, if -6, we start with monday of previous week. + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) + $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $max_day_in_prev_month + $tmpday, $prev_year); + $next_day = 7 - ($max_day_in_month + 1 - $tmpday) % 7; + if ($next_day < 6) $next_day += 7; + $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); } if ($action == 'show_week') { - $prev = dol_get_first_day_week($day, $month, $year); - $prev_year = $prev['prev_year']; - $prev_month = $prev['prev_month']; - $prev_day = $prev['prev_day']; - $first_day = $prev['first_day']; - $first_month = $prev['first_month']; - $first_year = $prev['first_year']; + $prev = dol_get_first_day_week($day, $month, $year); + $prev_year = $prev['prev_year']; + $prev_month = $prev['prev_month']; + $prev_day = $prev['prev_day']; + $first_day = $prev['first_day']; + $first_month = $prev['first_month']; + $first_year = $prev['first_year']; - $week = $prev['week']; + $week = $prev['week']; - $day = (int) $day; - $next = dol_get_next_week($first_day, $week, $first_month, $first_year); - $next_year = $next['year']; - $next_month = $next['month']; - $next_day = $next['day']; + $day = (int) $day; + $next = dol_get_next_week($first_day, $week, $first_month, $first_year); + $next_year = $next['year']; + $next_month = $next['month']; + $next_day = $next['day']; - // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) + $firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year); $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); - $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); + $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); - $tmpday = $first_day; + $tmpday = $first_day; } if ($action == 'show_day') { - $prev = dol_get_prev_day($day, $month, $year); - $prev_year = $prev['year']; - $prev_month = $prev['month']; - $prev_day = $prev['day']; - $next = dol_get_next_day($day, $month, $year); - $next_year = $next['year']; - $next_month = $next['month']; - $next_day = $next['day']; + $prev = dol_get_prev_day($day, $month, $year); + $prev_year = $prev['year']; + $prev_month = $prev['month']; + $prev_day = $prev['day']; + $next = dol_get_next_day($day, $month, $year); + $next_year = $next['year']; + $next_month = $next['month']; + $next_day = $next['day']; - // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) - $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $prev_day, $prev_year); - $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) + $firstdaytoshow = dol_mktime(0, 0, 0, $prev_month, $prev_day, $prev_year); + $lastdaytoshow = dol_mktime(0, 0, 0, $next_month, $next_day, $next_year); } //print 'xx'.$prev_year.'-'.$prev_month.'-'.$prev_day; //print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; @@ -356,30 +356,30 @@ $param .= "&maxprint=".urlencode($maxprint); // Show navigation bar if (empty($action) || $action == 'show_month') { - $nav = "  \n"; - $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%b %Y"); - $nav .= " \n"; - $nav .= "   \n"; - $nav .= "   ".$langs->trans("Today")." "; - $picto = 'calendar'; + $nav = "  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%b %Y"); + $nav .= " \n"; + $nav .= "   \n"; + $nav .= "   ".$langs->trans("Today")." "; + $picto = 'calendar'; } if ($action == 'show_week') { - $nav = "trans("Previous"))."\">  \n"; - $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; - $nav .= " \n"; - $nav .= "   trans("Next"))."\">\n"; - $nav .= "   ".$langs->trans("Today")." "; - $picto = 'calendarweek'; + $nav = "trans("Previous"))."\">  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y").", ".$langs->trans("Week")." ".$week; + $nav .= " \n"; + $nav .= "   trans("Next"))."\">\n"; + $nav .= "   ".$langs->trans("Today")." "; + $picto = 'calendarweek'; } if ($action == 'show_day') { - $nav = "  \n"; - $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "daytextshort"); - $nav .= " \n"; - $nav .= "   \n"; - $nav .= "   ".$langs->trans("Today")." "; - $picto = 'calendarday'; + $nav = "  \n"; + $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $month, $day, $year), "daytextshort"); + $nav .= " \n"; + $nav .= "   \n"; + $nav .= "   ".$langs->trans("Today")." "; + $picto = 'calendarday'; } $nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); @@ -398,6 +398,8 @@ if ($action == 'show_month') $tabactive = 'cardmonth'; if ($action == 'show_week') $tabactive = 'cardweek'; if ($action == 'show_day') $tabactive = 'cardday'; if ($action == 'show_list') $tabactive = 'cardlist'; +if ($action == 'show_pertuser') $tabactive = 'cardperuser'; +if ($action == 'show_pertype') $tabactive = 'cardpertype'; $paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); @@ -467,25 +469,25 @@ if (!empty($conf->use_javascript_ajax)) // If javascript on $s .= "\n".''."\n"; $s .= ''."\n"; + $s .= '});'."\n"; + } + $s .= '});'."\n"; + $s .= ''."\n"; // Local calendar $s .= '
'.$langs->trans("LocalAgenda").'  
'; @@ -510,29 +512,29 @@ if (!empty($conf->use_javascript_ajax)) // If javascript on } // Birthdays - $s .= '
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; + $s .= '
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; // Calendars from hooks - $parameters = array(); $object = null; + $parameters = array(); $object = null; $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); - if (empty($reshook)) - { - $s .= $hookmanager->resPrint; - } elseif ($reshook > 1) + if (empty($reshook)) { - $s = $hookmanager->resPrint; - } + $s .= $hookmanager->resPrint; + } elseif ($reshook > 1) + { + $s = $hookmanager->resPrint; + } } 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'; - $link = ''; - if (empty($showbirthday)) $link .= $langs->trans("AgendaShowBirthdayEvents"); - else $link .= $langs->trans("AgendaHideBirthdayEvents"); - $link .= ''; + $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 .= ''; } // Load events from database into $eventarray @@ -561,26 +563,26 @@ $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'"; - } - } 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)) - { - $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; - } else { - $sql .= " AND ca.code IN ('".implode("','", explode(',', $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)) + { + $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; + } else { + $sql .= " AND ca.code IN ('".implode("','", explode(',', $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); @@ -590,28 +592,28 @@ if ($socid > 0) $sql .= ' AND a.fk_soc = '.$socid; if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; if ($action == 'show_day') { - $sql .= " AND ("; - $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql .= " OR "; - $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql .= " OR "; - $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; - $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; - $sql .= ')'; + $sql .= " AND ("; + $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= " OR "; + $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= " OR "; + $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."'"; + $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."')"; + $sql .= ')'; } else { - // To limit array - $sql .= " AND ("; - $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; // Start 7 days before - $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; // End 7 days after + 3 to go from 28 to 31 - $sql .= " OR "; - $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; - $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; - $sql .= " OR "; - $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; - $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; - $sql .= ')'; + // To limit array + $sql .= " AND ("; + $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; // Start 7 days before + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; // End 7 days after + 3 to go from 28 to 31 + $sql .= " OR "; + $sql .= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; + $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; + $sql .= " OR "; + $sql .= " (a.datep < '".$db->idate(dol_mktime(0, 0, 0, $month, 1, $year) - (60 * 60 * 24 * 7))."'"; + $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"; } @@ -622,10 +624,10 @@ if ($status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } // We must filter on assignement table 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; - $sql .= ")"; + $sql .= " AND ("; + if ($filtert > 0) $sql .= "ar.fk_element = ".$filtert; + if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + $sql .= ")"; } // Sort on date $sql .= ' ORDER BY datep'; @@ -636,487 +638,518 @@ dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($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) - { - $obj = $db->fetch_object($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) + { + $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') - { - $i++; - continue; - } + // Discard auto action if option is on + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + { + $i++; + continue; + } - // Create a new object action - $event = new ActionComm($db); + // Create a new object action + $event = new ActionComm($db); - $event->id = $obj->id; - $event->ref = $event->id; + $event->id = $obj->id; + $event->ref = $event->id; - $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin - $event->datef = $db->jdate($obj->datep2); + $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin + $event->datef = $db->jdate($obj->datep2); //var_dump($obj->datep); - //var_dump($event->datep); + //var_dump($event->datep); - $event->type_code = $obj->type_code; - $event->type_label = $obj->type_label; - $event->type_color = $obj->type_color; + $event->type_code = $obj->type_code; + $event->type_label = $obj->type_label; + $event->type_color = $obj->type_color; - $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; - $event->transparency = $obj->transparency; - $event->fk_element = $obj->fk_element; - $event->elementtype = $obj->elementtype; + $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; + $event->transparency = $obj->transparency; + $event->fk_element = $obj->fk_element; + $event->elementtype = $obj->elementtype; - $event->fk_project = $obj->fk_project; + $event->fk_project = $obj->fk_project; - $event->thirdparty_id = $obj->fk_soc; - $event->contact_id = $obj->fk_contact; + $event->thirdparty_id = $obj->fk_soc; + $event->contact_id = $obj->fk_contact; - // 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; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - } + // 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; + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel = 1; + } - // Check values - 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); + // Check values + 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); - // 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); + // 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); - // Loop on each day covered by action to prepare an index to show on calendar - $loop = true; $j = 0; - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; + // Loop on each day covered by action to prepare an index to show on calendar + $loop = true; $j = 0; + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + do { + //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
'; - $eventarray[$daykey][] = $event; - $j++; + $eventarray[$daykey][] = $event; + $j++; - $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; - } while ($loop); + $daykey += 60 * 60 * 24; + 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); - //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; - } - $i++; - } + //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); + //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
'; + } + $i++; + } } else { - dol_print_error($db); + dol_print_error($db); } // Complete $eventarray with birthdates 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') - { - $sql .= ' AND MONTH(birthday) = '.$month; - $sql .= ' AND DAY(birthday) = '.$day; - } else { - $sql .= ' AND MONTH(birthday) = '.$month; - } - $sql .= ' ORDER BY birthday'; + // 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') + { + $sql .= ' AND MONTH(birthday) = '.$month; + $sql .= ' AND DAY(birthday) = '.$day; + } else { + $sql .= ' AND MONTH(birthday) = '.$month; + } + $sql .= ' ORDER BY birthday'; - dol_syslog("comm/action/index.php", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $event = new ActionComm($db); + dol_syslog("comm/action/index.php", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + 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 - $event->ref = $event->id; + $event->id = $obj->rowid; // We put contact id in action id for birthdays events + $event->ref = $event->id; - $datebirth = dol_stringtotime($obj->birthday, 1); - //print 'ee'.$obj->birthday.'-'.$datebirth; - $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->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname); - $event->percentage = 100; - $event->fulldayevent = 1; + $datebirth = dol_stringtotime($obj->birthday, 1); + //print 'ee'.$obj->birthday.'-'.$datebirth; + $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->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->ponctuel = 0; + $event->date_start_in_calendar = $event->datep; + $event->date_end_in_calendar = $event->datef; + $event->ponctuel = 0; - // 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); + // 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); - $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 { - dol_print_error($db); - } + $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 { + dol_print_error($db); + } } 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 '".$year."-".$month."-".$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"; + } 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); + $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->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->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; - 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->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; - } + 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; + } - $annee = date('Y', $event->date_start_in_calendar); - $mois = date('m', $event->date_start_in_calendar); - $jour = date('d', $event->date_start_in_calendar); - $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); + $annee = date('Y', $event->date_start_in_calendar); + $mois = date('m', $event->date_start_in_calendar); + $jour = date('d', $event->date_start_in_calendar); + $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee); - do { - $eventarray[$daykey][] = $event; + do { + $eventarray[$daykey][] = $event; - $daykey += 60 * 60 * 24; - } while ($daykey <= $event->date_end_in_calendar); + $daykey += 60 * 60 * 24; + } while ($daykey <= $event->date_end_in_calendar); - $i++; - } - } + $i++; + } + } } // Complete $eventarray with external import Ical if (count($listofextcals)) { - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; - 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); + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; + 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'] + // 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 (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 - { - //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 - { - $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'])) - { - $datecurstart = $icalevent['DTSTART']['unixtime']; - $datecurend = $icalevent['DTEND']['unixtime']; - if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) - { - //var_dump($ical->cal); - $tmpcurstart = $datecurstart; - $tmpcurend = $datecurend; - $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; - $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; - } - // datecurstart and datecurend are now GMT date - //var_dump($datecurstart); var_dump($datecurend); exit; - } else { - // Not a recongized record - dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); - continue; - } - //print 'xx'.$datecurstart;exit; + 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 + { + //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 + { + $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'])) + { + $datecurstart = $icalevent['DTSTART']['unixtime']; + $datecurend = $icalevent['DTEND']['unixtime']; + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) + { + //var_dump($ical->cal); + $tmpcurstart = $datecurstart; + $tmpcurend = $datecurend; + $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART']; + $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; + } + // datecurstart and datecurend are now GMT date + //var_dump($datecurstart); var_dump($datecurend); exit; + } else { + // Not a recongized record + dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR); + continue; + } + //print 'xx'.$datecurstart;exit; - $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 + $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 - $numofevent = 0; - while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) - { - if ($datecurend >= $firstdaytoshow) // We add event - { - $newevent = $icalevent; - unset($newevent['RRULE']); - 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 { - $newevent['DTSTART'] = $datecurstart; - $newevent['DTEND'] = $datecurend; - } - $moreicalevents[] = $newevent; - } - // Jump on next occurence - $numofevent++; - $savdatecurstart = $datecurstart; - 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') - { - $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); - $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); - } 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') - { - $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) - { - 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; - } - } - } - } - $icalevents = array_merge($icalevents, $moreicalevents); + $numofevent = 0; + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) + { + if ($datecurend >= $firstdaytoshow) // We add event + { + $newevent = $icalevent; + unset($newevent['RRULE']); + 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 { + $newevent['DTSTART'] = $datecurstart; + $newevent['DTEND'] = $datecurend; + } + $moreicalevents[] = $newevent; + } + // Jump on next occurence + $numofevent++; + $savdatecurstart = $datecurstart; + 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') + { + $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); + $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); + } 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') + { + $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) + { + 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; + } + } + } + } + $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) - { - //var_dump($icalevent); + // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray + 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. + //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. - // Create a new object action - $event = new ActionComm($db); - $addevent = false; - 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 - //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) - { - $datestart = $icalevent['DTSTART']; - $dateend = $icalevent['DTEND']; + // Create a new object action + $event = new ActionComm($db); + $addevent = false; + 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 + //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) + { + $datestart = $icalevent['DTSTART']; + $dateend = $icalevent['DTEND']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $dateend += +($offsettz * 3600); - $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) - { - $datestart = $icalevent['DTSTART']['unixtime']; - $dateend = $icalevent['DTEND']['unixtime']; + $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) + { + $datestart = $icalevent['DTSTART']['unixtime']; + $dateend = $icalevent['DTEND']['unixtime']; - $datestart += +($offsettz * 3600); - $dateend += +($offsettz * 3600); + $datestart += +($offsettz * 3600); + $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 - { - // 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 - { - $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); - $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); + // $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 + { + // 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 + { + $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); + $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze); $tmps = -1 * $localtzs->getOffset($localdts); $tmpe = -1 * $localtze->getOffset($localdte); $datestart += $tmps; $dateend += $tmpe; //var_dump($datestart); - } - $addevent = true; - } + } + $addevent = true; + } - if ($addevent) - { - $event->id = $icalevent['UID']; - $event->ref = $event->id; + if ($addevent) + { + $event->id = $icalevent['UID']; + $event->ref = $event->id; - $event->icalname = $namecal; - $event->icalcolor = $colorcal; - $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. - $event->datep = $datestart + $usertime; - $event->datef = $dateend + $usertime; - $event->type_code = "ICALEVENT"; + $userId = $userstatic->findUserIdByEmail($namecal); + if (!empty($userId) && $userId > 0) + { + $event->userassigned[$userId] = $userId; + $event->percentage = -1; + } + else { + $event->type_code = "ICALEVENT"; + } - if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; - elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); - else $event->label = $langs->trans("ExtSiteNoLabel"); + $event->icalname = $namecal; + $event->icalcolor = $colorcal; + $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output. + $event->datep = $datestart + $usertime; + $event->datef = $dateend + $usertime; - $event->date_start_in_calendar = $event->datep; + if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; + elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); + else $event->label = $langs->trans("ExtSiteNoLabel"); - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + // 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']; - // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { - $event->ponctuel = 1; - //print 'x'.$datestart.'-'.$dateend;exit; - } + // 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 - // Add event into $eventarray if date range are ok. - 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); + // TODO: MS outlook states + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free + // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place + // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations + // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy + // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site + } - // 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); + if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; - // 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); - 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; - } while ($loop); - } - } - } - } - } + $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; + + // Define ponctual property + 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) + { + //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); + + // 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); + + // 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); + 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; + } while ($loop); + } + } + } + } + } } @@ -1125,12 +1158,12 @@ if (count($listofextcals)) $parameters = array(); $object = null; $reshook = $hookmanager->executeHooks('getCalendarEvents', $parameters, $object, $action); if (!empty($hookmanager->resArray['eventarray'])) { - foreach ($hookmanager->resArray['eventarray'] as $keyDate => $events) { - if (!isset($eventarray[$keyDate])) { - $eventarray[$keyDate] = array(); - } - $eventarray[$keyDate] = array_merge($eventarray[$keyDate], $events); - } + foreach ($hookmanager->resArray['eventarray'] as $keyDate => $events) { + if (!isset($eventarray[$keyDate])) { + $eventarray[$keyDate] = array(); + } + $eventarray[$keyDate] = array_merge($eventarray[$keyDate], $events); + } } // Sort events @@ -1149,7 +1182,7 @@ $cacheusers = array(); $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; if (is_readable($color_file)) { - include_once $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)); @@ -1161,171 +1194,190 @@ print $s; 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); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewcal=1'; + $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); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewcal=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; - $i = 0; - while ($i < 7) - { - print ' '."\n"; - $i++; - } - echo ' '."\n"; + print '
'; + print '
'; - $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); - 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); - print '
'; + print ' '; + // Column title of weeks numbers + echo ' '; + $i = 0; + while ($i < 7) + { + print ' '."\n"; + $i++; + } + echo ' '."\n"; - $todayarray = dol_getdate($now, 'fast'); - $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); + $todayarray = dol_getdate($now, 'fast'); + $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']); - // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) - //var_dump($eventarray); - for ($iter_week = 0; $iter_week < 6; $iter_week++) { - echo " \n"; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - 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'; - echo ' \n"; - } elseif ($tmpday <= $max_day_in_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'; - $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'; + // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) + //var_dump($eventarray); + 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 + { + $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 + { + $currdate0 = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $tmpday); + } + 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); + } + // Get week number for the targeted date '$currdate0' + $numweek0 = date("W", strtotime(date($currdate0))); + // Show the week number, and define column width + echo ' '; + + for ($iter_day = 0; $iter_day < 7; $iter_day++) { + 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'; + echo ' \n"; + } elseif ($tmpday <= $max_day_in_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'; + $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'; //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); - echo ' \n"; - } else { - /* Show days after the current month (next month) */ - $style = 'cal_other_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; - echo ' \n"; - } - $tmpday++; - } - echo " \n"; - } - print "
#'; + $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); + 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); + print '
'; - show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo "
'.$numweek0.''; + 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); - echo " '; - show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); - echo "
\n"; + echo ' '; + show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); + echo " \n"; + } else { + /* Show days after the current month (next month) */ + $style = 'cal_other_month'; + 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 "\n"; + } + $tmpday++; + } + echo " \n"; + } + print "\n"; print '
'; print ''; print ''; print ''; } elseif ($action == 'show_week') { - // View by week - $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); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); - $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter - $newparam .= '&viewweek=1'; + // View by week + $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); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); + $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter + $newparam .= '&viewweek=1'; - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - print ''; - print ' '; - $i = 0; - while ($i < 7) { - echo ' \n"; - $i++; - } - echo " \n"; + print '
'; + print '
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; + print ' '; + $i = 0; + while ($i < 7) { + echo ' \n"; + $i++; + } + echo " \n"; - echo " \n"; + echo " \n"; - for ($iter_day = 0; $iter_day < 7; $iter_day++) { - // Show days of the current week + 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']; - $style = 'cal_current_month'; - 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'; + $style = 'cal_current_month'; + 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'; - echo ' \n"; - } - echo " \n"; + echo ' \n"; + } + echo " \n"; - print "
'.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))."
'; - show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); - echo "
'; + show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); + echo "
\n"; + print "\n"; print '
'; - echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; } else // View by day { - $newparam = $param; // newparam is for birthday links - $newparam = preg_replace('/action=show_month&?/i', '', $newparam); - $newparam = preg_replace('/action=show_week&?/i', '', $newparam); - $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); - $newparam .= '&viewday=1'; - // Code to show just one day - $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 ($today) $style='cal_today'; + $newparam = $param; // newparam is for birthday links + $newparam = preg_replace('/action=show_month&?/i', '', $newparam); + $newparam = preg_replace('/action=show_week&?/i', '', $newparam); + $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam); + $newparam .= '&viewday=1'; + // Code to show just one day + $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 ($today) $style='cal_today'; - $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); - $arraytimestamp = dol_getdate($timestamp); + $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); + $arraytimestamp = dol_getdate($timestamp); - print '
'; - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); - print '
'; + print '
'; + print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print '
'; - print '
'; - echo ''; + print '
'; + echo '
'; - echo ' '; - echo ' '; - echo ' \n"; - echo " \n"; + echo ' '; + echo ' \n"; + echo " \n"; - /* + /* echo '
'; echo '
'; echo '
'; @@ -1334,39 +1386,39 @@ if (empty($action) || $action == 'show_month') // View by month echo "
\n"; */ - echo '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; + echo ''; print '
'; - /* WIP View per hour */ - $useviewhour = 0; - if ($useviewhour) - { - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + /* WIP View per hour */ + $useviewhour = 0; + 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 + $maxheightwin = (isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500) ? ($_SESSION["dol_screenheight"] - 200) : 660; // Also into index.php file - echo '
'; + echo '
'; echo '
'; - $maxnbofchar = 80; + $maxnbofchar = 80; - $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; } + $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; } - $i = 0; - $j = 0; + $i = 0; + $j = 0; while ($i < 24) { - echo '
'."\n"; - echo '
'.dol_print_date($i * 3600, 'hour', 'gmt').'
'; - echo '
'."\n"; - echo '
'."\n"; - $i++; - $j++; + echo '
'."\n"; + echo '
'.dol_print_date($i * 3600, 'hour', 'gmt').'
'; + echo '
'."\n"; + echo '
'."\n"; + $i++; + $j++; } echo '
'; @@ -1374,13 +1426,13 @@ if (empty($action) || $action == 'show_month') // View by month show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 1); print '
'; - } else { - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + } else { + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 0); + show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 0); - print '
'; - } + print '
'; + } } print "\n".''; @@ -1410,399 +1462,401 @@ $db->close(); */ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0) { - global $user, $conf, $langs; - global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form - global $theme_datacolor; - global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; + global $user, $conf, $langs; + global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form + global $theme_datacolor; + global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; - $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); - print "\n"; + print "\n"; - // Line with title of day - $curtime = dol_mktime(0, 0, 0, $month, $day, $year); - print '
'."\n"; + // Line with title of day + $curtime = dol_mktime(0, 0, 0, $month, $day, $year); + print '
'."\n"; - if ($nonew <= 0) - { - print '
'; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { - $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; + if ($nonew <= 0) + { + print '
'; + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) + { + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; - //$param='month='.$monthshown.'&year='.$year; - $hourminsec = '100000'; - print ''; - print img_picto($langs->trans("NewAction"), 'edit_add.png'); - print ''; - } - print '
'."\n"; - } + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + print ''; + print img_picto($langs->trans("NewAction"), 'edit_add.png'); + print ''; + } + print '
'."\n"; + } - if ($nonew < 0) - { - print '
'; - return; - } + if ($nonew < 0) + { + print '
'; + return; + } - // Line with td contains all div of each events - print '
'; - print '
'; + // Line with td contains all div of each events + print '
'; + print '
'; - //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); - $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array(); - $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day); + //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); + $i = 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, ... + $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) - { - $annee = date('Y', $daykey); - $mois = date('m', $daykey); - $jour = date('d', $daykey); - 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); + foreach ($eventarray as $daykey => $notused) + { + $annee = date('Y', $daykey); + $mois = date('m', $daykey); + $jour = date('d', $daykey); + 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)) - { - $cssclass = 'family_mytasks'; + // Define $color (Hex string like '0088FF') and $cssclass of event + $color = -1; $cssclass = ''; $colorindex = -1; + if (in_array($user->id, $keysofuserassigned)) + { + $cssclass = 'family_mytasks'; - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + 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; - } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file - { - $numical++; - if (!empty($event->icalname)) { - if (!isset($numicals[dol_string_nospecial($event->icalname)])) { - $numicals[dol_string_nospecial($event->icalname)] = 0; - } - $numicals[dol_string_nospecial($event->icalname)]++; - } + // 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 + { + $numical++; + if (!empty($event->icalname)) { + if (!isset($numicals[dol_string_nospecial($event->icalname)])) { + $numicals[dol_string_nospecial($event->icalname)] = 0; + } + $numicals[dol_string_nospecial($event->icalname)]++; + } - $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]); - } else { - $numother++; - $color = ($event->icalcolor ? $event->icalcolor : -1); - $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); + $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]); + } else { + $numother++; + $color = ($event->icalcolor ? $event->icalcolor : -1); + $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - if (empty($cacheusers[$event->userownerid])) - { - $newuser = new User($db); - $newuser->fetch($event->userownerid); - $cacheusers[$event->userownerid] = $newuser; - } - //var_dump($cacheusers[$event->userownerid]->color); + 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. - { - // Define color index if not yet defined - $idusertouse = ($event->userownerid ? $event->userownerid : 0); - 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 - } - //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; + 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])) + { + $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 + } + //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; - // Defined style to disable drag and drop feature - if ($event->type_code == 'AC_OTH_AUTO') - { - $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) - { - $cssclass .= " unmovable"; - } - } else { - if ($user->rights->agenda->allactions->create || - (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { - $cssclass .= " movable cursormove"; - } else { - $cssclass .= " unmovable"; - } - } + // Defined style to disable drag and drop feature + if ($event->type_code == 'AC_OTH_AUTO') + { + $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) + { + $cssclass .= " unmovable"; + } + } else { + if ($user->rights->agenda->allactions->create || + (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) + { + $cssclass .= " movable cursormove"; + } else { + $cssclass .= " unmovable"; + } + } - $h = ''; $nowrapontd = 1; - if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } - if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } + $h = ''; $nowrapontd = 1; + if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } - // Show rect of event - print "\n"; - print ''."\n"; - print '
'; + // Show rect of event + print "\n"; + print ''."\n"; + print '
'; - //var_dump($event->userassigned); - //var_dump($event->transparency); - print ''; - print ''; - print ''; + // Status - Percent + $withstatus = 0; + if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') + { + $withstatus = 1; + if ($event->percentage >= 0) $withstatus = 2; + } + print '
'; + //var_dump($event->userassigned); + //var_dump($event->transparency); + print ''; + print ''; + print ''; - // Status - Percent - $withstatus = 0; - if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') - { - $withstatus = 1; - if ($event->percentage >= 0) $withstatus = 2; - } - print '
'; - $daterange = ''; + $daterange = ''; - if ($event->type_code == 'BIRTHDAY') // It's a birthday - { - 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') - { - // Picto - if (empty($event->fulldayevent)) - { - //print $event->getNomUrl(2).' '; - } + if ($event->type_code == 'BIRTHDAY') // It's a birthday + { + 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') + { + // Picto + if (empty($event->fulldayevent)) + { + //print $event->getNomUrl(2).' '; + } - // Date - if (empty($event->fulldayevent)) - { - // Show hours (start ... end) - $tmpyearstart = date('Y', $event->date_start_in_calendar); - $tmpmonthstart = date('m', $event->date_start_in_calendar); - $tmpdaystart = date('d', $event->date_start_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); - // Hour start - if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) - { - $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - 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) - { - $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'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user - } - } else { - if ($showinfo) - { - print $langs->trans("EventOnFullDay")."
\n"; - } - } + // Date + if (empty($event->fulldayevent)) + { + // Show hours (start ... end) + $tmpyearstart = date('Y', $event->date_start_in_calendar); + $tmpmonthstart = date('m', $event->date_start_in_calendar); + $tmpdaystart = date('d', $event->date_start_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); + // Hour start + if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) + { + $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + 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) + { + $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'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user + } + } else { + if ($showinfo) + { + print $langs->trans("EventOnFullDay")."
\n"; + } + } - // Show title - $titletoshow = $daterange; - $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); + // Show title + $titletoshow = $daterange; + $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle); - if ($event->type_code != 'ICALEVENT') { - $savlabel = $event->label ? $event->label : $event->libelle; - $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', '', 0, 0); - $event->label = $savlabel; - $event->libelle = $savlabel; - } + if ($event->type_code != 'ICALEVENT') { + $savlabel = $event->label ? $event->label : $event->libelle; + $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); + $event->label = $savlabel; + $event->libelle = $savlabel; + } - // Loop on each assigned user - $listofusertoshow = ''; - $posuserassigned = 0; - foreach ($event->userassigned as $tmpid => $tmpdata) - { - if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; - $posuserassigned++; - if (empty($cacheusers[$tmpid])) - { - $newuser = new User($db); - $newuser->fetch($tmpid); - $cacheusers[$tmpid] = $newuser; - } + // Loop on each assigned user + $listofusertoshow = ''; + $posuserassigned = 0; + foreach ($event->userassigned as $tmpid => $tmpdata) + { + if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; + $posuserassigned++; + 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'); - } + $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom'); + } - print $titletoshow; - print $listofusertoshow; + 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)); + $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])) - { - $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); - } - 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); - } - 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 .= '
'; - $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); - } - if ($linerelatedto) print '
'.$linerelatedto; - } + // If action related to company / contact + $linerelatedto = ''; + 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); + } + 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); + } + 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 .= '
'; + $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); + } + if ($linerelatedto) print '
'.$linerelatedto; + } - // Show location - if ($showinfo) - { - if ($event->location) - { - print '
'; - print $langs->trans("Location").': '.$event->location; - } - } + // Show location + if ($showinfo) + { + if ($event->location) + { + print '
'; + print $langs->trans("Location").': '.$event->location; + } + } - print '
'; - if ($withstatus) print $event->getLibStatut(3, 1); - else print ' '; - print '
'; - print ''."\n"; - $i++; - } else { - print ''.img_picto("all", "1downarrow_selected.png").' ...'; - print ' +'.(count($eventarray[$daykey]) - $maxprint); - print ''; - break; - //$ok=false; // To avoid to show twice the link - } - } + print '
'; + if ($withstatus) print $event->getLibStatut(3, 1); + else print ' '; + print '
'; + print '
'."\n"; + $i++; + } else { + print ''.img_picto("all", "1downarrow_selected.png").' ...'; + print ' +'.(count($eventarray[$daykey]) - $maxprint); + print ''; + break; + //$ok=false; // To avoid to show twice the link + } + } - break; - } - } - if (!$i) print ' '; + break; + } + } + if (!$i) print ' '; - if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint) - { - print '
'.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...
'; - //print ' +'.(count($eventarray[$daykey])-$maxprint); - print ''."\n"; - } + print ''."\n"; + } - print '
'; // td tr + print '
'; // td tr - print '
'; // table - print "\n"; + print '
'; // table + print "\n"; } @@ -1819,11 +1873,11 @@ function dol_color_minus($color, $minus, $minusunit = 16) $newcolor = $color; 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)); + $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)); } else { - // Not yet implemented + // Not yet implemented } return $newcolor; } @@ -1838,39 +1892,39 @@ function dol_color_minus($color, $minus, $minusunit = 16) function sort_events_by_date($a, $b) { // Sort holidays at first - if ($a->type_code === 'HOLIDAY') - { - return -1; - } + if ($a->type_code === 'HOLIDAY') + { + return -1; + } - if ($b->type_code === 'HOLIDAY') - { - return 1; - } + if ($b->type_code === 'HOLIDAY') + { + return 1; + } - // datep => Event start time - // datef => Event end time + // datep => Event start time + // datef => Event end time - // Events have different start time - if ($a->datep !== $b->datep) - { - return $a->datep - $b->datep; - } + // Events have different start time + 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))) - { - return sort_events_by_percentage($a, $b); - } + // Events have same start time and no end time + 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) - { - return sort_events_by_percentage($a, $b); - } + // Events have the same start time and same end time + if ($b->datef === $a->datef) + { + return sort_events_by_percentage($a, $b); + } - // Events have the same start time, but have different end time -> longest event first - return $b->datef - $a->datef; + // Events have the same start time, but have different end time -> longest event first + return $b->datef - $a->datef; } /** @@ -1882,18 +1936,18 @@ function sort_events_by_date($a, $b) */ 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) + // Sort events with no percentage before each other + // (usefull to sort holidays, sick days or similar on the top) - if ($a->percentage < 0) - { - return -1; - } + if ($a->percentage < 0) + { + return -1; + } - if ($b->percentage < 0) - { - return 1; - } + if ($b->percentage < 0) + { + return 1; + } - return $b->percentage - $a->percentage; + return $b->percentage - $a->percentage; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 1c21140b12a..92975aafec0 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -40,7 +40,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->loadLangs(array("users", "companies", "agenda", "commercial", "other")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'actioncommlist'; // To manage different context of search $resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int"); @@ -134,8 +134,8 @@ $arrayfields = array( 'a.datep'=>array('label'=>"DateStart", 'checked'=>1), 'a.datep2'=>array('label'=>"DateEnd", 'checked'=>1), 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1), - 'a.fk_contact'=>array('label'=>"Contact", 'checked'=>1), - 'a.fk_element'=>array('label'=>"LinkedObject", 'checked'=>0, 'enabled'=>(!empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))), + 'a.fk_contact'=>array('label'=>"Contact", 'checked'=>0), + 'a.fk_element'=>array('label'=>"LinkedObject", 'checked'=>1, 'enabled'=>(!empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))), 'a.percent'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 'a.datec'=>array('label'=>'DateCreation', 'checked'=>0), 'a.tms'=>array('label'=>'DateModification', 'checked'=>0) @@ -160,7 +160,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); if (GETPOST('cancel', 'alpha')) { - $action='list'; $massaction=''; + $action = 'list'; $massaction = ''; } if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) @@ -429,7 +429,7 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); // Local calendar - $newtitle = '
'; + $newtitle = '
'; $newtitle .= ' '.$langs->trans("LocalAgenda").'   '; $newtitle .= '
'; //$newtitle=$langs->trans($title); @@ -519,20 +519,21 @@ if ($resql) $viewmode .= ''; - $newcardbutton = ''; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { - $tmpforcreatebutton = dol_getdate(dol_now(), true); + $tmpforcreatebutton = dol_getdate(dol_now(), true); - $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; + + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + + $url = DOL_URL_ROOT.'/comm/action/card.php?action=create'; + $url .= '&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec; + $url .= '&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : '')); + + $newcardbutton = dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', $url, '', $user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create); - //$param='month='.$monthshown.'&year='.$year; - $hourminsec = '100000'; - $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : ''))); - } $param .= '&action='.$action; - print_barre_liste($langs->trans("Agenda"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, -1 * $nbtotalofrecords, 'object_action', 0, $nav.$newcardbutton, '', $limit, 0, 0, 1, $viewmode); print $s; @@ -694,7 +695,7 @@ if ($resql) 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_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').' '; @@ -706,14 +707,17 @@ if ($resql) if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; if ($actioncomm->type_code == 'AC_OTH' && $actioncomm->code == 'TICKET_MSG') { $labeltype = $langs->trans("Message"); - } elseif (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; + } 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 + } print dol_trunc($labeltype, 28); print ''; } // Label if (!empty($arrayfields['a.label']['checked'])) { - print ''; + print ''; print $actionstatic->label; print ''; } @@ -727,6 +731,7 @@ if ($resql) } $formatToUse = $obj->fulldayevent ? 'day' : 'dayhour'; + // Start date if (!empty($arrayfields['a.datep']['checked'])) { print ''; diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index 7eb5b9e5c6d..72b25c9d731 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -41,9 +41,9 @@ 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; -$filter = GETPOST("filter", 'alpha', 3); -$filtert = GETPOST("filtert", "int", 3); -$usergroup = GETPOST("usergroup", "int", 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); +$usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup", "int", 3) : GETPOST("usergroup", "int", 3); //if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id; //$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; $showbirthday = 0; @@ -64,7 +64,7 @@ if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "a.datec"; // Security check -$socid = GETPOST("socid", "int"); +$socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int"); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); if ($socid < 0) $socid = ''; @@ -79,22 +79,23 @@ if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no per //$action=GETPOST('action','alpha'); $action = 'show_pertype'; -$resourceid = GETPOST("resourceid", "int"); +$resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int"); $year = GETPOST("year", "int") ?GETPOST("year", "int") : date("Y"); $month = GETPOST("month", "int") ?GETPOST("month", "int") : date("m"); $week = GETPOST("week", "int") ?GETPOST("week", "int") : date("W"); $day = GETPOST("day", "int") ?GETPOST("day", "int") : date("d"); -$pid = GETPOST("projectid", "int", 3); -$status = GETPOST("status", 'alpha'); -$type = GETPOST("type", 'alpha'); +$pid = GETPOST("search_projectid", "int", 3) ?GETPOST("search_projectid", "int", 3) : GETPOST("projectid", "int", 3); +$status = GETPOST("search_status", 'alpha') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha'); +$type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPOST("type", 'alpha'); $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('actioncode', 'array')) +if (GETPOST('search_actioncode', 'array')) { - $actioncode = GETPOST('actioncode', 'array', 3); + $actioncode = GETPOST('search_actioncode', 'array', 3); if (!count($actioncode)) $actioncode = '0'; } else { - $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); + $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); @@ -107,6 +108,7 @@ if ($dateselect > 0) } $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_HOURS) ? '9-18' : $conf->global->MAIN_DEFAULT_WORKING_HOURS; +$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); @@ -115,14 +117,15 @@ 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 $tmparray = explode('-', $tmp); $begin_d = 1; -$end_d = 53; +$end_d = 53; if ($status == '' && !isset($_GET['status']) && !isset($_POST['status'])) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); if (empty($action) && !isset($_GET['action']) && !isset($_POST['action'])) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); -if (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { +if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { $action = 'show_month'; $day = ''; } // View by month if (GETPOST('viewweek', 'alpha') || $action == 'show_week') { @@ -150,6 +153,10 @@ if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); + $event->fetch_optionals(); + $event->fetch_userassigned(); + $event->oldcopy = clone $event; + $result = $event->delete(); } @@ -159,6 +166,27 @@ if ($action == 'delete_action') * View */ +$parameters = array( + 'socid' => $socid, + 'status' => $status, + 'year' => $year, + 'month' => $month, + 'day' => $day, + 'type' => $type, + 'maxprint' => $maxprint, + 'filter' => $filter, + 'filtert' => $filtert, + 'showbirthday' => $showbirthday, + 'canedit' => $canedit, + 'optioncss' => $optioncss, + 'actioncode' => $actioncode, + 'pid' => $pid, + 'resourceid' => $resourceid, + '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'); + $form = new Form($db); $companystatic = new Societe($db); @@ -199,18 +227,26 @@ if ($status == 'done') $title = $langs->trans("DoneActions"); if ($status == 'todo') $title = $langs->trans("ToDoActions"); $param = ''; -if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param .= "&actioncode=".$actioncode; -if ($resourceid > 0) $param .= "&resourceid=".$resourceid; -if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&status=".$status; -if ($filter) $param .= "&filter=".$filter; -if ($filtert) $param .= "&filtert=".$filtert; -if ($usergroup) $param .= "&usergroup=".$usergroup; -if ($socid) $param .= "&socid=".$socid; -if ($showbirthday) $param .= "&showbirthday=1"; -if ($pid) $param .= "&projectid=".$pid; -if ($type) $param .= "&type=".$type; -if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser' || $action != 'show_pertype') $param .= '&action='.$action; -$param .= "&maxprint=".$maxprint; +if ($actioncode || isset($_GET['search_actioncode']) || isset($_POST['search_actioncode'])) { + if (is_array($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 || isset($_GET['status']) || isset($_POST['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); $prev = dol_get_first_day($year, 1); $prev_year = $year - 1; @@ -238,6 +274,7 @@ $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd'); $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); $tmpday = $first_day; +$picto = 'calendartype'; $nav = "".img_previous($langs->trans("Previous"))."\n"; $nav .= " ".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y")." \n"; @@ -245,7 +282,7 @@ $nav .= "".$langs->trans("Today").")"; $picto = 'calendarweek'; -$nav .= '  
'; +/*$nav .= '   '; $nav .= ''; $nav .= ''; $nav .= ''; @@ -260,27 +297,30 @@ $nav .= ''; $nav .= ''; $nav .= ''; $nav .= ''; - +*/ $nav .= $form->selectDate($dateselect, 'dateselect', 0, 0, 1, '', 1, 0); -$nav .= ' '; -$nav .= '
'; +//$nav .= ' '; +$nav .= ' '; +//$nav .= ''; // Must be after the nav definition -$param .= '&year='.$year.'&month='.$month.($day ? '&day='.$day : ''); +$param .= '&year='.urlencode($year).'&month='.urlencode($month).($day ? '&day='.urlencode($day) : ''); //print 'x'.$param; - - -$tabactive = 'cardpertype'; +$tabactive = ''; +if ($action == 'show_month') $tabactive = 'cardmonth'; +if ($action == 'show_week') $tabactive = 'cardweek'; +if ($action == 'show_day') $tabactive = 'cardday'; +if ($action == 'show_list') $tabactive = 'cardlist'; +if ($action == 'show_peruser') $tabactive = 'cardperuser'; +if ($action == 'show_pertype') $tabactive = 'cardpertype'; $paramnoaction = preg_replace('/action=[a-z_]+/', '', $param); $head = calendars_prepare_head($paramnoaction); -dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); -print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, $listofextcals, $actioncode, $usergroup, '', $resourceid); -dol_fiche_end(); +print '
'."\n"; $showextcals = $listofextcals; // Legend @@ -334,10 +374,73 @@ if ($conf->use_javascript_ajax) } } +$massactionbutton = ''; + +$viewmode = ''; +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("List"), 'object_list-alt', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewList").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewCal").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewWeek").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewDay").''; + +$viewmode .= ''; +//$viewmode .= ''; +$viewmode .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview block"'); +//$viewmode .= ''; +$viewmode .= ''.$langs->trans("ViewPerUser").''; + +$viewmode .= ''; + + +$newcardbutton = ''; +if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) +{ + $tmpforcreatebutton = dol_getdate(dol_now(), true); + + $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$tmpforcreatebutton['year']; + + //$param='month='.$monthshown.'&year='.$year; + $hourminsec = '100000'; + $newcardbutton .= dolGetButtonTitle($langs->trans("AddAction"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $tmpforcreatebutton['year'], $tmpforcreatebutton['mon'], $tmpforcreatebutton['mday']).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : ''))); +} + +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); $link = ''; -print load_fiche_titre($s, $link.'     '.$nav, ''); +//print load_fiche_titre('', $link.'     '.$nav.' '.$newcardbutton, ''); + +// Local calendar +$newtitle = '
'; +$newtitle .= ' '.$langs->trans("LocalAgenda").'   '; +$newtitle .= '
'; +//$newtitle=$langs->trans($title); + +$s = $newtitle; + +print $s; + +print '
'; +print_actions_filter($form, $canedit, $search_status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); +print '
'; // Get event in an array @@ -377,7 +480,12 @@ if (!empty($actioncode)) if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; else { - $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; + if (is_array($actioncode)) + { + $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; + } else { + $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; + } } } } @@ -430,7 +538,7 @@ if ($filtert > 0 || $usergroup > 0) $sql .= ' ORDER BY fk_user_action, datep'; //fk_user_action //print $sql; -dol_syslog("comm/action/index.php", LOG_DEBUG); +dol_syslog("comm/action/pertype.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -529,6 +637,7 @@ if ($resql) } $i++; } + $db->free($resql); } else { dol_print_error($db); } @@ -536,6 +645,7 @@ if ($resql) $maxnbofchar = 18; $cachethirdparties = array(); $cachecontacts = array(); +$cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; @@ -557,11 +667,10 @@ $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam); $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter $newparam .= '&viewweek=1'; -echo ''; +print ''; echo ''; echo ''; echo ''; -echo '
'; // Line header with list of days @@ -603,6 +712,7 @@ $sql = "SELECT code, color, libelle as label FROM ".MAIN_DB_PREFIX."c_actioncomm $resql = $db->query($sql); while ($obj = $db->fetch_object($resql)) { + $typeofevents[$obj->code] = $obj->code; $colorsbytype[$obj->code] = $obj->color; $labelbytype[$obj->code] = $obj->label; } @@ -616,7 +726,7 @@ foreach ($typeofevents as $typeofevent) { $var = !$var; echo ""; - echo ''.$username->getNomUrl(1).''; + echo ''.$typeofevent.''; $tmpday = $sav; // Lopp on each day of week @@ -642,7 +752,7 @@ foreach ($typeofevents as $typeofevent) if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; if ($today) $style = 'cal_today_peruser'; - show_day_events_pertype($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); + show_day_events_pertype($typeofevent, $tmpday, $tmpmonth, $tmpyear, $mont, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); $i++; } @@ -651,7 +761,7 @@ foreach ($typeofevents as $typeofevent) } echo "\n"; - +echo "
"; if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { @@ -678,6 +788,9 @@ if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) */ } +print "\n".''; +print "\n"; + // Add js code to manage click on a box print ''; + } + print '
'; print ''."\n"; @@ -631,37 +652,37 @@ if ($resql) if (!empty($arrayfields['c.ref']['checked'])) { print ''; } // Ref customer if (!empty($arrayfields['c.ref_client']['checked'])) { print ''; } // Project ref if (!empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } // Project title if (!empty($arrayfields['p.title']['checked'])) { - print ''; + print ''; } // Thirpdarty if (!empty($arrayfields['s.nom']['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'])) { @@ -688,12 +709,10 @@ if ($resql) { print ''; } @@ -701,12 +720,10 @@ if ($resql) { print ''; } @@ -714,14 +731,14 @@ if ($resql) { // Amount print ''; } if (!empty($arrayfields['c.total_vat']['checked'])) { // Amount print ''; } if (!empty($arrayfields['c.total_ttc']['checked'])) @@ -754,7 +771,7 @@ if ($resql) } if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) { - // Amount + // Amount VAT print ''; @@ -793,6 +810,24 @@ if ($resql) } // Date cloture if (!empty($arrayfields['c.date_cloture']['checked'])) + { + print ''; + } + // Note public + if (!empty($arrayfields['c.note_public']['checked'])) + { + print ''; + } + // Note private + if (!empty($arrayfields['c.note_private']['checked'])) { print ''; @@ -816,7 +851,7 @@ if ($resql) if (!empty($arrayfields['c.facture']['checked'])) { print ''; } // Action column @@ -860,6 +895,8 @@ if ($resql) 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['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'], $_SERVER["PHP_SELF"], "c.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['c.facture']['checked'])) print_liste_field_titre($arrayfields['c.facture']['label'], $_SERVER["PHP_SELF"], 'c.facture', '', $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center '); @@ -868,6 +905,7 @@ if ($resql) $total = 0; $subtotal = 0; $productstat_cache = array(); + $productstat_cachevirtual = array(); $getNomUrl_cache = array(); $generic_commande = new Commande($db); @@ -925,7 +963,6 @@ if ($resql) // Show shippable Icon (create subloop, so may be slow) if ($conf->stock->enabled) { - $langs->load("stocks"); if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) { $numlines = count($generic_commande->lines); // Loop on each line of order @@ -949,16 +986,16 @@ if ($resql) if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result { - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->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; + $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.''; $text_info .= '
'; if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) { $notshippable++; } - } else { // Detailed code, looks bugged + } else { // Detailed virtual stock, looks bugged, uncomplete and need heavy load. // stock order and stock order_supplier $stock_order = 0; $stock_order_supplier = 0; @@ -1081,7 +1118,7 @@ if ($resql) { if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) { - print ' '; + print ' '; print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; } } @@ -1124,7 +1161,7 @@ if ($resql) if (!empty($arrayfields['typent.code']['checked'])) { print ''; if (!$i) $totalarray['nbfield']++; @@ -1248,6 +1285,22 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Note public + if (!empty($arrayfields['c.note_public']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Note private + if (!empty($arrayfields['c.note_private']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Status if (!empty($arrayfields['c.fk_statut']['checked'])) { @@ -1262,7 +1315,7 @@ if ($resql) } // Action column - print ''; - print "
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_dateorder_start ? $search_dateorder_start : -1, 'search_dateorder_start', 0, 0, 1); + print $form->selectDate($search_dateorder_start ? $search_dateorder_start : -1, 'search_dateorder_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_dateorder_end ? $search_dateorder_end : -1, 'search_dateorder_end', 0, 0, 1); + print $form->selectDate($search_dateorder_end ? $search_dateorder_end : -1, 'search_dateorder_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_datedelivery_start ? $search_datedelivery_start : -1, 'search_datedelivery_start', 0, 0, 1); + 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 $langs->trans('to').' '; - print $form->selectDate($search_datedelivery_end ? $search_datedelivery_end : -1, 'search_datedelivery_end', 0, 0, 1); + 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 ''; - print ''; + print ''; 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')); + print '
'; + print '
'; + print $form->selectDate($search_datecloture_end ? $search_datecloture_end : -1, 'search_datecloture_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + print '
'; + print ''; print ''; - print $form->selectyesno('billed', $billed, 1, 0, 1); + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); print ''; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (empty($typenArray)) $typenArray = $formcompany->typent_array(1); print $typenArray[$obj->typent_code]; print ''; + print dol_escape_htmltag($obj->note_public); + print ''; + print dol_escape_htmltag($obj->note_private); + 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 { $selected = 0; diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php index 9054252e6d9..9922d3b0e3e 100644 --- a/htdocs/commande/note.php +++ b/htdocs/commande/note.php @@ -38,7 +38,7 @@ $langs->loadLangs(array('companies', 'bills', 'orders')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check $socid = 0; diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php deleted file mode 100644 index c3d82821249..00000000000 --- a/htdocs/commande/orderstoinvoice.php +++ /dev/null @@ -1,723 +0,0 @@ - - * Copyright (C) 2004-2019 Laurent Destailleur - * Copyright (C) 2005 Marc Barilley / Ocebo - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2012 Andreu Bisquerra Gaya - * Copyright (C) 2012 David Rodriguez Martinez - * Copyright (C) 2012-2018 Juanjo Menent - * Copyright (C) 2015 Ferran Marcet - * Copyright (C) 2018 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 htdocs/commande/orderstoinvoice.php - * \ingroup commande - * \brief Page to invoice multiple orders - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; -if (!empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; -} - -// Load translation files required by the page -$langs->loadLangs(array("orders", "deliveries", "companies")); - -if (!$user->rights->facture->creer) - accessforbidden(); - -$id = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST("facid", "int")); // For backward compatibility -$ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); -$confirm = GETPOST('confirm', 'alpha'); -$sref = GETPOST('sref', 'alpha'); -$sref_client = GETPOST('sref_client', 'alpha'); -$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$socid = GETPOST('socid', 'int'); -$selected = GETPOST('orders_to_invoice'); -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'alpha'); -$search_status = GETPOST('search_status', 'alpha'); - -$error = 0; - -if (!$sortfield) $sortfield = 'c.rowid'; -if (!$sortorder) $sortorder = 'DESC'; - -$now = dol_now(); -$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server -$date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]); -$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server -$date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]); - -$extrafields = new ExtraFields($db); - -$object = new Facture($db); - -// fetch optionals attributes and labels -$extrafields->fetch_name_optionals_label($object->table_element); - -if ($action == 'create') -{ - if (!is_array($selected)) - { - $error++; - setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors'); - } else { - $origin = GETPOST('origin'); - $originid = GETPOST('originid'); - } -} - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; -$hookmanager = new HookManager($db); -$hookmanager->initHooks(array('orderstoinvoice')); - - -/* - * Actions - */ - -if (($action == 'create' || $action == 'add') && !$error) -{ - require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; - if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - - $langs->load('bills'); - $langs->load('products'); - $langs->load('main'); - if (isset($_GET['orders_to_invoice'])) - { - $orders_id = GETPOST('orders_to_invoice', '', 1); - $n = count($orders_id); - $i = 0; - - $originid = $orders_id[0]; - $_GET['originid'] = $orders_id[0]; - } - if (isset($_POST['orders_to_invoice'])) - { - $orders_id = GETPOST('orders_to_invoice', '', 2); - $nn = count($orders_id); - $ii = 0; - - $originid = $orders_id[0]; - $_POST['originid'] = $orders_id[0]; - } - - $projectid = GETPOST('projectid', 'int') ?GETPOST('projectid', 'int') : 0; - $lineid = GETPOST('lineid', 'int'); - $userid = GETPOST('userid', 'int'); - $search_ref = GETPOST('sf_ref') ?GETPOST('sf_ref') : GETPOST('search_ref'); - $closeOrders = GETPOST('autocloseorders') ? true : false; - - // Security check - $fieldid = GETPOST('ref', 'alpha') ? 'ref' : 'rowid'; - if ($user->socid) $socid = $user->socid; - $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid); - - $usehm = $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE; - - // Insert new invoice in database - if ($action == 'add' && $user->rights->facture->creer) - { - $object->socid = GETPOST('socid'); - $db->begin(); - $error = 0; - - // Standard or deposit or proforma invoice - if ($_POST['type'] == 0) - { - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) - { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } - if (!$error) - { - // Si facture standard - $object->socid = $_POST['socid']; - $object->type = $_POST['type']; - $object->number = $_POST['ref']; - $object->date = $datefacture; - $object->note_public = trim($_POST['note_public']); - $object->note = trim($_POST['note']); - $object->ref_client = $_POST['ref_client']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = ($_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id']); - $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->amount = $_POST['amount']; - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; - - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - - if ($_POST['origin'] && $_POST['originid']) - { - $object->origin = $_POST['origin']; - $object->origin_id = $orders_id[$ii]; - $object->linked_objects = $orders_id; - $id = $object->create($user); - $object->fetch_thirdparty(); - - if ($id > 0) - { - foreach ($orders_id as $origin => $origin_id) - { - $origin_id = (!empty($origin_id) ? $origin_id : $object->origin_id); - $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql .= "fk_source"; - $sql .= ", sourcetype"; - $sql .= ", fk_target"; - $sql .= ", targettype"; - $sql .= ") VALUES ("; - $sql .= $origin_id; - $sql .= ", '".$object->origin."'"; - $sql .= ", ".$id; - $sql .= ", '".$object->element."'"; - $sql .= ")"; - - if ($db->query($sql)) - { - $db->commit(); - } else { - $db->rollback(); - } - } - - while ($ii < $nn) - { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $objectsrc = new Commande($db); - dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result = $objectsrc->fetch($orders_id[$ii]); - if ($result > 0) - { - if ($closeOrders) - { - $objectsrc->classifyBilled($user); - $objectsrc->setStatut(3); - } - $lines = $objectsrc->lines; - if (empty($lines) && method_exists($objectsrc, 'fetch_lines')) - { - $objectsrc->fetch_lines(); - $lines = $objectsrc->lines; - } - $fk_parent_line = 0; - $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { - // Negative line, we create a discount line - $discount = new DiscountAbsolute($db); - $discount->fk_soc = $object->socid; - $discount->amount_ht = abs($lines[$i]->total_ht); - $discount->amount_tva = abs($lines[$i]->total_tva); - $discount->amount_ttc = abs($lines[$i]->total_ttc); - $discount->tva_tx = $lines[$i]->tva_tx; - $discount->fk_user = $user->id; - $discount->description = $desc; - $discountid = $discount->create($user); - if ($discountid > 0) - { - $result = $object->insert_discount($discountid); - //$result=$discount->link_to_invoice($lineid,$id); - } else { - setEventMessages($discount->error, $discount->errors, 'errors'); - $error++; - break; - } - } else { - // Positive line - $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; - //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; - // 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; - } - - // Extrafields - if (method_exists($lines[$i], 'fetch_optionals')) { - $lines[$i]->fetch_optionals(); - $array_options = $lines[$i]->array_options; - } - - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->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, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $lines[$i]->label, - $array_options - ); - if ($result > 0) - { - $lineid = $result; - } else { - $lineid = 0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { - $fk_parent_line = $result; - } - } - } - } else { - setEventMessages($objectsrc->error, $objectsrc->errors, 'errors'); - $error++; - } - $ii++; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - } - } - - // End of object creation, we show it - if ($id > 0 && !$error) - { - $db->commit(); - header('Location: '.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$id); - exit; - } else { - $db->rollback(); - $action = 'create'; - $_GET["origin"] = $_POST["origin"]; - $_GET["originid"] = $_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } -} - - -/* - * View - */ - -$html = new Form($db); -$htmlother = new FormOther($db); -$formfile = new FormFile($db); -$companystatic = new Societe($db); - -// Mode creation -if ($action == 'create' && !$error) -{ - $facturestatic = new Facture($db); - - llxHeader(); - print load_fiche_titre($langs->trans('NewBill')); - - $soc = new Societe($db); - if ($socid) $res = $soc->fetch($socid); - if ($res) - { - $cond_reglement_id = $soc->cond_reglement_id; - $mode_reglement_id = $soc->mode_reglement_id; - $remise_percent = $soc->remise_percent; - } - $remise_absolue = 0; - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; - - $absolute_discount = $soc->getAvailableDiscounts(); - print '
'; - print ''; - print ''; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - - dol_fiche_head(); - - print ''; - - // Ref - print ''; - - // Third party - print ''; - print ''."\n"; - - // Type - print ''; - // Payment term - print ''; - // Payment mode - print ''; - // Project - if (!empty($conf->projet->enabled)) - { - $formproject = new FormProjets($db); - - $langs->load('projects'); - print ''; - } - - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $objectsrc = new Commande($db); - $listoforders = array(); - foreach ($selected as $sel) - { - $result = $objectsrc->fetch($sel); - if ($result > 0) - { - $listoforders[] = $objectsrc->ref; - } - } - - // Other attributes - $parameters = array('objectsrc' => $objectsrc, 'idsrc' => $listoforders); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook)) - { - $object = new Facture($db); - print $object->showOptionals($extrafields, 'edit'); - } - - // Modele PDF - print ''; - print '"; - - // Public note - print ''; - print ''; - print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''; - print ''; - } - - print '
'.$langs->trans('Ref').''.$langs->trans('Draft').'
'.$langs->trans('Customer').''; - print $soc->getNomUrl(1); - print ''; - print '
'.$langs->trans('Type').''; - print ''."\n"; - - // Standard invoice - print ''."\n"; - print '
'; - print ''; - print ''; - $desc = $html->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1); - print $desc; - print '
'; - - // Date invoice - print '
'.$langs->trans('Date').''; - print $html->selectDate('', '', '', '', '', "add", 1, 1); - print '
'.$langs->trans('PaymentConditionsShort').''; - $html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); - print '
'.$langs->trans('PaymentMode').''; - $html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); - print '
'.$langs->trans('Project').''; - $formproject->select_projects($soc->id, $projectid, 'projectid'); - print '
'.$langs->trans('Model').''; - include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - $liste = ModelePDFFactures::liste_modeles($db); - print $html->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF); - print "
'.$langs->trans('NotePublic').''; - print '
'.$langs->trans('NotePrivate').''; - print '
'; - - while ($i < $n) - { - print ''; - - $i++; - } - - dol_fiche_end(); - - // Button "Create Draft" - print '
'; - print "
\n"; - - print '
\n"; -} - -// Mode liste -if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)) -{ - llxHeader(); - ?> - - 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'; - - // Show orders with status validated, shipping started and delivered (well any order we can bill) - $sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))"; - - 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 ($sref) - { - $sql .= " AND c.ref LIKE '%".$db->escape($sref)."%'"; - } - if ($sall) - { - $sql .= " AND (c.ref LIKE '%".$db->escape($sall)."%' OR c.note LIKE '%".$db->escape($sall)."%')"; - } - - //Date filter - if ($date_start && $date_end) $sql .= " AND c.date_commande >= '".$db->idate($date_start)."' AND c.date_commande <= '".$db->idate($date_end)."'"; - if ($date_starty && $date_endy) $sql .= " AND c.date_livraison >= '".$db->idate($date_starty)."' AND c.date_livraison <= '".$db->idate($date_endy)."'"; - - if (!empty($sref_client)) - { - $sql .= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\''; - } - $sql .= $db->order($sortfield, $sortorder); - - $resql = $db->query($sql); - if ($resql) - { - if ($socid) - { - $soc = new Societe($db); - $soc->fetch($socid); - } - $title = $langs->trans('ListOfOrders'); - $title .= ' - '.$langs->trans('StatusOrderValidated').', '.$langs->trans("StatusOrderSent").', '.$langs->trans('StatusOrderToBill'); - $num = $db->num_rows($resql); - print load_fiche_titre($title); - $i = 0; - $period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); - $periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); - - if (!empty($socid)) - { - // Company - $companystatic->id = $socid; - $companystatic->name = $soc->name; - print '

'.$companystatic->getNomUrl(1, 'customer').'

'; - } - - print '
'; - print ''; - print ''; - print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'c.ref', '', '&socid='.$socid, '', $sortfield, $sortorder); - print_liste_field_titre('RefCustomerOrder', $_SERVER["PHP_SELF"], 'c.ref_client', '', '&socid='.$socid, '', $sortfield, $sortorder); - print_liste_field_titre('OrderDate', $_SERVER["PHP_SELF"], 'c.date_commande', '', '&socid='.$socid, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre('DeliveryDate', $_SERVER["PHP_SELF"], 'c.date_livraison', '', '&socid='.$socid, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre('Status', '', '', '', '', 'class="right"'); - print_liste_field_titre('GenerateBill', '', '', '', '', 'align="center"'); - print ''; - - // Fields title search - print ''; - print ''; - print ''; - - //REF - print ''; - - print ''; - - //DATE ORDER - print ''; - - //DATE DELIVERY - print ''; - - //SEARCH BUTTON - print ''; - - //ALL/NONE - print ''; - - print ''; - print ''; - - print ''; - - $generic_commande = new Commande($db); - - while ($i < $num) - { - $objp = $db->fetch_object($resql); - - print ''; - print ''; - - print ''; - - // Order date - print ''; - - //Delivery date - print ''; - - // Statut - print ''; - - // Checkbox - print ''; - - print ''; - - $total = $total + $objp->price; - $subtotal = $subtotal + $objp->price; - $i++; - } - print '
'; - print ''; - print ''; - print ''; - print ''; - print $period; - print ''; - print $periodely; - print ''; - print ''; - print ''; - if ($conf->use_javascript_ajax) print ''.$langs->trans("All").' / '.$langs->trans("None").''; - print '
'; - - $generic_commande->id = $objp->rowid; - $generic_commande->ref = $objp->ref; - $generic_commande->statut = $objp->fk_statut; - $generic_commande->date_commande = $db->jdate($objp->date_commande); - $generic_commande->date_livraison = $db->jdate($objp->date_livraison); - - print ''; - print ''; - - print ''; - - print '
'; - print $generic_commande->getNomUrl(1, 0); - print ''; - if ($generic_commande->hasDelay()) { - print img_picto($langs->trans("Late"), "warning"); - } - print ''; - $filename = dol_sanitizeFileName($objp->ref); - $filedir = $conf->commande->multidir_output[$objp->entity].'/'.dol_sanitizeFileName($objp->ref); - $urlsource = $_SERVER['PHP_SELF'].'?id='.$objp->rowid; - print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); - print '
'; - print '
'.$objp->ref_client.''; - print dol_print_date($db->jdate($objp->date_commande), 'day'); - print ''; - print dol_print_date($db->jdate($objp->date_livraison), 'day'); - print ''.$generic_commande->LibStatut($objp->fk_statut, $objp->billed, 5).''; - print ''; - print '
'; - print '
'; - - // Buttons actions - print '
global->INVOICE_CLOSE_ORDERS_OFF_BY_DEFAULT_FORMASSINVOICE) ? ' checked="checked"' : '').' name="autocloseorders"> '.$langs->trans("CloseProcessedOrdersAutomatically"); - print '
'; - print ''; - print ''; - print '
'; - //print ''.$langs->trans("GoBack").''; - print ''; - print '
'; - print '
'; - - print ''; - - $db->free($resql); - } else { - dol_print_error($db); - } -} - -// End of page -llxFooter(); -$db->close(); diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 0910e4ee7ad..346b5549bfd 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -94,11 +94,11 @@ 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->escape($object_status).')'; + 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->escape($object_status).')'; + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; } diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index 0c20e46e316..020b85bf06c 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -60,15 +60,15 @@ $date_stopMonth = GETPOST('date_stopmonth', 'int'); $date_stopYear = GETPOST('date_stopyear', 'int'); //FIXME doldate $date_stop = ($date_stopDay) ?dol_mktime(23, 59, 59, $date_stopMonth, $date_stopDay, $date_stopYear) : strtotime($date_stop); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('comptafileslist', 'globallist')); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -149,7 +149,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Customer invoices if (GETPOST('selectinvoices')) { 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.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 .= "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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -158,7 +158,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Vendor invoices if (GETPOST('selectsupplierinvoices')) { 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.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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -167,7 +167,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Expense reports if (GETPOST('selectexpensereports')) { 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.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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -176,16 +176,16 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Donations if (GETPOST('selectdonations')) { 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, 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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT; } - // Paiements of salaries + // Payments of salaries if (GETPOST('selectpaymentsofsalaries')) { 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, 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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -194,7 +194,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Social contributions if (GETPOST('selectsocialcontributions')) { 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_tva, 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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -203,7 +203,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Various payments if (GETPOST('selectvariouspayment')) { if (!empty($sql)) $sql .= " UNION ALL"; - $sql .= " SELECT t.rowid as id, t.entity, t.label as ref, 1 as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_tva, 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 .= " 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; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -211,7 +211,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Loan payments if (GETPOST('selectloanspayment')) { 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_tva, 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 .= " 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; $sql .= " AND l.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -525,6 +525,9 @@ dol_fiche_head($head, 'AccountancyFiles'); print '
'."\n"; print ''; +print ''.$langs->trans("ExportAccountingSourceDocHelp", $langs->transnoentitiesnoconv("Accounting"), $langs->transnoentitiesnoconv("Journals")).'
'; +print '
'; + print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_start', 0, 0, 0, "", 1, 1, 0); print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; @@ -578,7 +581,7 @@ if (!empty($date_start) && !empty($date_stop)) foreach ($listofchoices as $choice => $val) { $param .= '&'.$choice.'='.(GETPOST($choice, 'int') ? 1 : 0); } - print ''."\n"; + print ''."\n"; print ''; echo dol_print_date($date_start, 'day')." - ".dol_print_date($date_stop, 'day'); @@ -589,7 +592,7 @@ if (!empty($date_start) && !empty($date_stop)) print ''; } - print ''; + print ''; print '
'."\n"; print '
'; @@ -603,13 +606,14 @@ if (!empty($date_start) && !empty($date_stop)) print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'nowraponall '); print ''.$langs->trans("Document").''; print ''.$langs->trans("Paid").''; - print ''.$langs->trans("TotalHT").''; - print ''.$langs->trans("TotalTTC").''; - print ''.$langs->trans("TotalVAT").''; + print ''.$langs->trans("TotalHT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; + print ''.$langs->trans("TotalTTC").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; + print ''.$langs->trans("TotalVAT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; print ''.$langs->trans("ThirdParty").''; print ''.$langs->trans("Code").''; print ''.$langs->trans("Country").''; print ''.$langs->trans("VATIntra").''; + if ($conf->multicurrency->enabled) print ''.$langs->trans("Currency").''; print ''; if ($result) { @@ -617,7 +621,11 @@ if (!empty($date_start) && !empty($date_stop)) if (empty($TData)) { - print ''.$langs->trans("NoItem").''; + print ''.$langs->trans("NoItem").''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } + print ''; } else { // Sort array by date ASC to calculate balance @@ -644,7 +652,7 @@ if (!empty($date_start) && !empty($date_stop)) print dol_print_date($data['date'], 'day'); print "\n"; - // Date + // Date due print ''; print dol_print_date($data['date_due'], 'day'); print "\n"; @@ -655,10 +663,18 @@ if (!empty($date_start) && !empty($date_stop)) if ($data['item'] == 'Invoice') { $invoice->id = $data['id']; $invoice->ref = $data['ref']; + $invoice->total_ht = $data['amount_ht']; + $invoice->total_ttc = $data['amount_ttc']; + $invoice->total_tva = $data['amount_vat']; + $invoice->multicurrency_code = $data['currency']; print $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); } elseif ($data['item'] == 'SupplierInvoice') { $supplier_invoice->id = $data['id']; $supplier_invoice->ref = $data['ref']; + $supplier_invoice->total_ht = $data['amount_ht']; + $supplier_invoice->total_ttc = $data['amount_ttc']; + $supplier_invoice->total_tva = $data['amount_vat']; + $supplier_invoice->multicurrency_code = $data['currency']; print $supplier_invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); } elseif ($data['item'] == 'ExpenseReport') { $expensereport->id = $data['id']; @@ -709,7 +725,7 @@ if (!empty($date_start) && !empty($date_stop)) // Total VAT print ''.price($data['sens'] ? $data['amount_vat'] : -$data['amount_vat'])."\n"; - print ''.$data['thirdparty_name']."\n"; + print ''.$data['thirdparty_name']."\n"; print ''.$data['thirdparty_code']."\n"; @@ -727,6 +743,10 @@ if (!empty($date_start) && !empty($date_stop)) $totalVAT_debit -= $data['amount_vat']; } + if (! empty($conf->multicurrency->enabled)) { + print ''.$data['currency']."\n"; + } + print "\n"; } @@ -737,6 +757,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_credit, 'MT')).''; print ''.price(price2num($totalVAT_credit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; // Total debits print ''; @@ -745,6 +768,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_debit, 'MT')).''; print ''.price(price2num($totalVAT_debit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; // Balance print ''; @@ -753,6 +779,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_credit + $totalIT_debit, 'MT')).''; print ''.price(price2num($totalVAT_credit + $totalVAT_debit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; } } diff --git a/htdocs/compta/bank/account_statement_document.php b/htdocs/compta/bank/account_statement_document.php index 1e9c6e3b358..3b8423b68dc 100644 --- a/htdocs/compta/bank/account_statement_document.php +++ b/htdocs/compta/bank/account_statement_document.php @@ -38,7 +38,7 @@ $langs->loadLangs(array('banks', 'companies', 'other')); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int')); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $numref = (GETPOST('num', 'alpha') ? GETPOST('num', 'alpha') : GETPOST('sectionid', 'alpha')); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index 72a7e33d3f2..cd82da0e1bd 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -91,7 +91,7 @@ $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; $sql .= " AND b.amount >= 0"; if (!empty($id)) - $sql .= " AND b.fk_account IN (".$db->escape($id).")"; + $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; $sql .= " GROUP BY dm"; $resql = $db->query($sql); @@ -117,7 +117,7 @@ $sql .= " WHERE b.fk_account = ba.rowid"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; $sql .= " AND b.amount <= 0"; if (!empty($id)) - $sql .= " AND b.fk_account IN (".$db->escape($id).")"; + $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; $sql .= " GROUP BY dm"; $resql = $db->query($sql); @@ -240,7 +240,7 @@ $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)) - $sql .= " AND b.fk_account IN (".$db->escape($id).")"; + $sql .= " AND b.fk_account IN (".$db->sanitize($db->escape($id)).")"; $resql = $db->query($sql); if ($resql) diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 0af1f84d9f6..5035e6a1366 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -56,7 +56,7 @@ $langs->loadLangs(array("banks", "bills", "categories", "companies", "margins", $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $contextpage = 'banktransactionlist'.(empty($object->ref) ? '' : '-'.$object->id); @@ -109,15 +109,15 @@ if (!$sortfield) $sortfield = 'b.datev,b.dateo,b.rowid'; $object = new Account($db); if ($id > 0 || !empty($ref)) { - $result = $object->fetch($id, $ref); - $search_account = $object->id; // Force the search field on id of account + $result = $object->fetch($id, $ref); + $search_account = $object->id; // Force the search field on id of account - if (!($object->id > 0)) - { - $langs->load("errors"); - print($langs->trans('ErrorRecordNotFound')); - exit; - } + if (!($object->id > 0)) + { + $langs->load("errors"); + print($langs->trans('ErrorRecordNotFound')); + exit; + } } $mode_balance_ok = false; @@ -137,20 +137,20 @@ $extrafields->fetch_name_optionals_label('banktransaction'); $search_array_options = $extrafields->getOptionalsFromPost('banktransaction', '', 'search_'); $arrayfields = array( - 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'b.label'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), - '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), - '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), + 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'b.label'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), + '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), + '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), 'balancebefore'=>array('label'=>$langs->trans("BalanceBefore"), 'checked'=>0, 'position'=>1000), 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1001), 'b.num_releve'=>array('label'=>$langs->trans("AccountStatement"), 'checked'=>1, 'position'=>1010), - 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), + 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), ); // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) @@ -181,10 +181,10 @@ 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 { - $search_dt_start = ''; - $search_dt_end = ''; - $search_dv_start = ''; - $search_dv_end = ''; + $search_dt_start = ''; + $search_dt_end = ''; + $search_dv_start = ''; + $search_dv_end = ''; $search_type = ""; $search_debit = ""; $search_credit = ""; @@ -203,56 +203,56 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' if (empty($reshook)) { - $objectclass = 'Account'; - $objectlabel = 'BankTransaction'; - $permissiontoread = $user->rights->banque->lire; - $permissiontodelete = $user->rights->banque->supprimer; - $uploaddir = $conf->bank->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass = 'Account'; + $objectlabel = 'BankTransaction'; + $permissiontoread = $user->rights->banque->lire; + $permissiontodelete = $user->rights->banque->supprimer; + $uploaddir = $conf->bank->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } // Conciliation if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', 'alpha')) && $user->rights->banque->consolidate) { - $error = 0; + $error = 0; - // Definition, nettoyage parametres - $num_releve = trim(GETPOST("num_releve", "alpha")); + // Definition, nettoyage parametres + $num_releve = GETPOST("num_releve", "alpha"); - if ($num_releve) - { - $bankline = new AccountLine($db); - if (isset($_POST['rowid']) && is_array($_POST['rowid'])) - { - foreach ($_POST['rowid'] as $row) - { - if ($row > 0) - { - $result = $bankline->fetch($row); - $bankline->num_releve = $num_releve; //$_POST["num_releve"]; - $result = $bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha') ? 1 : 0); // If we confirm_reconcile, we set flag 'rappro' to 1. - if ($result < 0) - { - setEventMessages($bankline->error, $bankline->errors, 'errors'); - $error++; - break; - } - } - } - } else { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("NoRecordSelected"), null, 'errors'); - } - } else { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); - } + if ($num_releve) + { + $bankline = new AccountLine($db); + if (isset($_POST['rowid']) && is_array($_POST['rowid'])) + { + foreach ($_POST['rowid'] as $row) + { + if ($row > 0) + { + $result = $bankline->fetch($row); + $bankline->num_releve = $num_releve; //$_POST["num_releve"]; + $result = $bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha') ? 1 : 0); // If we confirm_reconcile, we set flag 'rappro' to 1. + if ($result < 0) + { + setEventMessages($bankline->error, $bankline->errors, 'errors'); + $error++; + break; + } + } + } + } else { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("NoRecordSelected"), null, 'errors'); + } + } else { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); + } - if (!$error) - { - $param = 'action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; + 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); @@ -268,85 +268,85 @@ if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', ' 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; - } + exit; + } } if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) { - $error = 0; + $error = 0; - if (price2num($_POST["addcredit"]) > 0) - { - $amount = price2num($_POST["addcredit"]); - } else { - $amount = - price2num($_POST["adddebit"]); - } + if (price2num($_POST["addcredit"]) > 0) + { + $amount = price2num($_POST["addcredit"]); + } else { + $amount = - price2num($_POST["adddebit"]); + } - $operation = GETPOST("operation", 'alpha'); - $num_chq = GETPOST("num_chq", 'alpha'); - $label = GETPOST("label", 'alpha'); - $cat1 = GETPOST("cat1", 'alpha'); + $operation = GETPOST("operation", 'alpha'); + $num_chq = GETPOST("num_chq", 'alpha'); + $label = GETPOST("label", 'alpha'); + $cat1 = GETPOST("cat1", 'alpha'); - $bankaccountid = $id; - if (GETPOST('add_account', 'int') > 0) $bankaccountid = GETPOST('add_account', 'int'); + $bankaccountid = $id; + if (GETPOST('add_account', 'int') > 0) $bankaccountid = GETPOST('add_account', 'int'); - if (!$dateop) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - } - if (!$operation) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - } - if (!$label) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - } - if (!$amount) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); - } - if (!$bankaccountid > 0) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); - } - /*if (! empty($conf->accounting->enabled) && (empty($search_accountancy_code) || $search_accountancy_code == '-1')) + if (!$dateop) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + } + if (!$operation) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + } + if (!$label) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!$amount) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); + } + if (!$bankaccountid > 0) + { + $error++; + 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++; }*/ - 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) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - header("Location: ".$_SERVER['PHP_SELF'].($id ? "?id=".$id : '')); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - $action = 'addline'; - } + 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) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + header("Location: ".$_SERVER['PHP_SELF'].($id ? "?id=".$id : '')); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + $action = 'addline'; + } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) { - $accline = new AccountLine($db); - $result = $accline->fetch(GETPOST("rowid", "int")); - $result = $accline->delete($user); - if ($result <= 0) { - setEventMessages($accline->error, $accline->errors, 'errors'); - } else { - setEventMessages('RecordDeleted', null, 'mesgs'); - } + $accline = new AccountLine($db); + $result = $accline->fetch(GETPOST("rowid", "int")); + $result = $accline->delete($user); + if ($result <= 0) { + setEventMessages($accline->error, $accline->errors, 'errors'); + } else { + setEventMessages('RecordDeleted', null, 'mesgs'); + } } @@ -419,43 +419,43 @@ if ($id > 0 || !empty($ref)) $helpurl = ""; llxHeader('', $title, $helpurl); - // Load bank groups - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; - $bankcateg = new BankCateg($db); + // Load bank groups + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; + $bankcateg = new BankCateg($db); - foreach ($bankcateg->fetchAll() as $bankcategory) { - $options[$bankcategory->id] = $bankcategory->label; - } + foreach ($bankcateg->fetchAll() as $bankcategory) { + $options[$bankcategory->id] = $bankcategory->label; + } - // Bank card - $head = bank_prepare_head($object); - dol_fiche_head($head, 'journal', $langs->trans("FinancialAccount"), 0, 'account'); + // Bank card + $head = bank_prepare_head($object); + dol_fiche_head($head, 'journal', $langs->trans("FinancialAccount"), 0, 'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); - dol_fiche_end(); + dol_fiche_end(); - /* + /* * Buttons actions */ - if ($action != 'reconcile') - { - if ($object->canBeConciliated() > 0) - { - // If not cash account and can be reconciliate - if ($user->rights->banque->consolidate) { - $newparam = $param; - $newparam = preg_replace('/search_conciliated=\d+/i', '', $newparam); - $buttonreconcile = ''.$langs->trans("Conciliate").''; - } else { - $buttonreconcile = ''.$langs->trans("Conciliate").''; - } - } - } + if ($action != 'reconcile') + { + if ($object->canBeConciliated() > 0) + { + // If not cash account and can be reconciliate + if ($user->rights->banque->consolidate) { + $newparam = $param; + $newparam = preg_replace('/search_conciliated=\d+/i', '', $newparam); + $buttonreconcile = ''.$langs->trans("Conciliate").''; + } else { + $buttonreconcile = ''.$langs->trans("Conciliate").''; + } + } + } } else { llxHeader('', $langs->trans("BankTransactions"), '', '', 0, 0, array(), array(), $param); } @@ -538,25 +538,25 @@ $nbtotalofrecords = ''; $nbtotalofpages = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - $nbtotalofpages = ceil($nbtotalofrecords / $limit); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + $nbtotalofpages = ceil($nbtotalofrecords / $limit); } 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; + // 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 >= $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 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; } @@ -582,23 +582,23 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - //if ($user->rights->bank->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); - $massactionbutton = $form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->bank->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - // Confirmation 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); - } + // Confirmation 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 + // Lines of title fields print '
'."\n"; if ($optioncss != '') print ''; print ''; @@ -607,7 +607,7 @@ if ($resql) print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; if (GETPOST('bid')) print ''; @@ -615,54 +615,54 @@ if ($resql) // Form to 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)) - { - print $langs->trans("EventualyAddCategory").': '; - print Form::selectarray('cat', $options, GETPOST('cat'), 1); - } - print '
'.$langs->trans("ThenCheckLinesAndConciliate").' '; - print ''; - print ' '.$langs->trans("or").' '; - print ''; - print ' '.$langs->trans("or").' '; - print ''; + print '
'; + print ''.$langs->trans("InputReceiptNumber").': '; + print ''; // The only default value is value we just entered + print '
'; + if (is_array($options) && count($options)) + { + print $langs->trans("EventualyAddCategory").': '; + print Form::selectarray('cat', $options, GETPOST('cat'), 1); + } + print '
'.$langs->trans("ThenCheckLinesAndConciliate").' '; + print ''; + print ' '.$langs->trans("or").' '; + print ''; + print ' '.$langs->trans("or").' '; + print ''; print '
'; - // Show last bank statements - $nbmax = 15; // We accept to show last 15 receipts (so we can have more than one year) - $liste = ""; - $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; - $sql .= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; - $sql .= $db->order("num_releve", "DESC"); - $sql .= $db->plimit($nbmax + 1); - print '
'; - print $langs->trans("LastAccountStatements").' : '; - $resqlr = $db->query($sql); - if ($resqlr) - { - $numr = $db->num_rows($resqlr); - $i = 0; - $last_ok = 0; - while (($i < $numr) && ($i < $nbmax)) - { - $objr = $db->fetch_object($resqlr); - if (!$last_ok) { - $last_releve = $objr->num_releve; - $last_ok = 1; - } - $i++; - $liste = ''.$objr->num_releve.'   '.$liste; - } - if ($numr >= $nbmax) $liste = "...   ".$liste; - print $liste; - if ($numr <= 0) print ''.$langs->trans("None").''; - } else { - dol_print_error($db); - } + // Show last bank statements + $nbmax = 15; // We accept to show last 15 receipts (so we can have more than one year) + $liste = ""; + $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; + $sql .= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; + $sql .= $db->order("num_releve", "DESC"); + $sql .= $db->plimit($nbmax + 1); + print '
'; + print $langs->trans("LastAccountStatements").' : '; + $resqlr = $db->query($sql); + if ($resqlr) + { + $numr = $db->num_rows($resqlr); + $i = 0; + $last_ok = 0; + while (($i < $numr) && ($i < $nbmax)) + { + $objr = $db->fetch_object($resqlr); + if (!$last_ok) { + $last_releve = $objr->num_releve; + $last_ok = 1; + } + $i++; + $liste = ''.$objr->num_releve.'   '.$liste; + } + if ($numr >= $nbmax) $liste = "...   ".$liste; + print $liste; + 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)) @@ -775,13 +775,13 @@ if ($resql) { if (empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) // If direct entries is done using miscellaneous payments { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create&accountid='.$search_account.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.urlencode($search_account)), '', $user->rights->banque->modifier); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create&accountid='.$search_account.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.urlencode($search_account)), '', $user->rights->banque->modifier); } else // If direct entries is not done using miscellaneous payments { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', $user->rights->banque->modifier); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', $user->rights->banque->modifier); } } else { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', -1); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', -1); } } @@ -811,19 +811,19 @@ if ($resql) $moreforfilter .= '
'; $moreforfilter .= $langs->trans('DateOperationShort').' :'; $moreforfilter .= ($conf->browser->layout == 'phone' ? '
' : ' '); - $moreforfilter .= '
'.$langs->trans('From').' '; - $moreforfilter .= $form->selectDate($search_dt_start, 'search_start_dt', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'; + $moreforfilter .= $form->selectDate($search_dt_start, 'search_start_dt', 0, 0, 1, "search_form", 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')).'
'; //$moreforfilter .= ' - '; - $moreforfilter .= '
'.$langs->trans('to').' '.$form->selectDate($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'.$form->selectDate($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')).'
'; $moreforfilter .= '
'; $moreforfilter .= '
'; $moreforfilter .= $langs->trans('DateValueShort').' : '; $moreforfilter .= ($conf->browser->layout == 'phone' ? '
' : ' '); - $moreforfilter .= '
'.$langs->trans('From').' '; - $moreforfilter .= $form->selectDate($search_dv_start, 'search_start_dv', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'; + $moreforfilter .= $form->selectDate($search_dv_start, 'search_start_dv', 0, 0, 1, "search_form", 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')).'
'; //$moreforfilter .= ' - '; - $moreforfilter .= '
'.$langs->trans('to').' '.$form->selectDate($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0).'
'; + $moreforfilter .= '
'.$form->selectDate($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')).'
'; $moreforfilter .= '
'; if (!empty($conf->categorie->enabled)) @@ -854,66 +854,66 @@ if ($resql) print '
'."\n"; } - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - print '
'; - print ''."\n"; + print '
'; + print '
'."\n"; print ''; if (!empty($arrayfields['b.rowid']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.label']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.dateo']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.datev']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['type']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.num_chq']['checked'])) { - // Numero - print ''; + // Numero + print ''; } if (!empty($arrayfields['bu.label']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['ba.ref']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.debit']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.credit']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['balancebefore']['checked'])) { @@ -932,21 +932,21 @@ if ($resql) // Numero statement if (!empty($arrayfields['b.num_releve']['checked'])) { - print ''; + print ''; } // Conciliated if (!empty($arrayfields['b.conciliated']['checked'])) { - print ''; + print ''; } print ''; print ''; + print ''; print "\n"; // Fields title @@ -984,107 +984,107 @@ if ($resql) // Loop on each record $sign = 1; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); + $totalarray = array(); + while ($i < min($num, $limit)) + { + $objp = $db->fetch_object($resql); - // If we are in a situation where we need/can show balance, we calculate the start of balance - if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) - { - if (!$search_account) - { - dol_print_error('', 'account is not defined but $mode_balance_ok is true'); - exit; - } + // If we are in a situation where we need/can show balance, we calculate the start of balance + if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) + { + if (!$search_account) + { + dol_print_error('', 'account is not defined but $mode_balance_ok is true'); + exit; + } - // Loop on each record before - $sign = 1; - $i = 0; - $sqlforbalance = 'SELECT SUM(b.amount) as previoustotal'; - $sqlforbalance .= " FROM "; - $sqlforbalance .= " ".MAIN_DB_PREFIX."bank_account as ba,"; - $sqlforbalance .= " ".MAIN_DB_PREFIX."bank as b"; - $sqlforbalance .= " WHERE b.fk_account = ba.rowid"; - $sqlforbalance .= " AND ba.entity IN (".getEntity('bank_account').")"; - $sqlforbalance .= " AND b.fk_account = ".$search_account; - $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; - $resqlforbalance = $db->query($sqlforbalance); - //print $sqlforbalance; - if ($resqlforbalance) - { - $objforbalance = $db->fetch_object($resqlforbalance); - if ($objforbalance) - { - // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show - if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') - { - $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); - } // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show - else { - $balance = $objforbalance->previoustotal; - } - } - } else dol_print_error($db); + // Loop on each record before + $sign = 1; + $i = 0; + $sqlforbalance = 'SELECT SUM(b.amount) as previoustotal'; + $sqlforbalance .= " FROM "; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank_account as ba,"; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank as b"; + $sqlforbalance .= " WHERE b.fk_account = ba.rowid"; + $sqlforbalance .= " AND ba.entity IN (".getEntity('bank_account').")"; + $sqlforbalance .= " AND b.fk_account = ".$search_account; + $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; + $resqlforbalance = $db->query($sqlforbalance); + //print $sqlforbalance; + if ($resqlforbalance) + { + $objforbalance = $db->fetch_object($resqlforbalance); + if ($objforbalance) + { + // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); + } // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show + else { + $balance = $objforbalance->previoustotal; + } + } + } else dol_print_error($db); - $balancecalculated = true; + $balancecalculated = true; - // Output a line with start balance - if ($user->rights->banque->consolidate && $action == 'reconcile') - { - $tmpnbfieldbeforebalance = 0; - $tmpnbfieldafterbalance = 0; - $balancefieldfound = 0; - foreach ($arrayfields as $key => $val) - { - if ($key == 'balancebefore' || $key == 'balance') - { - $balancefieldfound++; - continue; - } - if (!empty($arrayfields[$key]['checked'])) - { - if (!$balancefieldfound) $tmpnbfieldbeforebalance++; - else $tmpnbfieldafterbalance++; - } - } - // Extra fields - $element = 'banktransaction'; - if (is_array($extrafields->attributes[$element]['label']) && count($extrafields->attributes[$element]['label'])) - { - foreach ($extrafields->attributes[$element]['label'] as $key => $val) - { - if (!empty($arrayfields["ef.".$key]['checked'])) - { - if (!empty($arrayfields[$key]['checked'])) - { - if (!$balancefieldfound) $tmpnbfieldbeforebalance++; - else $tmpnbfieldafterbalance++; - } - } - } - } + // Output a line with start balance + if ($user->rights->banque->consolidate && $action == 'reconcile') + { + $tmpnbfieldbeforebalance = 0; + $tmpnbfieldafterbalance = 0; + $balancefieldfound = 0; + foreach ($arrayfields as $key => $val) + { + if ($key == 'balancebefore' || $key == 'balance') + { + $balancefieldfound++; + continue; + } + if (!empty($arrayfields[$key]['checked'])) + { + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + // Extra fields + $element = 'banktransaction'; + if (is_array($extrafields->attributes[$element]['label']) && count($extrafields->attributes[$element]['label'])) + { + foreach ($extrafields->attributes[$element]['label'] as $key => $val) + { + if (!empty($arrayfields["ef.".$key]['checked'])) + { + if (!empty($arrayfields[$key]['checked'])) + { + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + } + } - print ''; - if ($tmpnbfieldbeforebalance) - { - print ''; - } + print ''; + if ($tmpnbfieldbeforebalance) + { + print ''; + } - if (!empty($arrayfields['balancebefore']['checked'])) - { - print ''; - } - if (!empty($arrayfields['balance']['checked'])) - { - print ''; - } + } + if (!empty($arrayfields['balance']['checked'])) + { + print ''; + } print ''; - print ''; - } - } + print ''; + } + } - if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') - { - $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) - $balancebefore = price2num($balancebefore - ($sign * $objp->amount), 'MT'); - } else { + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) + $balancebefore = price2num($balancebefore - ($sign * $objp->amount), 'MT'); + } else { $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc) $balance = price2num($balance + ($sign * $objp->amount), 'MT'); } - if (empty($cachebankaccount[$objp->bankid])) - { - $bankaccounttmp = new Account($db); - $bankaccounttmp->fetch($objp->bankid); - $cachebankaccount[$objp->bankid] = $bankaccounttmp; - $bankaccount = $bankaccounttmp; - } else { - $bankaccount = $cachebankaccount[$objp->bankid]; - } + if (empty($cachebankaccount[$objp->bankid])) + { + $bankaccounttmp = new Account($db); + $bankaccounttmp->fetch($objp->bankid); + $cachebankaccount[$objp->bankid] = $bankaccounttmp; + $bankaccount = $bankaccounttmp; + } else { + $bankaccount = $cachebankaccount[$objp->bankid]; + } - if (empty($conf->global->BANK_COLORIZE_MOVEMENT)) { - $backgroundcolor = "class='oddeven'"; - } else { - if ($objp->amount < 0) - { - if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR1)) { - $color = '#fca955'; - } else { - $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; - } - $backgroundcolor = 'style="background: '.$color.';"'; - } else { - if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { - $color = '#7fdb86'; - } else { - $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; - } - $backgroundcolor = 'style="background: '.$color.';"'; - } - } - print ''; + if (empty($conf->global->BANK_COLORIZE_MOVEMENT)) { + $backgroundcolor = "class='oddeven'"; + } else { + if ($objp->amount < 0) + { + if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR1)) { + $color = '#fca955'; + } else { + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; + } + $backgroundcolor = 'style="background: '.$color.';"'; + } else { + if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { + $color = '#7fdb86'; + } else { + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; + } + $backgroundcolor = 'style="background: '.$color.';"'; + } + } - // Ref - if (!empty($arrayfields['b.rowid']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + $banklinestatic->id = $objp->rowid; + $banklinestatic->ref = $objp->rowid; - // Description - if (!empty($arrayfields['b.label']['checked'])) - { - print "'; - //print "rowid."&account=".$objp->fk_account."\">"; - $reg = array(); - preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); - else { - if ($objp->label == '(payment_salary)') { - print dol_trunc($langs->trans("SalaryPayment", 40)); - } else { - print dol_trunc($objp->label, 40); - } - } - //print " "; + // Ref + if (!empty($arrayfields['b.rowid']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Add links after description - $links = $bankaccountstatic->get_url($objp->rowid); - $cachebankaccount = array(); - foreach ($links as $key=>$val) - { - print ''; - if ($links[$key]['type'] == 'withdraw') - { - $banktransferstatic->id = $links[$key]['url_id']; - $banktransferstatic->ref = $links[$key]['label']; - print ' '.$banktransferstatic->getNomUrl(0); - } elseif ($links[$key]['type'] == 'payment') - { - $paymentstatic->id = $links[$key]['url_id']; - $paymentstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment - print ' '.$paymentstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_supplier') - { - $paymentsupplierstatic->id = $links[$key]['url_id']; - $paymentsupplierstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment - print ' '.$paymentsupplierstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_sc') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - //print $langs->trans("SocialContributionPayment"); - print ''; - } elseif ($links[$key]['type'] == 'payment_vat') - { - $paymentvatstatic->id = $links[$key]['url_id']; - $paymentvatstatic->ref = $links[$key]['url_id']; - print ' '.$paymentvatstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_salary') - { - $paymentsalstatic->id = $links[$key]['url_id']; - $paymentsalstatic->ref = $links[$key]['url_id']; - print ' '.$paymentsalstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_loan') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - print ''; - } elseif ($links[$key]['type'] == 'payment_donation') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - print ''; - } elseif ($links[$key]['type'] == 'payment_expensereport') - { - $paymentexpensereportstatic->id = $links[$key]['url_id']; - $paymentexpensereportstatic->ref = $links[$key]['url_id']; - print ' '.$paymentexpensereportstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_various') - { - $paymentvariousstatic->id = $links[$key]['url_id']; - $paymentvariousstatic->ref = $links[$key]['url_id']; - print ' '.$paymentvariousstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'banktransfert') - { - // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. - if ($objp->amount > 0) - { - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id = $banklinestatic->fk_account; - $bankstatic->label = $banklinestatic->bank_account_ref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1, 'transactions'); - print ' '.$langs->trans("toward").' '; - $bankstatic->id = $objp->bankid; - $bankstatic->label = $objp->bankref; - print $bankstatic->getNomUrl(1, ''); - print ')'; - } else { - $bankstatic->id = $objp->bankid; - $bankstatic->label = $objp->bankref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1, ''); - print ' '.$langs->trans("toward").' '; - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id = $banklinestatic->fk_account; - $bankstatic->label = $banklinestatic->bank_account_ref; - print $bankstatic->getNomUrl(1, 'transactions'); - print ')'; - } - //var_dump($links); - } elseif ($links[$key]['type'] == 'company') - { - } elseif ($links[$key]['type'] == 'user') - { - } elseif ($links[$key]['type'] == 'member') - { - } elseif ($links[$key]['type'] == 'sc') - { - } else { - // Show link with label $links[$key]['label'] - if (!empty($objp->label) && !empty($links[$key]['label'])) print ' - '; - print ''; - if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) - { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; - print ' '.$langs->trans($reg[1]); - } else { - print ' '.$links[$key]['label']; - } - print ''; - } - } - print ''; - if (!$i) $totalarray['nbfield']++; - } + // Description + if (!empty($arrayfields['b.label']['checked'])) + { + print "\n"; - if (!$i) $totalarray['nbfield']++; - } + //print "rowid."&account=".$objp->fk_account."\">"; + $reg = array(); + preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction + if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); + else { + if ($objp->label == '(payment_salary)') { + print dol_trunc($langs->trans("SalaryPayment", 40)); + } else { + print dol_trunc($objp->label, 40); + } + } + //print " "; - // Date value - if (!empty($arrayfields['b.datev']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Add links after description + $links = $bankaccountstatic->get_url($objp->rowid); + $cachebankaccount = array(); + foreach ($links as $key=>$val) + { + print ''; + if ($links[$key]['type'] == 'withdraw') + { + $banktransferstatic->id = $links[$key]['url_id']; + $banktransferstatic->ref = $links[$key]['label']; + print ' '.$banktransferstatic->getNomUrl(0); + } elseif ($links[$key]['type'] == 'payment') + { + $paymentstatic->id = $links[$key]['url_id']; + $paymentstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment + print ' '.$paymentstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_supplier') + { + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment + print ' '.$paymentsupplierstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_sc') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + //print $langs->trans("SocialContributionPayment"); + print ''; + } elseif ($links[$key]['type'] == 'payment_vat') + { + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $links[$key]['url_id']; + print ' '.$paymentvatstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_salary') + { + $paymentsalstatic->id = $links[$key]['url_id']; + $paymentsalstatic->ref = $links[$key]['url_id']; + print ' '.$paymentsalstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_loan') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + print ''; + } elseif ($links[$key]['type'] == 'payment_donation') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + print ''; + } elseif ($links[$key]['type'] == 'payment_expensereport') + { + $paymentexpensereportstatic->id = $links[$key]['url_id']; + $paymentexpensereportstatic->ref = $links[$key]['url_id']; + print ' '.$paymentexpensereportstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_various') + { + $paymentvariousstatic->id = $links[$key]['url_id']; + $paymentvariousstatic->ref = $links[$key]['url_id']; + print ' '.$paymentvariousstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'banktransfert') + { + // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. + if ($objp->amount > 0) + { + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1, 'transactions'); + print ' '.$langs->trans("toward").' '; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; + print $bankstatic->getNomUrl(1, ''); + print ')'; + } else { + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1, ''); + print ' '.$langs->trans("toward").' '; + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; + print $bankstatic->getNomUrl(1, 'transactions'); + print ')'; + } + //var_dump($links); + } elseif ($links[$key]['type'] == 'company') + { + } elseif ($links[$key]['type'] == 'user') + { + } elseif ($links[$key]['type'] == 'member') + { + } elseif ($links[$key]['type'] == 'sc') + { + } else { + // Show link with label $links[$key]['label'] + if (!empty($objp->label) && !empty($links[$key]['label'])) print ' - '; + print ''; + if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) + { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + print ' '.$langs->trans($reg[1]); + } else { + print ' '.$links[$key]['label']; + } + print ''; + } + } + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Payment type - if (!empty($arrayfields['type']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Date ope + if (!empty($arrayfields['b.dateo']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } - // Num cheque - if (!empty($arrayfields['b.num_chq']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Date value + if (!empty($arrayfields['b.datev']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Payment type + if (!empty($arrayfields['type']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Num cheque + if (!empty($arrayfields['b.num_chq']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } // Third party - if (!empty($arrayfields['bu.label']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + if (!$i) $totalarray['nbfield']++; + } - // Bank account - if (!empty($arrayfields['ba.ref']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + if (!$i) $totalarray['nbfield']++; + } - // Debit - if (!empty($arrayfields['b.debit']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totaldebfield'] = $totalarray['nbfield']; - } + // Debit + if (!empty($arrayfields['b.debit']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totaldebfield'] = $totalarray['nbfield']; + } - // Credit - if (!empty($arrayfields['b.credit']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totalcredfield'] = $totalarray['nbfield']; - } + $totalarray['totalcred'] += $objp->amount; + } + print "\n"; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totalcredfield'] = $totalarray['nbfield']; + } - // Balance before - if (!empty($arrayfields['balancebefore']['checked'])) - { - if ($mode_balance_ok) - { - if ($balancebefore >= 0) - { - print ''; - } else { - print ''; - } - } else { - print ''; - } - if (!$i) $totalarray['nbfield']++; - } - // Balance - if (!empty($arrayfields['balance']['checked'])) - { - if ($mode_balance_ok) - { - if ($balance >= 0) - { - print ''; - } else { - print ''; - } - } else { - print ''; - } - if (!$i) $totalarray['nbfield']++; - } + // Balance before + if (!empty($arrayfields['balancebefore']['checked'])) + { + if ($mode_balance_ok) + { + if ($balancebefore >= 0) + { + print ''; + } else { + print ''; + } + } else { + print ''; + } + if (!$i) $totalarray['nbfield']++; + } + // Balance + if (!empty($arrayfields['balance']['checked'])) + { + if ($mode_balance_ok) + { + if ($balance >= 0) + { + print ''; + } else { + print ''; + } + } else { + print ''; + } + if (!$i) $totalarray['nbfield']++; + } - if (!empty($arrayfields['b.num_releve']['checked'])) - { - print ''; - if (!$i) - { - $totalarray['nbfield']++; - $posconciliatecol = $totalarray['nbfield']; - } - } + if (!empty($arrayfields['b.num_releve']['checked'])) + { + print ''; + if (!$i) + { + $totalarray['nbfield']++; + $posconciliatecol = $totalarray['nbfield']; + } + } - if (!empty($arrayfields['b.conciliated']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + if (!empty($arrayfields['b.conciliated']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Action edit/delete - print ''; - if (!$i) $totalarray['nbfield']++; + // Action edit/delete + print ''; + if (!$i) $totalarray['nbfield']++; - // Action column - print ''; - if (!$i) $totalarray['nbfield']++; + // Action column + print ''; + if (!$i) $totalarray['nbfield']++; print ""; @@ -1513,25 +1517,25 @@ if ($resql) // Show total line if (isset($totalarray['totaldebfield']) || isset($totalarray['totalcredfield'])) { - print ''; - $i = 0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } elseif ($totalarray['totaldebfield'] == $i) print ''; - elseif ($totalarray['totalcredfield'] == $i) print ''; - elseif ($i == $posconciliatecol) - { - print ''; - } else print ''; - } - print ''; + print ''; + $i = 0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } elseif ($totalarray['totaldebfield'] == $i) print ''; + elseif ($totalarray['totalcredfield'] == $i) print ''; + elseif ($i == $posconciliatecol) + { + print ''; + } else print ''; + } + print ''; } // If no record found @@ -1545,7 +1549,7 @@ if ($resql) print "
'; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print '    '; - $form->select_types_paiements(empty($search_type) ? '' : $search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100'); - print ''; + $form->select_types_paiements(empty($search_type) ? '' : $search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100'); + print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1, ($id > 0 || !empty($ref) ? ' disabled="disabled"' : ''), 0, 'maxwidth100'); - print ''; + $form->select_comptes($search_account, 'search_account', 0, '', 1, ($id > 0 || !empty($ref) ? ' disabled="disabled"' : ''), 0, 'maxwidth100'); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1); - print ''; + print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1); + print ''; print ''; $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; - print '
'; - print ' '; - print '
'; + print ' '; + print ''; - print price(price2num($balance, 'MT'), 1, $langs); - print ''; + if (!empty($arrayfields['balancebefore']['checked'])) + { + print ''; print price(price2num($balance, 'MT'), 1, $langs); print ''; + print price(price2num($balance, 'MT'), 1, $langs); + print ''; print ''; @@ -1097,245 +1097,249 @@ if ($resql) print ''; print ' '; print '
'; - print "rowid.'&save_lastsearch_values=1">'.img_object($langs->trans("ShowPayment").': '.$objp->rowid, 'account', 'class="classfortooltip"').' '.$objp->rowid."   "; - print '"; + print '
'; + print $banklinestatic->getNomUrl(1); + print '"; - // Date ope - if (!empty($arrayfields['b.dateo']['checked'])) - { - print ''; - print ''.dol_print_date($db->jdate($objp->do), "day").""; - print ' '; - print ''; - print ''; - print img_edit_remove()." "; - print ''; - print img_edit_add().""; - print ''; - print "'; - print ''.dol_print_date($db->jdate($objp->dv), "day").""; - print ' '; - print ''; - print ''; - print img_edit_remove()." "; - print ''; - print img_edit_add().""; - print ''; - print "'; - $labeltype = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); - if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); - else print $labeltype; - print "'; + print ''.dol_print_date($db->jdate($objp->do), "day").""; + print ' '; + print ''; + print ''; + print img_edit_remove()." "; + print ''; + print img_edit_add().""; + print ''; + print "'.($objp->num_chq ? $objp->num_chq : "")."'; + print ''.dol_print_date($db->jdate($objp->dv), "day").""; + print ' '; + print ''; + print ''; + print img_edit_remove()." "; + print ''; + print img_edit_add().""; + print ''; + print "'; + $labeltype = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); + if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); + else print $labeltype; + print "'.($objp->num_chq ? $objp->num_chq : "")."'; + if (!empty($arrayfields['bu.label']['checked'])) + { + print ''; if ($objp->url_id) { $companystatic->id = $objp->url_id; @@ -1353,157 +1357,157 @@ if ($resql) print ' '; } print ''; + // Bank account + if (!empty($arrayfields['ba.ref']['checked'])) + { + print ''; print $bankaccount->getNomUrl(1); print "'; - if ($objp->amount < 0) - { - print price($objp->amount * -1); - $totalarray['totaldeb'] += $objp->amount; - } - print "'; + if ($objp->amount < 0) + { + print price($objp->amount * -1); + $totalarray['totaldeb'] += $objp->amount; + } + print "'; - if ($objp->amount > 0) - { + // Credit + if (!empty($arrayfields['b.credit']['checked'])) + { + print ''; + if ($objp->amount > 0) + { print price($objp->amount); - $totalarray['totalcred'] += $objp->amount; - } - print " '.price($balancebefore).' '.price($balancebefore).'- '.price($balance).' '.price($balance).'- '.price($balancebefore).' '.price($balancebefore).'- '.price($balance).' '.price($balance).'-'; - // Transaction reconciliated or edit link - if ($bankaccount->canBeConciliated() > 0) - { - if ($objp->num_releve) - { - print ''.$objp->num_releve.''; - } - if (!$objp->conciliated && $action == 'reconcile') - { - if ($objp->num_releve) print ' '; - print 'rowid]) ? ' checked' : '').'>'; - } - } - print ''; + // Transaction reconciliated or edit link + if ($bankaccount->canBeConciliated() > 0) + { + if ($objp->num_releve) + { + print ''.$objp->num_releve.''; + } + if (!$objp->conciliated && $action == 'reconcile') + { + if ($objp->num_releve) print ' '; + print 'rowid]) ? ' checked' : '').'>'; + } + } + print ''; - print $objp->conciliated ? $langs->trans("Yes") : $langs->trans("No"); - print ''; + print $objp->conciliated ? $langs->trans("Yes") : $langs->trans("No"); + print ''; - // Transaction reconciliated or edit link - if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated - { - print ''; - print img_edit(); - print ''; - } else { - if ($user->rights->banque->modifier || $user->rights->banque->consolidate) - { - print ''; - print img_edit(); - print ''; - } else { - print ''; - print img_view(); - print ''; - } - if ($bankaccount->canBeConciliated() > 0 && empty($objp->conciliated)) - { - if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) - { - print ' '.img_warning($langs->trans("ReconciliationLate")); - } - } - if ($user->rights->banque->modifier) - { - print 'rowid.'&id='.$objp->bankid.'&page='.$page.'">'; - print img_delete('', 'class="marginleftonly"'); - print ''; - } - } - print ''; + // Transaction reconciliated or edit link + if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated + { + print ''; + print img_edit(); + print ''; + } else { + if ($user->rights->banque->modifier || $user->rights->banque->consolidate) + { + print ''; + print img_edit(); + print ''; + } else { + print ''; + print img_view(); + print ''; + } + if ($bankaccount->canBeConciliated() > 0 && empty($objp->conciliated)) + { + if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) + { + print ' '.img_warning($langs->trans("ReconciliationLate")); + } + } + if ($user->rights->banque->modifier) + { + print 'rowid.'&id='.$objp->bankid.'&page='.$page.'">'; + print img_delete('', 'class="marginleftonly"'); + 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 - { - $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; - 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 + { + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; + } + print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price(-1 * $totalarray['totaldeb']).''.price($totalarray['totalcred']).''; - if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; - print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price(-1 * $totalarray['totaldeb']).''.price($totalarray['totalcred']).''; + if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; + print '
"; print "
"; - print '
'; + print ''; $db->free($resql); } else { dol_print_error($db); diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index c99f303210b..bac2f974def 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -115,7 +115,7 @@ if ($action == 'add') $object->min_allowed = GETPOST("account_min_allowed", 'int'); $object->min_desired = GETPOST("account_min_desired", 'int'); - $object->comment = trim(GETPOST("account_comment", 'none')); + $object->comment = trim(GETPOST("account_comment", 'restricthtml')); $object->fk_user_author = $user->id; @@ -213,7 +213,7 @@ if ($action == 'update') $object->min_allowed = GETPOST("account_min_allowed", 'int'); $object->min_desired = GETPOST("account_min_desired", 'int'); - $object->comment = trim(GETPOST("account_comment", 'none')); + $object->comment = trim(GETPOST("account_comment", 'restricthtml')); if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) { @@ -761,13 +761,13 @@ if ($action == 'create') if ($user->rights->banque->configurer) { - print 'id.'">'.$langs->trans("Modify").''; + print 'id.'">'.$langs->trans("Modify").''; } $canbedeleted = $object->can_be_deleted(); // Renvoi vrai si compte sans mouvements if ($user->rights->banque->configurer && $canbedeleted) { - print 'id.'">'.$langs->trans("Delete").''; + print 'id.'">'.$langs->trans("Delete").''; } print '
'; diff --git a/htdocs/compta/bank/categ.php b/htdocs/compta/bank/categ.php index 0f71134d08a..18b75bdea9b 100644 --- a/htdocs/compta/bank/categ.php +++ b/htdocs/compta/bank/categ.php @@ -135,8 +135,8 @@ if ($result) } else { print "".$objp->label.""; print ''; - print ''.img_edit().''; - print ''.img_delete().''; + print ''.img_edit().''; + print ''.img_delete().''; print ''; } print ""; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index ded439748e5..dffd62dc5a3 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -390,11 +390,11 @@ class Account extends CommonObject $sql .= ", label"; $sql .= ", type"; $sql .= ") VALUES ("; - $sql .= "'".$line_id."'"; - $sql .= ", '".$url_id."'"; - $sql .= ", '".$url."'"; + $sql .= " ".((int) $line_id); + $sql .= ", '".$this->db->escape($url_id)."'"; + $sql .= ", '".$this->db->escape($url)."'"; $sql .= ", '".$this->db->escape($label)."'"; - $sql .= ", '".$type."'"; + $sql .= ", '".$this->db->escape($type)."'"; $sql .= ")"; dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); @@ -434,7 +434,7 @@ class Account extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."bank_url"; if ($fk_bank > 0) { $sql .= " WHERE fk_bank = ".$fk_bank; - } else { $sql .= " WHERE url_id = ".$url_id." AND type = '".$type."'"; + } else { $sql .= " WHERE url_id = ".$url_id." AND type = '".$this->db->escape($type)."'"; } $sql .= " ORDER BY type, label"; @@ -472,7 +472,7 @@ class Account extends CommonObject * @param string $oper 'VIR','PRE','LIQ','VAD','CB','CHQ'... * @param string $label Descripton * @param float $amount Amount - * @param string $num_chq Numero cheque ou virement + * @param string $num_chq Numero cheque or transfer * @param int $categorie Category id (optionnal) * @param User $user User that create * @param string $emetteur Name of cheque writer @@ -566,15 +566,18 @@ class Account extends CommonObject if (!$result) { $this->error = $this->db->lasterror(); $this->db->rollback(); + return -3; } } $this->db->commit(); + return $accline->id; } else { $this->error = $this->db->lasterror(); $this->db->rollback(); + return -2; } } @@ -1312,7 +1315,7 @@ class Account extends CommonObject * * @return int Nb of account we can reconciliate */ - public static function countAccountToReconcile() + public function countAccountToReconcile() { global $db, $conf, $user; @@ -1328,12 +1331,12 @@ class Account extends CommonObject $sql .= " WHERE ba.rappro > 0 and ba.clos = 0"; $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql .= " AND ba.courant != 2"; - $resql = $db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $obj = $db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); $nb = $obj->nb; - } else dol_print_error($db); + } else dol_print_error($this->db); return $nb; } @@ -1353,7 +1356,7 @@ class Account extends CommonObject global $conf, $langs, $user; $result = ''; - $label = ''.$langs->trans("BankAccount").''; + $label = img_picto('', $this->picto).' '.$langs->trans("BankAccount").''; $label .= '
'.$langs->trans('Label').': '.$this->label; $label .= '
'.$langs->trans('AccountNumber').': '.$this->number; $label .= '
'.$langs->trans('IBAN').': '.$this->iban; @@ -1703,7 +1706,7 @@ class AccountLine extends CommonObject /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto = 'generic'; + public $picto = 'accountline'; /** * @var int ID @@ -1822,7 +1825,7 @@ class AccountLine extends CommonObject $sql .= " AND ba.entity IN (".getEntity('bank_account').")"; if ($num) $sql .= " AND b.num_chq='".$this->db->escape($num)."'"; elseif ($ref) $sql .= " AND b.rowid='".$this->db->escape($ref)."'"; - else $sql .= " AND b.rowid=".$rowid; + else $sql .= " AND b.rowid = ".((int) $rowid); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -2303,13 +2306,16 @@ class AccountLine extends CommonObject global $langs; $result = ''; - $label = $langs->trans("ShowTransaction").': '.$this->rowid; - $linkstart = ''; + + $label = img_picto('', $this->picto).' '.$langs->trans("Transaction").':
'; + $label .= ''.$langs->trans("Ref").': '.$this->ref; + + $linkstart = '
'; $linkend = ''; $result .= $linkstart; if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'account'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->rowid); + if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->id); $result .= $linkend; if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') $result .= ' ('; @@ -2415,7 +2421,7 @@ class AccountLine extends CommonObject $type = 'bank'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; + $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) { diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index d33523863a3..157a7096eb8 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -95,6 +95,37 @@ class PaymentVarious extends CommonObject public $fk_user_modif; + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * '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' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * '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 + public $fields = array( + // TODO: fill this array + ); + // END MODULEBUILDER PROPERTIES + /** * Constructor * @@ -307,6 +338,24 @@ class PaymentVarious extends CommonObject $this->fk_user_modif = ''; } + /** + * Check if a miscellaneous payment can be created into database + * + * @return boolean True or false + */ + public function check() + { + $newamount = price2num($this->amount, 'MT'); + + // Validation of parameters + if (!($newamount) > 0 || empty($this->datep)) + { + return false; + } + + return true; + } + /** * Create in database * @@ -679,7 +728,7 @@ class PaymentVarious extends CommonObject $type = 'bank'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$banklineid; + $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 = ".$banklineid; $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index e3863cd2922..2bd95409827 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -36,7 +36,7 @@ $langs->loadLangs(array('banks', 'companies', 'other')); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int')); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index 296211bf35c..686122f4d56 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -130,8 +130,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-".$month."-01 00:00:00'"; - $sql .= " AND b.datev < '".$yearnext."-".$monthnext."-01 00:00:00'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-".$db->escape($month)."-01 00:00:00'"; + $sql .= " AND b.datev < '".$db->escape($yearnext)."-".$db->escape($monthnext)."-01 00:00:00'"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%Y%m%d')"; @@ -159,7 +159,7 @@ 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').")"; - $sql .= " AND b.datev < '".$year."-".sprintf("%02s", $month)."-01'"; + $sql .= " AND b.datev < '".$db->escape($year)."-".sprintf("%02s", $month)."-01'"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $resql = $db->query($sql); @@ -267,8 +267,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-01-01 00:00:00'"; - $sql .= " AND b.datev <= '".$year."-12-31 23:59:59'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-01-01 00:00:00'"; + $sql .= " AND b.datev <= '".$db->escape($year)."-12-31 23:59:59'"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%Y%m%d')"; @@ -296,7 +296,7 @@ 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').")"; - $sql .= " AND b.datev < '".$year."-01-01'"; + $sql .= " AND b.datev < '".$db->escape($year)."-01-01'"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $resql = $db->query($sql); @@ -519,8 +519,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-".$month."-01 00:00:00'"; - $sql .= " AND b.datev < '".$yearnext."-".$monthnext."-01 00:00:00'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-".$db->escape($month)."-01 00:00:00'"; + $sql .= " AND b.datev < '".$db->escape($yearnext)."-".$db->escape($monthnext)."-01 00:00:00'"; $sql .= " AND b.amount > 0"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%d')"; @@ -555,8 +555,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-".$month."-01 00:00:00'"; - $sql .= " AND b.datev < '".$yearnext."-".$monthnext."-01 00:00:00'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-".$db->escape($month)."-01 00:00:00'"; + $sql .= " AND b.datev < '".$db->escape($yearnext)."-".$db->escape($monthnext)."-01 00:00:00'"; $sql .= " AND b.amount < 0"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%d')"; @@ -632,8 +632,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-01-01 00:00:00'"; - $sql .= " AND b.datev <= '".$year."-12-31 23:59:59'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-01-01 00:00:00'"; + $sql .= " AND b.datev <= '".$db->escape($year)."-12-31 23:59:59'"; $sql .= " AND b.amount > 0"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%m');"; @@ -659,8 +659,8 @@ 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').")"; - $sql .= " AND b.datev >= '".$year."-01-01 00:00:00'"; - $sql .= " AND b.datev <= '".$year."-12-31 23:59:59'"; + $sql .= " AND b.datev >= '".$db->escape($year)."-01-01 00:00:00'"; + $sql .= " AND b.datev <= '".$db->escape($year)."-12-31 23:59:59'"; $sql .= " AND b.amount < 0"; if ($account && $_GET["option"] != 'all') $sql .= " AND b.fk_account IN (".$account.")"; $sql .= " GROUP BY date_format(b.datev,'%m')"; diff --git a/htdocs/compta/bank/info.php b/htdocs/compta/bank/info.php index 6f6d7236f15..e1adb0b5e41 100644 --- a/htdocs/compta/bank/info.php +++ b/htdocs/compta/bank/info.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories', 'companies')); -$id = GETPOST("rowid"); +$id = GETPOST("rowid", 'int'); /* @@ -55,7 +55,7 @@ $hselected = $h; $h++; -dol_fiche_head($head, $hselected, $langs->trans("LineRecord"), -1, 'account'); +dol_fiche_head($head, $hselected, $langs->trans("LineRecord"), -1, 'accountline'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/compta/bank/line.php b/htdocs/compta/bank/line.php index d2b3e6099dd..4e2998792d8 100644 --- a/htdocs/compta/bank/line.php +++ b/htdocs/compta/bank/line.php @@ -32,6 +32,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories', 'compta', 'bills', 'other')); @@ -43,7 +44,7 @@ if (!empty($conf->salaries->enabled)) $langs->load("salaries"); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int')); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $rowid = GETPOST("rowid", 'int'); $orig_account = GETPOST("orig_account"); @@ -138,15 +139,15 @@ if ($user->rights->banque->modifier && $action == "update") $sql = "UPDATE ".MAIN_DB_PREFIX."bank"; $sql .= " SET "; // Always opened - if (isset($_POST['value'])) $sql .= " fk_type='".$db->escape($_POST['value'])."',"; - if (isset($_POST['num_chq'])) $sql .= " num_chq='".$db->escape($_POST["num_chq"])."',"; - if (isset($_POST['banque'])) $sql .= " banque='".$db->escape($_POST["banque"])."',"; - if (isset($_POST['emetteur'])) $sql .= " emetteur='".$db->escape($_POST["emetteur"])."',"; + if (isset($_POST['value'])) $sql .= " fk_type='".$db->escape(GETPOST('value'))."',"; + if (isset($_POST['num_chq'])) $sql .= " num_chq='".$db->escape(GETPOST("num_chq"))."',"; + if (isset($_POST['banque'])) $sql .= " banque='".$db->escape(GETPOST("banque"))."',"; + if (isset($_POST['emetteur'])) $sql .= " emetteur='".$db->escape(GETPOST("emetteur"))."',"; // Blocked when conciliated if (!$acline->rappro) { - if (isset($_POST['label'])) $sql .= " label='".$db->escape($_POST["label"])."',"; - if (isset($_POST['amount'])) $sql .= " amount='".$amount."',"; + if (isset($_POST['label'])) $sql .= " label = '".$db->escape(GETPOST("label"))."',"; + if (isset($_POST['amount'])) $sql .= " amount= '".$db->escape($amount)."',"; if (isset($_POST['dateomonth'])) $sql .= " dateo = '".$db->idate($dateop)."',"; if (isset($_POST['datevmonth'])) $sql .= " datev = '".$db->idate($dateval)."',"; } @@ -212,7 +213,7 @@ if ($user->rights->banque->consolidate && ($action == 'num_releve' || $action == $db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."bank"; - $sql .= " SET num_releve=".($num_rel ? "'".$num_rel."'" : "null"); + $sql .= " SET num_releve=".($num_rel ? "'".$db->escape($num_rel)."'" : "null"); if (empty($num_rel)) $sql .= ", rappro = 0"; else $sql .= ", rappro = ".$rappro; $sql .= " WHERE rowid = ".$rowid; @@ -246,16 +247,7 @@ foreach ($cats as $cat) { $arrayselected[] = $cat->id; } -$tabs = array( - array( - DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$rowid, - $langs->trans('BankTransaction') - ), - array( - DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$rowid, - $langs->trans('Info') - ) -); +$head = bankline_prepare_head($rowid); $sql = "SELECT b.rowid,b.dateo as do,b.datev as dv, b.amount, b.label, b.rappro,"; @@ -296,7 +288,7 @@ if ($result) print ''; print ''; - dol_fiche_head($tabs, 0, $langs->trans('LineRecord'), 0, 'account', 0); + dol_fiche_head($head, 'bankline', $langs->trans('LineRecord'), 0, 'accountline', 0); $linkback = ''.$langs->trans("BackToList").''; @@ -306,7 +298,7 @@ if ($result) print '
'; print '
'; - print ''; + print '
'; $i++; diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 882244518f7..9c67897e18d 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -39,7 +39,7 @@ if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categori // Load translation files required by the page $langs->loadLangs(array('banks', 'categories', 'accountancy', 'compta')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -247,12 +247,7 @@ if ($user->rights->banque->supprimer) $arrayofmassactions['predelete'] = 'selectMassAction('', $arrayofmassactions); -$newcardbutton = ''; -if ($user->rights->banque->configurer) -{ - $newcardbutton .= dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create'); -} - +$newcardbutton = dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create', '', $user->rights->banque->configurer); // Lines of title fields print '
'; @@ -281,7 +276,7 @@ if ($sall) $moreforfilter = ''; -if (!empty($conf->categorie->enabled)) +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $moreforfilter .= $form->getFilterBox(Categorie::TYPE_ACCOUNT, $search_category_list); } diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index aee53fe3f23..ba5e20c11c1 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -48,7 +48,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; // Load translation files required by the page $langs->loadLangs(array("banks", "categories", "companies", "bills", "trips", "donations", "loan")); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('account', 'int') ? GETPOST('account', 'int') : GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $dvid = GETPOST('dvid', 'alpha'); diff --git a/htdocs/compta/bank/transfer.php b/htdocs/compta/bank/transfer.php index 7228c38fe50..70903f9120f 100644 --- a/htdocs/compta/bank/transfer.php +++ b/htdocs/compta/bank/transfer.php @@ -37,7 +37,7 @@ $langs->loadLangs(array("banks", "categories", "multicurrency")); if (!$user->rights->banque->transfer) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $error = 0; diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 071a5abf0a9..56843c9032f 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -41,8 +41,9 @@ $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy", "cat // Get parameters $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm'); +$cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); $accountid = GETPOST("accountid") > 0 ? GETPOST("accountid", "int") : 0; @@ -107,8 +108,8 @@ if (empty($reshook)) $object->datev = $datev; $object->datep = $datep; $object->amount = price2num(GETPOST("amount", 'alpha')); - $object->label = GETPOST("label", 'none'); - $object->note = GETPOST("note", 'none'); + $object->label = GETPOST("label", 'restricthtml'); + $object->note = GETPOST("note", 'restricthtml'); $object->type_payment = GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0; $object->num_payment = GETPOST("num_payment", 'alpha'); $object->fk_user_author = $user->id; @@ -225,6 +226,64 @@ if (empty($reshook)) } } +// Action clone object +if ($action == 'confirm_clone' && $confirm != 'yes') { $action = ''; } + +if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->banque->modifier)) +{ + $db->begin(); + + $originalId = $id; + + $object->fetch($id); + + if ($object->id > 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; + } + + $newdatepayment = dol_mktime(0, 0, 0, GETPOST('clone_date_paymentmonth', 'int'), GETPOST('clone_date_paymentday', 'int'), GETPOST('clone_date_paymentyear', 'int')); + $newdatevalue = dol_mktime(0, 0, 0, GETPOST('clone_date_valuemonth', 'int'), GETPOST('clone_date_valueday', 'int'), GETPOST('clone_date_valueyear', 'int')); + if ($newdatepayment) $object->datep = $newdatepayment; + if (!empty($newdatevalue)) { + $object->datev = $newdatevalue; + } else { + $object->datev = $newdatepayment; + } + + if ($object->check()) + { + $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 { + $id = $originalId; + $db->rollback(); + + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + $db->rollback(); + dol_print_error($db, $object->error); + } +} + /* * View @@ -419,6 +478,19 @@ if ($id) $head = various_payment_prepare_head($object); + // Clone confirmation + 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', 'tdclass'=>'fieldrequired', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'name' => 'clone_date_value', 'label' => $langs->trans("DateValue"), 'value' => -1); + $formquestion[] = array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($accountid, "accountid", 0, '', 1)); + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 300); + } + dol_fiche_head($head, 'card', $langs->trans("VariousPayment"), -1, $object->picto); $morehtmlref = '
'; @@ -542,6 +614,12 @@ if ($id) // TODO // Add button modify + // Clone + if ($user->rights->banque->modifier) + { + print '"; + } + // Delete if (empty($object->rappro)) { @@ -550,7 +628,7 @@ if ($id) if ($alreadyaccounted) { print ''; } else { - print ''; + print ''; } } else { print ''; diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php index 7a89fd77986..744daa939d5 100644 --- a/htdocs/compta/bank/various_payment/document.php +++ b/htdocs/compta/bank/various_payment/document.php @@ -34,7 +34,7 @@ $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -44,8 +44,8 @@ $result = restrictedArea($user, 'banque', '', '', ''); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index 09193b3ee91..2fb2c56fc46 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -2,6 +2,7 @@ /* Copyright (C) 2017-2019 Alexandre Spangaro * Copyright (C) 2017 Laurent Destailleur * Copyright (C) 2018 Frédéric France + * Copyright (C) 2020 Tobias Sekan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -29,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page $langs->loadLangs(array("compta", "banks", "bills", "accountancy")); @@ -44,11 +46,14 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $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_datep_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); +$search_datep_end = dol_mktime(23, 59, 59, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); +$search_datev_start = dol_mktime(0, 0, 0, GETPOST('search_date_value_startmonth', 'int'), GETPOST('search_date_value_startday', 'int'), GETPOST('search_date_value_startyear', 'int')); +$search_datev_end = dol_mktime(23, 59, 59, GETPOST('search_date_value_endmonth', 'int'), GETPOST('search_date_value_endday', 'int'), GETPOST('search_date_value_endyear', 'int')); $search_amount_deb = GETPOST('search_amount_deb', 'alpha'); $search_amount_cred = GETPOST('search_amount_cred', 'alpha'); -$search_account = GETPOST('search_account', 'int'); +$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 = ''; $search_accountancy_subledger = GETPOST("search_accountancy_subledger"); @@ -81,31 +86,97 @@ if (!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 { - $search_ref = ""; - $search_label = ""; - $search_date_start = ''; - $search_date_end = ''; - $search_amount_deb = ""; - $search_amount_cred = ""; - $search_account = ''; + $search_ref = ''; + $search_label = ''; + $search_datep_start = ''; + $search_datep_end = ''; + $search_datev_start = ''; + $search_datev_end = ''; + $search_amount_deb = ''; + $search_amount_cred = ''; + $search_bank_account = ''; + $search_bank_entry = ''; $search_accountancy_account = ''; $search_accountancy_subledger = ''; - $typeid = ""; + $typeid = ''; } +$search_all = GETPOSTISSET("search_all") ? trim(GETPOST("search_all", 'alpha')) : trim(GETPOST('sall')); + +/* +* TODO: fill array "$fields" in "/compta/bank/class/paymentvarious.class.php" and use +* +* +* $object = new PaymentVarious($db); +* +* $search = array(); +* foreach ($object->fields as $key => $val) +* { +* if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +* } + +* $fieldstosearchall = array(); +* foreach ($object->fields as $key => $val) +* { +* if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +* } +* +*/ + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array( + 'v.rowid'=>"Ref", + 'v.label'=>"Label", + 'v.datep'=>"DatePayment", + 'v.datev'=>"DateValue", + 'v.amount'=>$langs->trans("Debit").", ".$langs->trans("Credit"), +); + +// Definition of fields for lists +$arrayfields = array( + 'ref' =>array('label'=>"Ref", 'checked'=>1, 'position'=>100), + 'label' =>array('label'=>"Label", 'checked'=>1, 'position'=>110), + 'datep' =>array('label'=>"DatePayment", 'checked'=>1, 'position'=>120), + 'datev' =>array('label'=>"DateValue", 'checked'=>1, 'position'=>130), + 'type' =>array('label'=>"PaymentMode", 'checked'=>1, 'position'=>140), + 'project' =>array('label'=>"Project", 'checked'=>1, 'position'=>200, "enabled"=>!empty($conf->projet->enabled)), + 'bank' =>array('label'=>"BankAccount", 'checked'=>1, 'position'=>300, "enabled"=>!empty($conf->banque->enabled)), + 'entry' =>array('label'=>"BankTransactionLine", 'checked'=>1, 'position'=>310, "enabled"=>!empty($conf->banque->enabled)), + 'account' =>array('label'=>"AccountAccountingShort", 'checked'=>1, 'position'=>400, "enabled"=>!empty($conf->accounting->enabled)), + 'subledger' =>array('label'=>"SubledgerAccount", 'checked'=>1, 'position'=>410, "enabled"=>!empty($conf->accounting->enabled)), + 'debit' =>array('label'=>"Debit", 'checked'=>1, 'position'=>500), + 'credit' =>array('label'=>"Credit", 'checked'=>1, 'position'=>510), +); + +$arrayfields = dol_sort_array($arrayfields, 'position'); + +/* + * 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 (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; +} /* * View */ -llxHeader(); - $form = new Form($db); -$formaccounting = new FormAccounting($db); -$variousstatic = new PaymentVarious($db); -$accountstatic = new Account($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,"; +$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,"; $sql .= " pst.code as payment_code"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as v"; @@ -117,11 +188,14 @@ $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_date_start) $sql .= " AND v.datep >= '".$db->idate($search_date_start)."'"; -if ($search_date_end) $sql .= " AND v.datep <= '".$db->idate($search_date_end)."'"; +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_account > 0) $sql .= " AND b.fk_account=".$db->escape($search_account); +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; @@ -129,6 +203,7 @@ if ($filtre) { $filtre = str_replace(":", "=", $filtre); $sql .= " AND ".$filtre; } +if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); $sql .= $db->order($sortfield, $sortorder); @@ -144,6 +219,19 @@ $result = $db->query($sql); 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) + { + $obj = $db->fetch_object($result); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/compta/bank/various_payment/card.php?id='.$id); + exit; + } + + // must be place behind the last "header(...)" call + llxHeader(); + $i = 0; $total = 0; @@ -152,22 +240,22 @@ if ($result) 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_date_start) $param .= '&search_date_start='.urlencode($search_date_start); - if ($search_date_end) $param .= '&search_date_end='.urlencode($search_date_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_account > 0) $param .= '&search_amount='.urlencode($search_account); + 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 ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - $newcardbutton = ''; - if ($user->rights->banque->modifier) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('MenuNewVariousPayment'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create'); - } + $url = DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('MenuNewVariousPayment'), '', 'fa fa-plus-circle', $url, '', $user->rights->banque->modifier); print ''; @@ -177,59 +265,106 @@ if ($result) print ''; print ''; print ''; + print ''; 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); + print '
'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
'; + } + + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + print '
'; - print '
'."\n"; + print '
'; print ''; + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + } + // Ref - print ''; + if ($arrayfields['ref']['checked']) { + print ''; + } // Label - print ''; - - // Date - print ''; - - // Type - print ''; - - // Account - if (!empty($conf->banque->enabled)) - { + if ($arrayfields['label']['checked']) { print ''; + } + + // Payment date + if ($arrayfields['datep']['checked']) { + print ''; + } + + // Value date + if ($arrayfields['datev']['checked']) { + print ''; + } + + // Payment type + if ($arrayfields['type']['checked']) { + print ''; + } + + // Project + if ($arrayfields['project']['checked']) { + print ''; + } + + // Bank account + if ($arrayfields['bank']['checked']) { + print ''; + } + + // Bank entry + if ($arrayfields['entry']['checked']) { + print ''; } // Accounting account - if (!empty($conf->accounting->enabled)) - { - // Accounting account + if ($arrayfields['account']['checked']) { print ''; + } - // Subledger account + // Subledger account + if ($arrayfields['subledger']['checked']) { print ''; + if ($arrayfields['debit']['checked']) { + print ''; + } // Credit - print ''; + if ($arrayfields['credit']['checked']) { + print ''; + } print ''; - print "\n"; - + print ''; print ''; - print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "v.rowid", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "v.label", "", $param, '', $sortfield, $sortorder, 'left '); - print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "v.datep,v.rowid", "", $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("PaymentMode", $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'left '); - if (!empty($conf->banque->enabled)) print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); - if (!empty($conf->accounting->enabled)) print_liste_field_titre("AccountAccountingShort", $_SERVER["PHP_SELF"], "v.accountancy_code", "", $param, '', $sortfield, $sortorder, 'left '); - if (!empty($conf->accounting->enabled)) print_liste_field_titre("SubledgerAccount", $_SERVER["PHP_SELF"], "v.subledger_account", "", $param, '', $sortfield, $sortorder, 'left '); - print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "v.amount", "", $param, '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "v.amount", "", $param, '', $sortfield, $sortorder, 'right '); - print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; + + 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 '); + + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); + print ''; $totalarray = array(); @@ -272,28 +426,53 @@ if ($result) print ''; - $variousstatic->id = $obj->rowid; - $variousstatic->ref = $obj->rowid; + // No + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + } // Ref - print "\n"; - if (!$i) $totalarray['nbfield']++; + if ($arrayfields['ref']['checked']) { + $variousstatic->id = $obj->rowid; + $variousstatic->ref = $obj->rowid; + print ""; + if (!$i) $totalarray['nbfield']++; + } // Label payment - print "\n"; - if (!$i) $totalarray['nbfield']++; + if ($arrayfields['label']['checked']) { + print ""; + if (!$i) $totalarray['nbfield']++; + } // Date payment - print '\n"; - if (!$i) $totalarray['nbfield']++; + if ($arrayfields['datep']['checked']) { + print '"; + if (!$i) $totalarray['nbfield']++; + } + + + // Date value + if ($arrayfields['datev']['checked']) { + print '"; + if (!$i) $totalarray['nbfield']++; + } // Type - print ''; - if (!$i) $totalarray['nbfield']++; + if ($arrayfields['type']['checked']) { + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Account - if (!empty($conf->banque->enabled)) - { + // Project + if ($arrayfields['project']['checked']) { + $proj->fetch($obj->fk_project); + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Bank account + if ($arrayfields['bank']['checked']) { print ''; if (!$i) $totalarray['nbfield']++; } + // Bank entry + if ($arrayfields['entry']['checked']) { + $bankline->fetch($obj->fk_bank); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Accounting account - if (!empty($conf->accounting->enabled)) { - $accountingaccount = new AccountingAccount($db); + if ($arrayfields['account']['checked']) { $accountingaccount->fetch('', $obj->accountancy_code, 1); print ''; @@ -326,38 +511,42 @@ if ($result) } // Accounting subledger account - if (!empty($conf->accounting->enabled)) - { + if ($arrayfields['subledger']['checked']) { print ''; if (!$i) $totalarray['nbfield']++; } // Debit - print ''; } - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'total_deb'; - print ''; // Credit - print ''; } - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'total_cred'; - print ''; + print ''; if (!$i) $totalarray['nbfield']++; - print "\n"; + print ""; $i++; } diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index 0279ad5143c..2adf3a01a83 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -63,8 +63,8 @@ $id = GETPOST('id', 'int'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; @@ -98,7 +98,7 @@ if ($user->socid > 0) // Protection if external user //$result = restrictedArea($user, 'monmodule', $id, ''); // Initialize array of search criterias -$search_all = trim(GETPOST("search_all", 'alpha')); +$search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index f2d8e38fb15..02299788794 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -297,8 +297,8 @@ if ($resql) /* $sql = "UPDATE ".MAIN_DB_PREFIX."pos_cash_fence "; $sql .= "SET"; - $sql .= " cash='".$cash."'"; - $sql .= ", card='".$bank."'"; + $sql .= " cash='".$db->escape($cash)."'"; + $sql .= ", card='".$db->escape($bank)."'"; $sql .= " where rowid=".$id; $db->query($sql); */ diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index 5632e8ebc1a..1b4e86bbb4c 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -66,7 +66,7 @@ $thirdpartystatic = new Societe($db); if ($action == 'note') { - $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET note='".$note."' WHERE rowid=".$socid; + $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET note='".$db->escape($note)."' WHERE rowid=".$socid; $result = $db->query($sql); } diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 4d3ec6b1ee6..fcd7c542eb2 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -31,7 +31,7 @@ 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)) { - require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -43,7 +43,7 @@ $id = GETPOST('id', 'int'); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'deplacement', $id, ''); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $object = new Deplacement($db); @@ -62,138 +62,138 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, if ($action == 'validate' && $user->rights->deplacement->creer) { - $object->fetch($id); - if ($object->statut == Deplacement::STATUS_DRAFT) - { - $result = $object->setStatut(1); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->fetch($id); + if ($object->statut == Deplacement::STATUS_DRAFT) + { + $result = $object->setStatut(1); + 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) { - $object->fetch($id); - if ($object->statut == Deplacement::STATUS_VALIDATED) - { - $result = $object->setStatut(Deplacement::STATUS_REFUNDED); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->fetch($id); + if ($object->statut == Deplacement::STATUS_VALIDATED) + { + $result = $object->setStatut(Deplacement::STATUS_REFUNDED); + 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) { - $result = $object->delete($id); - if ($result >= 0) - { - header("Location: index.php"); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->delete($id); + 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')) - { - $error = 0; + if (!GETPOST('cancel', 'alpha')) + { + $error = 0; - $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount - $object->type = GETPOST('type', 'alpha'); - $object->socid = (int) GETPOST('socid', 'int'); - $object->fk_user = (int) GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); - $object->note_public = GETPOST('note_public', 'alpha'); - $object->statut = Deplacement::STATUS_DRAFT; + $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->type = GETPOST('type', 'alpha'); + $object->socid = (int) GETPOST('socid', 'int'); + $object->fk_user = (int) GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); + $object->note_public = GETPOST('note_public', 'alpha'); + $object->statut = Deplacement::STATUS_DRAFT; - if (!$object->date) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - $error++; - } - if ($object->type == '-1') - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error++; - } - if (!($object->fk_user > 0)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); - $error++; - } + if (!$object->date) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + $error++; + } + if ($object->type == '-1') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error++; + } + if (!($object->fk_user > 0)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); + $error++; + } - if (!$error) - { - $id = $object->create($user); + if (!$error) + { + $id = $object->create($user); - if ($id > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; - } - } else { - $action = 'create'; - } - } else { - header("Location: index.php"); - exit; - } + if ($id > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } else { + $action = 'create'; + } + } else { + header("Location: index.php"); + exit; + } } // Update record elseif ($action == 'update' && $user->rights->deplacement->creer) { - if (!GETPOST('cancel', 'alpha')) - { - $result = $object->fetch($id); + if (!GETPOST('cancel', 'alpha')) + { + $result = $object->fetch($id); - $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount - $object->type = GETPOST('type', 'alpha'); - $object->socid = (int) GETPOST('socid', 'int'); - $object->fk_user = (int) GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); - $object->note_public = GETPOST('note_public', 'alpha'); + $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->type = GETPOST('type', 'alpha'); + $object->socid = (int) GETPOST('socid', 'int'); + $object->fk_user = (int) GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); + $object->note_public = GETPOST('note_public', 'alpha'); - $result = $object->update($user); + $result = $object->update($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } } // Set into a project elseif ($action == 'classin' && $user->rights->deplacement->creer) { - $object->fetch($id); - $result = $object->setProject(GETPOST('projectid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + $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) { - $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); + $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) { - $object->fetch($id); - $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + $object->fetch($id); + $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); + if ($result < 0) dol_print_error($db, $object->error); } @@ -210,327 +210,327 @@ $form = new Form($db); */ if ($action == 'create') { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + //WYSIWYG Editor + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - print load_fiche_titre($langs->trans("NewTrip")); + print load_fiche_titre($langs->trans("NewTrip")); - $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - print ''."\n"; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; - print '
'; + print ''; - print ''; - print ''; + print ''; + print ''; - print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1); - print '
'; - print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1); - - print '
'; - print '
'; - $form->select_types_paiements($typeid, 'typeid', '', 0, 1, 1, 16); - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); + print ''; + print ''; + print '
'; + print $form->selectDate($search_datep_start ? $search_datep_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search_datep_end ? $search_datep_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + print '
'; + print '
'; + print $form->selectDate($search_datev_start ? $search_datev_start : -1, 'search_date_value_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search_datev_end ? $search_datev_end : -1, 'search_date_value_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + print '
'; + $form->select_types_paiements($typeid, 'typeid', '', 0, 1, 1, 16, 1, 'maxwidth100'); + print ''; + // TODO + print ''; + $form->select_comptes($search_bank_account, 'search_account', 0, '', 1, '', 0, 'maxwidth100'); + print ''; + print ''; print ''; print '
'; print $formaccounting->select_account($search_accountancy_account, 'search_accountancy_account', 1, array(), 1, 1, 'maxwidth200'); print '
'; print '
'; print '
'; print $formaccounting->select_auxaccount($search_accountancy_subledger, 'search_accountancy_subledger', 1, 'maxwidth200'); @@ -238,31 +373,50 @@ if ($result) } // Debit - print '
'; + print ''; + print ''; + print ''; + print ''; $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
'.(($offset * $limit) + $i).'".$variousstatic->getNomUrl(1)."".$variousstatic->getNomUrl(1)."".dol_trunc($obj->label, 40)."".dol_trunc($obj->label, 40)."'.dol_print_date($db->jdate($obj->datep), 'day')."'.dol_print_date($obj->datep, 'day')."'.dol_print_date($obj->datev, 'day')."'.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.''.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.''.$proj->getNomUrl(1).''; if ($obj->bid > 0) { @@ -303,22 +482,28 @@ if ($result) if (!empty($conf->accounting->enabled)) { $accountstatic->account_number = $obj->bank_account_number; - - $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($obj->accountancy_journal); $accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); } $accountstatic->label = $obj->blabel; print $accountstatic->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print ''.$bankline->getNomUrl(1).''.$accountingaccount->getNomUrl(0, 1, 1, '', 1).''.length_accounta($obj->subledger_account).''; - if ($obj->sens == 0) - { - print price($obj->amount); - $totalarray['val']['total_deb'] += $obj->amount; + if ($arrayfields['debit']['checked']) { + print ''; + 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'; + print ''; - if ($obj->sens == 1) - { - print price($obj->amount); - $totalarray['val']['total_cred'] += $obj->amount; + if ($arrayfields['credit']['checked']) { + print ''; + 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'; + print '
'; + print '
'; - print ""; - print ''; + print ""; + print ''; - print ""; - print ''; + print ""; + print ''; - print ""; - print ''; + print ""; + print ''; - // Km - print ''; + // Km + print ''; - // Company - print ""; - print ''; + // Company + print ""; + print ''; - // Public note - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''; - print ''; + print ''; + print ''; - } + print ''; + } - // 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; + // 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; - print '
'.$langs->trans("Type").''; - $form->select_type_fees(GETPOST('type', 'int'), 'type', 1); - print '
'.$langs->trans("Type").''; + $form->select_type_fees(GETPOST('type', 'int'), 'type', 1); + print '
'.$langs->trans("Person").''; - print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - print '
'.$langs->trans("Person").''; + print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print '
'.$langs->trans("Date").''; - print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1); - print '
'.$langs->trans("Date").''; + print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1); + print '
'.$langs->trans("FeesKilometersOrAmout").'
'.$langs->trans("FeesKilometersOrAmout").'
'.$langs->trans("CompanyVisited").''; - print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1); - print '
'.$langs->trans("CompanyVisited").''; + print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1); + print '
'.$langs->trans('NotePublic').''; + // Public note + print '
'.$langs->trans('NotePublic').''; - $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print '
'.$langs->trans('NotePrivate').''; + // Private note + if (empty($user->socid)) + { + print '
'.$langs->trans('NotePrivate').''; - $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print '
'; + print ''; - print '
'; + print '
'; print ''; print '     '; - print ''; + print ''; print '
'; - print ''; + print ''; } elseif ($id) { - $result = $object->fetch($id); - if ($result > 0) - { - $head = trip_prepare_head($object); + $result = $object->fetch($id); + if ($result > 0) + { + $head = trip_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip'); + dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip'); - if ($action == 'edit' && $user->rights->deplacement->creer) - { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + 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) - { - $soc->fetch($object->socid); - } + $soc = new Societe($db); + if ($object->socid) + { + $soc->fetch($object->socid); + } - print '
'."\n"; - print ''; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; + print ''; - print ''; + print '
'; - // Ref - print ""; - print ''; + // Ref + print ""; + print ''; - // Type - print ""; - print ''; + // Type + print ""; + print ''; - // Who - print ""; - print ''; + // Who + print ""; + print ''; - // Date - print ''; + // Date + print ''; - // Km - print ''; + // Km + print ''; - // Where - print ""; - print ''; + // Where + print ""; + print ''; - // Public note - print ''; - print ''; + print '"; + print ""; - // Private note - if (empty($user->socid)) - { - print ''; - print ''; + print '"; - } + print ""; + } - // 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; + // 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; - print '
'.$langs->trans("Ref").''; - print $object->ref; - print '
'.$langs->trans("Ref").''; + print $object->ref; + print '
'.$langs->trans("Type").''; - $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0); - print '
'.$langs->trans("Type").''; + $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0); + print '
'.$langs->trans("Person").''; - print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - print '
'.$langs->trans("Person").''; + print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print '
'.$langs->trans("Date").''; - print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0); - print '
'.$langs->trans("Date").''; + print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0); + print '
'.$langs->trans("FeesKilometersOrAmout").''; - print ''; - print '
'.$langs->trans("FeesKilometersOrAmout").''; + print ''; + print '
'.$langs->trans("CompanyVisited").''; - print $form->select_company($soc->id, 'socid', '', 1); - print '
'.$langs->trans("CompanyVisited").''; + print $form->select_company($soc->id, 'socid', '', 1); + print '
'.$langs->trans("NotePublic").''; + // Public note + print '
'.$langs->trans("NotePublic").''; - $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print "
'.$langs->trans("NotePrivate").''; + // Private note + if (empty($user->socid)) + { + print '
'.$langs->trans("NotePrivate").''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print "
'; + print ''; - print '
'; + print '
'; print ''; print '     '; - print ''; - print '
'; + print ''; + print '
'; - print '
'; + print ''; - print '
'; - } else { - /* + print '
'; + } else { + /* * Confirm delete trip */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete"); - } + 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); + $soc = new Societe($db); + if ($object->socid) $soc->fetch($object->socid); - print ''; + print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; + // Ref + print ''; - $form->load_cache_types_fees(); + $form->load_cache_types_fees(); - // Type - print ''; + // Type + print ''; - // Who - print ''; + // Who + print ''; - // Date - print ''; + // Date + print ''; - // Km/Price - print '"; + // Km/Price + print '"; - // Where - print ''; - print ''; + // Where + print ''; + print ''; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load('projects'); - print ''; - print ''; + print ''; - print ''; - } + print '
'.$langs->trans("Ref").''; - print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); - print '
'.$langs->trans("Ref").''; + print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); + print '
'; - print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees'); - print ''; - print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees'); - print '
'; + print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees'); + print ''; + print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees'); + print '
'.$langs->trans("Person").''; - $userfee = new User($db); - $userfee->fetch($object->fk_user); - print $userfee->getNomUrl(1); - print '
'.$langs->trans("Person").''; + $userfee = new User($db); + $userfee->fetch($object->fk_user); + print $userfee->getNomUrl(1); + print '
'; - print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); - print ''; - print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); - print '
'; + print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); + print ''; + print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); + print '
'; - print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); - print ''; - print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); - print "
'; + print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); + print ''; + print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); + print "
'.$langs->trans("CompanyVisited").''; - if ($soc->id) print $soc->getNomUrl(1); - print '
'.$langs->trans("CompanyVisited").''; + if ($soc->id) print $soc->getNomUrl(1); + print '
'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load('projects'); + print '
'; - print ''; - 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') - { - $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); - } - print '
'; + 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') + { + $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); + } + print ''; + print ''; + } - // Statut - print ''.$langs->trans("Status").''.$object->getLibStatut(4).''; + // Statut + print ''.$langs->trans("Status").''.$object->getLibStatut(4).''; - // Other attributes - $parameters = array('socid'=>$object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $parameters = array('socid'=>$object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print "
"; + print "
"; - // Notes - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + // Notes + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - print '
'; + print '
'; - /* + /* * Barre d'actions */ - print '
'; + print '
'; - 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_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) - { - print ''.$langs->trans('Validate').''; - } else { - print ''.$langs->trans('Validate').''; - } - } + 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) - { - print ''.$langs->trans('ClassifyRefunded').''; - } else { - print ''.$langs->trans('ClassifyRefunded').''; - } - } + 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) - { - print ''.$langs->trans('Delete').''; - } else { - print ''.$langs->trans('Delete').''; - } + if ($user->rights->deplacement->supprimer) + { + print ''.$langs->trans('Delete').''; + } else { + print ''.$langs->trans('Delete').''; + } - print '
'; - } - } else { - dol_print_error($db); - } + print '
'; + } + } else { + dol_print_error($db); + } } // End of page diff --git a/htdocs/compta/deplacement/class/deplacementstats.class.php b/htdocs/compta/deplacement/class/deplacementstats.class.php index 6fdd54095a2..953ee78a3d6 100644 --- a/htdocs/compta/deplacement/class/deplacementstats.class.php +++ b/htdocs/compta/deplacement/class/deplacementstats.class.php @@ -122,7 +122,7 @@ class DeplacementStats extends Stats { $sql = "SELECT date_format(dated,'%m') as dm, sum(".$this->field.")"; $sql .= " FROM ".$this->from; - $sql .= " WHERE date_format(dated,'%Y') = '".$year."'"; + $sql .= " WHERE date_format(dated,'%Y') = '".$this->db->escape($year)."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -142,7 +142,7 @@ class DeplacementStats extends Stats { $sql = "SELECT date_format(dated,'%m') as dm, avg(".$this->field.")"; $sql .= " FROM ".$this->from; - $sql .= " WHERE date_format(dated,'%Y') = '".$year."'"; + $sql .= " WHERE date_format(dated,'%Y') = '".$this->db->escape($year)."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php index 889eb390ca2..47b1709ff60 100644 --- a/htdocs/compta/deplacement/document.php +++ b/htdocs/compta/deplacement/document.php @@ -39,7 +39,7 @@ $langs->loadLangs(array('other', 'trips', 'companies', 'interventions')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -49,8 +49,8 @@ $result = restrictedArea($user, 'deplacement', $id, ''); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index 55d4141fc07..df5cb39f9e4 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -40,7 +40,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'facture'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php index feeca2046d6..a8d073958ad 100644 --- a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'facture_rec'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index 87467f0dba6..ebe2a437a92 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'facturedet'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php index 32a7a8cb75a..a09b0380f59 100644 --- a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'facturedet_rec'; //Must be the $table_element of the class that manage extrafield diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index cc3a0769e70..3ab212a62bd 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -188,11 +188,11 @@ if (empty($reshook)) if (!$error) { - $object->titre = GETPOST('titre', 'nohtml'); // deprecated - $object->title = GETPOST('titre', 'nohtml'); - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); - $object->modelpdf = GETPOST('modelpdf', 'alpha'); + $object->titre = GETPOST('title', 'nohtml'); // deprecated + $object->title = GETPOST('title', 'nohtml'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->model_pdf = GETPOST('modelpdf', 'alpha'); $object->usenewprice = GETPOST('usenewprice', 'alpha'); $object->frequency = $frequency; @@ -405,7 +405,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -650,7 +650,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model=$object->modelpdf; + $model=$object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -713,7 +713,7 @@ if (empty($reshook)) $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', 'none') ? GETPOST('product_desc', 'none') : GETPOST('desc', 'none')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml')); $pu_ht = GETPOST('price_ht'); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $qty = GETPOST('qty'); @@ -861,7 +861,7 @@ if (empty($reshook)) } $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ $object->fetch($object->id); // Reload lines @@ -964,8 +964,8 @@ if ($action == 'create') print ''.$langs->trans("Customer").''.$object->thirdparty->getNomUrl(1, 'customer').''; print ''; - $note_public = GETPOST('note_public', 'none') ?GETPOST('note_public', 'none') : $object->note_public; - $note_private = GETPOST('note_private', 'none') ?GETPOST('note_private', 'none') : $object->note_private; + $note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : $object->note_public; + $note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : $object->note_private; // Help of substitution key $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); @@ -1365,6 +1365,8 @@ if ($action == 'create') // Only on template invoices $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date(($object->date_when ? $object->date_when : dol_now()), 'dayhour').')'; $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree(($object->date_when ? $object->date_when : dol_now()), $object->frequency, $object->unit_frequency), 'dayhour').')'; + $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $object->nb_gen_done; + $substitutionarray['__INVOICE_COUNTER_MAX__'] = $object->nb_gen_max; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; foreach ($substitutionarray as $key => $val) @@ -1425,9 +1427,9 @@ if ($action == 'create') $list[] = str_replace(':', '|', $k).':'.$model; } $select = 'select;'.implode(',', $list); - print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->modelpdf, $object, $user->rights->facture->creer, $select); + print $form->editfieldval($langs->trans("Model"), 'modelpdf', $object->model_pdf, $object, $user->rights->facture->creer, $select); } else { - print $object->modelpdf; + print $object->model_pdf; } print ""; print ''; @@ -1617,13 +1619,12 @@ if ($action == 'create') // Show object lines if (!empty($object->lines)) { - //$disableedit=1; - //$disablemove=1; + $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 == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') + if ($object->statut == $object::STATUS_DRAFT && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') { if ($action != 'editline') { diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 3d06f665e22..7b0d7fcf869 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -75,7 +75,7 @@ $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $lineid = GETPOST('lineid', 'int'); @@ -251,7 +251,7 @@ if (empty($reshook)) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } if ($result >= 0) { header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); @@ -458,7 +458,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -530,7 +530,7 @@ if (empty($reshook)) } $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'setref' && $usercancreate) @@ -644,7 +644,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -728,7 +728,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -746,8 +746,8 @@ if (empty($reshook)) elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) { $object->fetch($id); - $close_code = GETPOST("close_code", 'none'); - $close_note = GETPOST("close_note", 'none'); + $close_code = GETPOST("close_code", 'restricthtml'); + $close_note = GETPOST("close_note", 'restricthtml'); if ($close_code) { $result = $object->set_paid($user, $close_code, $close_note); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); @@ -757,8 +757,8 @@ if (empty($reshook)) } // Classify "abandoned" elseif ($action == 'confirm_canceled' && $confirm == 'yes') { $object->fetch($id); - $close_code = GETPOST("close_code", 'none'); - $close_note = GETPOST("close_note", 'none'); + $close_code = GETPOST("close_code", 'restricthtml'); + $close_note = GETPOST("close_note", 'restricthtml'); if ($close_code) { $result = $object->set_canceled($user, $close_code, $close_note); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); @@ -987,11 +987,11 @@ if (empty($reshook)) $object->date = $dateinvoice; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); + $object->note_public = trim(GETPOST('note_public', 'restricthtml')); // We do not copy the private note $object->ref_client = $_POST['ref_client']; $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; + $object->model_pdf = $_POST['model']; $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = $_POST['cond_reglement_id']; $object->mode_reglement_id = $_POST['mode_reglement_id']; @@ -1015,7 +1015,7 @@ if (empty($reshook)) } // Credit note invoice - if ($_POST['type'] == Facture::TYPE_CREDIT_NOTE) + if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) { $sourceinvoice = GETPOST('fac_avoir'); if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) @@ -1033,7 +1033,7 @@ if (empty($reshook)) $action = 'create'; } - $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); + $date_pointoftax = dol_mktime(12, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int')); if (!$error) { @@ -1041,20 +1041,19 @@ if (empty($reshook)) $object->entity = $originentity; } $object->socid = GETPOST('socid', 'int'); - $object->ref = $_POST['ref']; + $object->ref = GETPOST('ref'); $object->date = $dateinvoice; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); + $object->note_public = trim(GETPOST('note_public', 'restricthtml')); // We do not copy the private note - $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; + $object->ref_client = GETPOST('ref_client'); + $object->model_pdf = GETPOST('model'); + $object->fk_project = GETPOST('projectid', 'int'); $object->cond_reglement_id = 0; - $object->mode_reglement_id = $_POST['mode_reglement_id']; + $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; + $object->remise_absolue = GETPOST('remise_absolue'); + $object->remise_percent = GETPOST('remise_percent'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); @@ -1256,22 +1255,21 @@ if (empty($reshook)) if (!$error) { $object->socid = GETPOST('socid', 'int'); - $object->type = $_POST['type']; - $object->ref = $_POST['ref']; + $object->type = GETPOST('type'); + $object->ref = GETPOST('ref'); $object->date = $dateinvoice; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); - $object->note_private = trim(GETPOST('note_private', 'none')); - $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = ($_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id']); - $object->mode_reglement_id = $_POST['mode_reglement_id']; + $object->note_public = trim(GETPOST('note_public', 'restricthtml')); + $object->note_private = trim(GETPOST('note_private', 'restricthtml')); + $object->ref_client = GETPOST('ref_client'); + $object->model_pdf = GETPOST('model'); + $object->fk_project = GETPOST('projectid', 'int'); + $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id')); + $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int'); $object->fk_account = GETPOST('fk_account', 'int'); - $object->amount = $_POST['amount']; - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; + $object->amount = price2num(GETPOST('amount')); + $object->remise_absolue = GETPOST('remise_absolue'); + $object->remise_percent = GETPOST('remise_percent'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); @@ -1309,21 +1307,20 @@ if (empty($reshook)) // Si facture standard $object->socid = GETPOST('socid', 'int'); $object->type = GETPOST('type'); - $object->ref = $_POST['ref']; + $object->ref = GETPOST('ref'); $object->date = $dateinvoice; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); - $object->note_private = trim(GETPOST('note_private', 'none')); - $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = ($_POST['type'] == 3 ? 1 : $_POST['cond_reglement_id']); - $object->mode_reglement_id = $_POST['mode_reglement_id']; + $object->note_public = trim(GETPOST('note_public', 'restricthtml')); + $object->note_private = trim(GETPOST('note_private', 'restricthtml')); + $object->ref_client = GETPOST('ref_client'); + $object->model_pdf = GETPOST('model'); + $object->fk_project = GETPOST('projectid'); + $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id')); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); - $object->amount = $_POST['amount']; - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; + $object->amount = price2num(GETPOST('amount')); + $object->remise_absolue = GETPOST('remise_absolue'); + $object->remise_percent = GETPOST('remise_percent'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); @@ -1667,7 +1664,7 @@ if (empty($reshook)) $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 = '".$originforcontact."'"; + $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) @@ -1801,12 +1798,11 @@ if (empty($reshook)) $object->fetch_thirdparty(); $object->date = $datefacture; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim(GETPOST('note_public', 'none')); - $object->note = trim(GETPOST('note', 'none')); - $object->note_private = trim(GETPOST('note', 'none')); + $object->note_public = trim(GETPOST('note_public', 'restricthtml')); + $object->note = trim(GETPOST('note', 'restricthtml')); + $object->note_private = trim(GETPOST('note', 'restricthtml')); $object->ref_client = GETPOST('ref_client', 'alpha'); - $object->ref_int = GETPOST('ref_int', 'alpha'); - $object->modelpdf = GETPOST('model', 'alpha'); + $object->model_pdf = GETPOST('model', 'alpha'); $object->fk_project = GETPOST('projectid', 'int'); $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int'); $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int'); @@ -1851,7 +1847,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -1883,9 +1879,9 @@ if (empty($reshook)) // Set if we used free entry or predefined product $predef = ''; - $product_desc = (GETPOST('dp_desc', 'none') ?GETPOST('dp_desc', 'none') : ''); - $price_ht = GETPOST('price_ht'); - $price_ht_devise = GETPOST('multicurrency_price_ht'); + $product_desc = (GETPOST('dp_desc', 'none') ?GETPOST('dp_desc', 'restricthtml') : ''); + $price_ht = price2num(GETPOST('price_ht')); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht')); $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha'); if ($prod_entry_mode == 'free') { @@ -2016,7 +2012,7 @@ 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) || $price_ht === '0') { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); @@ -2145,7 +2141,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -2204,7 +2200,7 @@ if (empty($reshook)) $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', 'none') ? GETPOST('product_desc', 'none') : GETPOST('desc', 'none')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml')); $pu_ht = GETPOST('price_ht'); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $qty = GETPOST('qty'); @@ -2335,10 +2331,10 @@ if (empty($reshook)) } } - $result = $object->updateline(GETPOST('lineid'), $description, $pu_ht, $qty, GETPOST('remise_percent'), + $result = $object->updateline(GETPOST('lineid', 'int'), $description, $pu_ht, $qty, price2num(GETPOST('remise_percent', 'alpha')), $date_start, $date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $info_bits, $type, - GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOST('progress'), - $_POST['units'], $pu_ht_devise); + 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)) { @@ -2356,7 +2352,7 @@ if (empty($reshook)) } $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } unset($_POST['qty']); @@ -2629,7 +2625,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -3397,13 +3393,16 @@ if ($action == 'create') print ''; // Bank Account - if (GETPOSTISSET('fk_account')) { - $fk_account = GETPOST('fk_account'); - } + if (!empty($conf->banque->enabled)) + { + if (GETPOSTISSET('fk_account')) { + $fk_account = GETPOST('fk_account'); + } - print ''.$langs->trans('BankAccount').''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + print ''.$langs->trans('BankAccount').''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; + } // Project if (!empty($conf->projet->enabled)) @@ -3936,7 +3935,7 @@ if ($action == 'create') } } - if ($action == 'deletepaiement') + 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', '', 'no', 1); @@ -4264,22 +4263,25 @@ if ($action == 'create') } // Bank Account - print ''; - print ''; - print '
'; - print $langs->trans('BankAccount'); - print ''; - if (($action != 'editbankaccount') && $usercancreate) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
'; - print ''; - if ($action == 'editbankaccount') + if (!empty($conf->banque->enabled)) { - $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 ''; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if (($action != 'editbankaccount') && $usercancreate) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
'; + print ''; + 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 ""; + print ''; } - print ""; - print ''; // Incoterms if (!empty($conf->incoterm->enabled)) @@ -4414,44 +4416,50 @@ if ($action == 'create') print '
'; print '
'; + print ''."\n"; print ''; + $sign = 1; + if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_CREDIT_NOTE) { + $sign = -1; // We invert sign for output + } + 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 ''; } // Amount print ''; - print ''; + print ''; // Vat - print ''; + print ''; print ''; // Amount Local Taxes if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 { print ''; - print ''; + print ''; } if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 { print ''; - print ''; + print ''; } // Revenue stamp @@ -4509,13 +4517,11 @@ if ($action == 'create') } // Total with tax - print ''; + print ''; 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($sign * $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($sign * $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($sign * $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).'
'.price($sign * $object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).'
'.$langs->trans('AmountVAT').''.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'
'.$langs->trans('AmountVAT').''.price($sign * $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($sign * $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($sign * $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($sign * $object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'
'; - $sign = 1; - if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; $nbrows = 8; $nbcols = 3; if (!empty($conf->projet->enabled)) @@ -4658,6 +4664,8 @@ if ($action == 'create') print ''; } + $sign = 1; + if ($object->type == $object::TYPE_CREDIT_NOTE) $sign = -1; // List of payments already done @@ -4735,7 +4743,7 @@ if ($action == 'create') print ''; if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { - print 'rowid.'">'; + print 'rowid.'">'; print img_delete(); print ''; } @@ -5278,7 +5286,7 @@ if ($action == 'create') { print ''.$langs->trans('Delete').''; } else { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } } else { print ''.$langs->trans('Delete').''; @@ -5305,7 +5313,7 @@ if ($action == 'create') print $formfile->showdocuments( 'facture', $filename, $filedir, $urlsource, $genallowed, - $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', + $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang, '', $object, 0, 'remove_file_comfirm'); $somethingshown = $formfile->numoffiles; diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index c1ed5b809da..0ab4974ce7f 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -28,96 +28,96 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; */ class Invoices extends DolibarrApi { - /** - * - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid', - ); + /** + * + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + ); - /** - * @var Facture $invoice {@type Facture} - */ - public $invoice; + /** + * @var Facture $invoice {@type Facture} + */ + public $invoice; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->invoice = new Facture($this->db); - } - - /** - * Get properties of a invoice object - * - * Return an array with invoice informations - * - * @param int $id ID of invoice - * @param int $contact_list 0:Return array contains all properties, 1:Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id, $contact_list = 1) + /** + * Constructor + */ + public function __construct() { - return $this->_fetch($id, '', '', $contact_list); + global $db, $conf; + $this->db = $db; + $this->invoice = new Facture($this->db); } - /** - * Get properties of an invoice object by ref - * - * Return an array with invoice informations - * - * @param string $ref Ref of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException - */ - public function getByRef($ref, $contact_list = 1) - { - return $this->_fetch('', $ref, '', $contact_list); - } + /** + * Get properties of a invoice object + * + * Return an array with invoice informations + * + * @param int $id ID of invoice + * @param int $contact_list 0:Return array contains all properties, 1:Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id, $contact_list = 1) + { + return $this->_fetch($id, '', '', $contact_list); + } - /** - * Get properties of an invoice object by ref_ext - * - * Return an array with invoice informations - * - * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref_ext/{ref_ext} - * - * @throws RestException - */ - public function getByRefExt($ref_ext, $contact_list = 1) - { - return $this->_fetch('', '', $ref_ext, $contact_list); - } + /** + * Get properties of an invoice object by ref + * + * Return an array with invoice informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } - /** - * Get properties of an invoice object - * - * Return an array with invoice informations - * - * @param int $id ID of order + /** + * Get properties of an invoice object by ref_ext + * + * Return an array with invoice informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } + + /** + * Get properties of an invoice object + * + * Return an array with invoice informations + * + * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ - private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) - { + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } @@ -142,138 +142,138 @@ class Invoices extends DolibarrApi $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); - } + } - /** - * List invoices - * - * Get a list of invoices - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} - * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" - * @return array Array of invoice objects - * + /** + * List invoices + * + * Get a list of invoices + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of invoice objects + * * @throws RestException 404 Not found * @throws RestException 503 Error - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') - { - global $db, $conf; + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - // 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 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; - $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) - $sql .= " FROM ".MAIN_DB_PREFIX."facture as t"; + $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) + $sql .= " FROM ".MAIN_DB_PREFIX."facture 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('invoice').')'; - 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.")"; + $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')'; + 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 ($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 == 'unpaid') $sql .= " AND t.fk_statut IN (1)"; - if ($status == 'paid') $sql .= " AND t.fk_statut IN (2)"; - if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (3)"; - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; + if ($status == 'unpaid') $sql .= " AND t.fk_statut IN (1)"; + if ($status == 'paid') $sql .= " AND t.fk_statut IN (2)"; + if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (3)"; + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $db->order($sortfield, $sortorder); - if ($limit) - { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) + { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $db->query($sql); - if ($result) - { - $i = 0; - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $invoice_static = new Facture($db); - if ($invoice_static->fetch($obj->rowid)) - { - // Get payment details - $invoice_static->totalpaid = $invoice_static->getSommePaiement(); - $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed(); - $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed(); - $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT'); + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $invoice_static = new Facture($this->db); + if ($invoice_static->fetch($obj->rowid)) + { + // Get payment details + $invoice_static->totalpaid = $invoice_static->getSommePaiement(); + $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed(); + $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed(); + $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT'); // Add external contacts ids $invoice_static->contacts_ids = $invoice_static->liste_contact(-1, 'external', 1); - $obj_ret[] = $this->_cleanObjectDatas($invoice_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve invoice list : '.$db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No invoice found'); - } + $obj_ret[] = $this->_cleanObjectDatas($invoice_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No invoice found'); + } return $obj_ret; - } + } - /** - * Create invoice object - * - * @param array $request_data Request datas - * @return int ID of invoice - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { + /** + * Create invoice object + * + * @param array $request_data Request datas + * @return int ID of invoice + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401, "Insuffisant rights"); } - // Check mandatory fields - $result = $this->_validate($request_data); + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->invoice->$field = $value; - } - if (!array_key_exists('date', $request_data)) { - $this->invoice->date = dol_now(); - } - /* We keep lines as an array + foreach ($request_data as $field => $value) { + $this->invoice->$field = $value; + } + if (!array_key_exists('date', $request_data)) { + $this->invoice->date = dol_now(); + } + /* We keep lines as an array if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { @@ -282,152 +282,154 @@ class Invoices extends DolibarrApi $this->invoice->lines = $lines; }*/ - if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) { - throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors)); - } - return $this->invoice->id; - } + if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) { + throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors)); + } + return $this->invoice->id; + } - /** - * Create an invoice using an existing order. - * - * - * @param int $orderid Id of the order - * - * @url POST /createfromorder/{orderid} - * - * @return int - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function createInvoiceFromOrder($orderid) - { + /** + * Create an invoice using an existing order. + * + * + * @param int $orderid Id of the order + * + * @url POST /createfromorder/{orderid} + * + * @return int + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function createInvoiceFromOrder($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->commande->lire) { - throw new RestException(401); - } - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if (empty($orderid)) { - throw new RestException(400, 'Order ID is mandatory'); - } + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($orderid)) { + throw new RestException(400, 'Order ID is mandatory'); + } - $order = new Commande($this->db); - $result = $order->fetch($orderid); - if (!$result) { - throw new RestException(404, 'Order not found'); - } + $order = new Commande($this->db); + $result = $order->fetch($orderid); + if (!$result) { + throw new RestException(404, 'Order not found'); + } - $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(405, $this->invoice->error); - } - $this->invoice->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->invoice); - } + $result = $this->invoice->createFromOrder($order, DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(405, $this->invoice->error); + } + $this->invoice->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->invoice); + } - /** - * Get lines of an invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/lines - * - * @return int - */ - public function getLines($id) - { - if (!DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } + /** + * Get lines of an invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/lines + * + * @return int + */ + public function getLines($id) + { + if (!DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Update a line to a given invoice - * - * @param int $id Id of invoice to update - * @param int $lineid Id of line to update - * @param array $request_data InvoiceLine data - * - * @url PUT {id}/lines/{lineid} - * - * @return array - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 Invoice not found - */ - public function putLine($id, $lineid, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } + /** + * Update a line to a given invoice + * + * @param int $id Id of invoice to update + * @param int $lineid Id of line to update + * @param array $request_data InvoiceLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return array + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 Invoice not found + */ + public function putLine($id, $lineid, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } - if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->invoice->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->date_start, - $request_data->date_end, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $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->situation_percent, - $request_data->fk_unit, - $request_data->multicurrency_subprice - ); + if (!DolibarrApi::_checkAccessToResource('facture', $this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->invoice->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_start, + $request_data->date_end, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $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->situation_percent, + $request_data->fk_unit, + $request_data->multicurrency_subprice, + 0, + $request_data->ref_ext + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } else { - throw new RestException(304, $this->invoice->error); - } - } + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } else { + throw new RestException(304, $this->invoice->error); + } + } - /** + /** * Add a contact type of given invoice * * @param int $id Id of invoice to update @@ -438,45 +440,46 @@ class Invoices extends DolibarrApi * * @return int * - * @throws RestException 401 - * @throws RestException 404 + * @throws RestException 401 + * @throws RestException 404 */ - public function postContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } + public function postContact($id, $contactid, $type) + { + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); + $result = $this->invoice->fetch($id); if (!$result) { throw new RestException(404, 'Invoice not found'); } - if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { - throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); - } + if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { + throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); + } - if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { + if (!DolibarrApi::_checkAccessToResource('invoice', $this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->invoice->add_contact($contactid, $type, 'external'); + $result = $this->invoice->add_contact($contactid, $type, 'external'); - if (!$result) { - throw new RestException(500, 'Error when added the contact'); - } + if (!$result) { + throw new RestException(500, 'Error when added the contact'); + } - return $this->_cleanObjectDatas($this->invoice); - } + return $this->_cleanObjectDatas($this->invoice); + } - /** + /** * Delete a contact type of given invoice * * @param int $id Id of invoice to update - * @param int $rowid Row key of the contact in the array contact_ids. + * @param int $contactid Row key of the contact in the array contact_ids. + * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). * - * @url DELETE {id}/contact/{rowid} + * @url DELETE {id}/contact/{contactid}/{type} * * @return array * @@ -484,7 +487,7 @@ class Invoices extends DolibarrApi * @throws RestException 404 * @throws RestException 500 */ - public function deleteContact($id, $rowid) + public function deleteContact($id, $contactid, $type) { if (!DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); @@ -500,10 +503,17 @@ class Invoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->invoice->delete_contact($rowid); - if ($result < 0) { - throw new RestException(500, 'Error when deleted the contact'); - } + $contacts = $this->invoice->liste_contact(); + + foreach ($contacts as $contact) { + if ($contact['id'] == $contactid && $contact['code'] == $type) { + $result = $this->invoice->delete_contact($contact['rowid']); + + if (!$result) { + throw new RestException(500, 'Error when deleted the contact'); + } + } + } return $this->_cleanObjectDatas($this->invoice); } @@ -704,7 +714,9 @@ class Invoices extends DolibarrApi $request_data->array_options, $request_data->situation_percent, $request_data->fk_prev_id, - $request_data->fk_unit + $request_data->fk_unit, + 0, + $request_data->ref_ext ); if ($updateRes < 0) { @@ -872,8 +884,8 @@ class Invoices extends DolibarrApi * Sets an invoice as paid * * @param int $id Order ID - * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple) - * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) + * @param string $close_code Code filled if we classify to 'Paid completely' when payment is not complete (for escompte for example) + * @param string $close_note Comment defined if we classify to 'Paid' when payment is not complete (for escompte for example) * * @url POST {id}/settopaid * @@ -984,6 +996,8 @@ class Invoices extends DolibarrApi */ public function markAsCreditAvailable($id) { + require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + if (!DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } @@ -1056,7 +1070,7 @@ class Invoices extends DolibarrApi // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT // Total payments - $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql = 'SELECT SUM(pf.amount) as total_payments'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql .= ' WHERE pf.fk_facture = '.$this->invoice->id; @@ -1066,7 +1080,7 @@ class Invoices extends DolibarrApi if (!$resql) dol_print_error($this->db); $res = $this->db->fetch_object($resql); - $total_paiements = $res->total_paiements; + $total_payments = $res->total_payments; // Total credit note and deposit $total_creditnote_and_deposit = 0; @@ -1079,7 +1093,7 @@ class Invoices extends DolibarrApi while ($obj = $this->db->fetch_object($resql)) $total_creditnote_and_deposit += $obj->amount_ttc; } else dol_print_error($this->db); - $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $this->invoice->total_ttc; + $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; @@ -1277,12 +1291,12 @@ class Invoices extends DolibarrApi * * @param int $id Id of invoice * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param int $paymentid {@from body} Payment mode Id {@min 1} * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} * @param int $accountid {@from body} Account Id {@min 1} - * @param string $num_paiement {@from body} Payment number (optional) - * @param string $comment {@from body} Note (optional) - * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $num_payment {@from body} Payment number (optional) + * @param string $comment {@from body} Note private (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paymentcode = 'CHQ') * @param string $chqbank {@from body} Issuer bank name (optional) * * @url POST {id}/payments @@ -1293,7 +1307,7 @@ class Invoices extends DolibarrApi * @throws RestException 401 * @throws RestException 404 */ - public function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') + public function addPayment($id, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '') { global $conf; @@ -1316,8 +1330,8 @@ class Invoices extends DolibarrApi } } - if (empty($paiementid)) { - throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + if (empty($paymentid)) { + throw new RestException(400, 'Payment ID or Payment Code is mandatory'); } @@ -1354,67 +1368,68 @@ class Invoices extends DolibarrApi // Creation of payment line - $paiement = new Paiement($this->db); - $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id - $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = $paiementid; - $paiement->paiementcode = dol_getIdFromCode($this->db, $paiementid, 'c_paiement', 'id', 'code', 1); - $paiement->num_paiement = $num_paiement; - $paiement->note = $comment; + $paymentobj = new Paiement($this->db); + $paymentobj->datepaye = $datepaye; + $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id + $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paymentobj->paiementid = $paymentid; + $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1); + $paymentobj->num_payment = $num_payment; + $paymentobj->note_private = $comment; - $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($paiement_id < 0) + $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices + if ($payment_id < 0) { $this->db->rollback(); - throw new RestException(400, 'Payment error : '.$paiement->error); + throw new RestException(400, 'Payment error : '.$paymentobj->error); } if (!empty($conf->banque->enabled)) { $label = '(CustomerInvoicePayment)'; - if ($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { - throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); } if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note - $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); + $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); if ($result < 0) { $this->db->rollback(); - throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); } } $this->db->commit(); - return $paiement_id; + return $payment_id; } /** * Add a payment to pay partially or completely one or several invoices. * Warning: Take care that all invoices are owned by the same customer. - * Example of value for parameter arrayofamounts: {"1": "99.99", "2": "10"} + * Example of value for parameter arrayofamounts: {"1": {"amount": "99.99", "multicurrency_amount": ""}, "2": {"amount": "", "multicurrency_amount": "10"}} * * @param array $arrayofamounts {@from body} Array with id of invoices with amount to pay for each invoice * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paiementid {@from body} Payment mode Id {@min 1} - * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} - * @param int $accountid {@from body} Account Id {@min 1} - * @param string $num_paiement {@from body} Payment number (optional) - * @param string $comment {@from body} Note (optional) - * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') - * @param string $chqbank {@from body} Issuer bank name (optional) + * @param int $paymentid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_payment {@from body} Payment number (optional) + * @param string $comment {@from body} Note private (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * @param string $ref_ext {@from body} External reference (optional) + * @param bool $accepthigherpayment {@from body} Accept higher payments that it remains to be paid (optional) * * @url POST /paymentsdistributed * * @return int Payment ID - * * @throws RestException 400 * @throws RestException 401 * @throws RestException 403 * @throws RestException 404 */ - public function addPaymentDistributed($arrayofamounts, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') + public function addPaymentDistributed($arrayofamounts, $datepaye, $paymentid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '', $ref_ext = '', $accepthigherpayment = false) { global $conf; @@ -1437,8 +1452,8 @@ class Invoices extends DolibarrApi throw new RestException(400, 'Account ID is mandatory'); } } - if (empty($paiementid)) { - throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + if (empty($paymentid)) { + throw new RestException(400, 'Payment ID or Payment Code is mandatory'); } $this->db->begin(); @@ -1447,7 +1462,7 @@ class Invoices extends DolibarrApi $multicurrency_amounts = array(); // Loop on each invoice to pay - foreach ($arrayofamounts as $id => $amount) + foreach ($arrayofamounts as $id => $amountarray) { $result = $this->invoice->fetch($id); if (!$result) { @@ -1455,68 +1470,134 @@ class Invoices extends DolibarrApi throw new RestException(404, 'Invoice ID '.$id.' not found'); } - // Calculate amount to pay - $totalpaye = $this->invoice->getSommePaiement(); - $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); - $totaldeposits = $this->invoice->getSumDepositsUsed(); - $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - if ($amount != 'remain') - { - if ($amount > $resteapayer) - { - $this->db->rollback(); - throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$resteapayer.')'); - } - $resteapayer = $amount; + if (($amountarray["amount"] == "remain" || $amountarray["amount"] > 0) && ($amountarray["multicurrency_amount"] == "remain" || $amountarray["multicurrency_amount"] > 0)) { + $this->db->rollback(); + throw new RestException(400, 'Payment in both currency '.$id.' ( amount: '.$amountarray["amount"].', multicurrency_amount: '.$amountarray["multicurrency_amount"].')'); } - // Clean parameters amount if payment is for a credit note - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = -$resteapayer; + + $is_multicurrency = 0; + $total_ttc = $this->invoice->total_ttc; + + if ($amountarray["multicurrency_amount"] > 0 || $amountarray["multicurrency_amount"] == "remain") { + $is_multicurrency = 1; + $total_ttc = $this->invoice->multicurrency_total_ttc; + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement($is_multicurrency); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed($is_multicurrency); + $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency); + $remainstopay = $amount = price2num($total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + if (!$is_multicurrency && $amountarray["amount"] != 'remain') + { + $amount = price2num($amountarray["amount"], 'MT'); + } + + if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') + { + $amount = price2num($amountarray["multicurrency_amount"], 'MT'); + } + + if ($amount > $remainstopay && !$accepthigherpayment) { + $this->db->rollback(); + throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')'); + } + + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $amount = -$amount; + } + + if ($is_multicurrency) { + $amounts[$id] = null; // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = -$newvalue; + $multicurrency_amounts[$id] = $amount; } else { - $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = $resteapayer; + $amounts[$id] = $amount; // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = $newvalue; + $multicurrency_amounts[$id] = null; } } // Creation of payment line - $paiement = new Paiement($this->db); - $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id - $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = $paiementid; - $paiement->paiementcode = dol_getIdFromCode($this->db, $paiementid, 'c_paiement', 'id', 'code', 1); - $paiement->num_paiement = $num_paiement; - $paiement->note = $comment; - $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($paiement_id < 0) + $paymentobj = new Paiement($this->db); + $paymentobj->datepaye = $datepaye; + $paymentobj->amounts = $amounts; // Array with all payments dispatching with invoice id + $paymentobj->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paymentobj->paiementid = $paymentid; + $paymentobj->paiementcode = dol_getIdFromCode($this->db, $paymentid, 'c_paiement', 'id', 'code', 1); + $paymentobj->num_payment = $num_payment; + $paymentobj->note_private = $comment; + $paymentobj->ref_ext = $ref_ext; + $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices + if ($payment_id < 0) { $this->db->rollback(); - throw new RestException(400, 'Payment error : '.$paiement->error); + throw new RestException(400, 'Payment error : '.$paymentobj->error); } if (!empty($conf->banque->enabled)) { $label = '(CustomerInvoicePayment)'; - if ($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { - throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); } if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note - $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); + $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); if ($result < 0) { $this->db->rollback(); - throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); } } $this->db->commit(); - return $paiement_id; + return $payment_id; + } + + /** + * Update a payment + * + * @param int $id Id of payment + * @param string $num_payment Payment number + * + * @url PUT payments/{id} + * + * @return array + * @throws RestException 400 Bad parameters + * @throws RestException 401 Not allowed + * @throws RestException 404 Not found + */ + public function putPayment($id, $num_payment = '') + { + require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; + + if (!DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Payment ID is mandatory'); + } + + $paymentobj = new Paiement($this->db); + $result = $paymentobj->fetch($id); + + if (!$result) { + throw new RestException(404, 'Payment not found'); + } + + if (!empty($num_payment)) { + $result = $paymentobj->update_num($num_payment); + if ($result < 0) { + throw new RestException(500, 'Error when updating the payment num'); + } + } + + return [ + 'success' => [ + 'code' => 200, + 'message' => 'Payment updated' + ] + ]; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 73b99341be3..d1a6abcdec3 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -74,6 +74,11 @@ class FactureRec extends CommonInvoice */ protected $table_ref_field = 'titre'; + /** + * @var string The label of recurring invoice + */ + public $title; + public $number; public $date; public $remise; @@ -155,7 +160,7 @@ class FactureRec extends CommonInvoice 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105), 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110), 'modelpdf' =>array('type'=>'varchar(255)', 'label'=>'Modelpdf', 'enabled'=>1, 'visible'=>-1, 'position'=>115), - 'last_gen' =>array('type'=>'varchar(7)', 'label'=>'Last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + 'date_last_gen' =>array('type'=>'varchar(7)', 'label'=>'Last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>120), 'unit_frequency' =>array('type'=>'varchar(2)', 'label'=>'Unit frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>125), 'date_when' =>array('type'=>'datetime', 'label'=>'Date when', 'enabled'=>1, 'visible'=>-1, 'position'=>130), 'date_last_gen' =>array('type'=>'datetime', 'label'=>'Date last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>135), @@ -277,8 +282,8 @@ class FactureRec extends CommonInvoice $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL"); $sql .= ", ".(!empty($this->modelpdf) ? ("'".$this->db->escape($this->modelpdf)."'") : "NULL"); $sql .= ", '".$this->db->escape($user->id)."'"; - $sql .= ", ".(!empty($facsrc->fk_project) ? "'".$facsrc->fk_project."'" : "null"); - $sql .= ", ".(!empty($facsrc->fk_account) ? "'".$facsrc->fk_account."'" : "null"); + $sql .= ", ".(!empty($facsrc->fk_project) ? "'".$this->db->escape($facsrc->fk_project)."'" : "null"); + $sql .= ", ".(!empty($facsrc->fk_account) ? "'".$this->db->escape($facsrc->fk_account)."'" : "null"); $sql .= ", ".($facsrc->cond_reglement_id > 0 ? $this->db->escape($facsrc->cond_reglement_id) : "null"); $sql .= ", ".($facsrc->mode_reglement_id > 0 ? $this->db->escape($facsrc->mode_reglement_id) : "null"); $sql .= ", ".$this->usenewprice; @@ -921,7 +926,7 @@ class FactureRec extends CommonInvoice $sql .= ", fk_unit"; $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; $sql .= ") VALUES ("; - $sql .= "'".$facid."'"; + $sql .= " ".((int) $facid); $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); $sql .= ", '".$this->db->escape($desc)."'"; $sql .= ", ".price2num($pu_ht); @@ -932,7 +937,7 @@ class FactureRec extends CommonInvoice $sql .= ", '".$this->db->escape($localtaxes_type[0])."'"; $sql .= ", ".price2num($txlocaltax2); $sql .= ", '".$this->db->escape($localtaxes_type[2])."'"; - $sql .= ", ".(!empty($fk_product) ? "'".$fk_product."'" : "null"); + $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); $sql .= ", ".$product_type; $sql .= ", ".price2num($remise_percent); $sql .= ", ".price2num($pu_ht); @@ -1083,7 +1088,7 @@ class FactureRec extends CommonInvoice } $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; - $sql .= "fk_facture = '".$facid."'"; + $sql .= "fk_facture = ".((int) $facid); $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); $sql .= ", description='".$this->db->escape($desc)."'"; $sql .= ", price=".price2num($pu_ht); @@ -1094,7 +1099,7 @@ class FactureRec extends CommonInvoice $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'"; $sql .= ", localtax2_tx=".$txlocaltax2; $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'"; - $sql .= ", fk_product=".(!empty($fk_product) ? "'".$fk_product."'" : "null"); + $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); $sql .= ", product_type=".$product_type; $sql .= ", remise_percent='".price2num($remise_percent)."'"; $sql .= ", subprice='".price2num($pu_ht)."'"; @@ -1194,13 +1199,13 @@ class FactureRec extends CommonInvoice $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec'; $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency - $sql .= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')"; + $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($today)."')"; $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)'; $sql .= ' AND suspended = 0'; $sql .= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here if ($restrictioninvoiceid > 0) $sql .= ' AND rowid = '.$restrictioninvoiceid; - $sql .= $db->order('entity', 'ASC'); + $sql .= $this->db->order('entity', 'ASC'); //print $sql;exit; $parameters = array( 'restrictioninvoiceid' => $restrictioninvoiceid, @@ -1208,11 +1213,11 @@ class FactureRec extends CommonInvoice ); $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks - $resql = $db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $i = 0; - $num = $db->num_rows($resql); + $num = $this->db->num_rows($resql); if ($num) $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n"; @@ -1222,14 +1227,14 @@ class FactureRec extends CommonInvoice while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass. { - $line = $db->fetch_object($resql); + $line = $this->db->fetch_object($resql); - $db->begin(); + $this->db->begin(); $invoiceidgenerated = 0; $facture = null; - $facturerec = new FactureRec($db); + $facturerec = new FactureRec($this->db); $facturerec->fetch($line->rowid); if ($facturerec->id > 0) @@ -1239,7 +1244,7 @@ class FactureRec extends CommonInvoice dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity); - $facture = new Facture($db); + $facture = new Facture($this->db); $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice @@ -1286,12 +1291,12 @@ class FactureRec extends CommonInvoice if (!$error && $invoiceidgenerated >= 0) { - $db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); + $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation"); $nb_create++; $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n"; } else { - $db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); + $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); } $parameters = array( @@ -1308,7 +1313,7 @@ class FactureRec extends CommonInvoice } $conf->entity = $saventity; // Restore entity context - } else dol_print_error($db); + } else dol_print_error($this->db); $this->output = trim($this->output); @@ -1555,6 +1560,8 @@ class FactureRec extends CommonInvoice $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->plimit(100); + $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 50b84840901..8ec349c79f4 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -7,7 +7,7 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2010-2016 Juanjo Menent + * Copyright (C) 2010-2020 Juanjo Menent * Copyright (C) 2012-2014 Christophe Battarel * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2012 Cédric Salvador @@ -100,13 +100,13 @@ class Facture extends CommonInvoice public $author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_valid; public $date; // Date invoice @@ -153,8 +153,8 @@ class Facture extends CommonInvoice public $mode_reglement_code; // Code in llx_c_paiement /** - * @var int ID Field to store bank id to use when payment mode is withdraw - */ + * @var int ID Field to store bank id to use when payment mode is withdraw + */ public $fk_bank; /** @@ -175,8 +175,8 @@ class Facture extends CommonInvoice // Multicurrency /** - * @var int ID - */ + * @var int ID + */ public $fk_multicurrency; public $multicurrency_code; @@ -323,30 +323,30 @@ class Facture extends CommonInvoice ); // END MODULEBUILDER PROPERTIES - /** - * Standard invoice - */ - const TYPE_STANDARD = 0; + /** + * Standard invoice + */ + const TYPE_STANDARD = 0; - /** - * Replacement invoice - */ - const TYPE_REPLACEMENT = 1; + /** + * Replacement invoice + */ + const TYPE_REPLACEMENT = 1; - /** - * Credit note invoice - */ - const TYPE_CREDIT_NOTE = 2; + /** + * Credit note invoice + */ + const TYPE_CREDIT_NOTE = 2; - /** - * Deposit invoice - */ - const TYPE_DEPOSIT = 3; + /** + * Deposit invoice + */ + const TYPE_DEPOSIT = 3; - /** - * Proforma invoice (should not be used. a proforma is an order) - */ - const TYPE_PROFORMA = 4; + /** + * Proforma invoice (should not be used. a proforma is an order) + */ + const TYPE_PROFORMA = 4; /** * Situation invoice @@ -407,7 +407,7 @@ class Facture extends CommonInvoice * @param int $forceduedate If set, do not recalculate due date from payment condition but force it with value * @return int <0 if KO, >0 if OK */ - public function create(User $user, $notrigger = 0, $forceduedate = 0) + public function create(User $user, $notrigger = 0, $forceduedate = 0) { global $langs, $conf, $mysoc, $hookmanager; $error = 0; @@ -458,10 +458,10 @@ class Facture extends CommonInvoice $nextdatewhen = null; $previousdaynextdatewhen = null; - // Create invoice from a template invoice + // Create invoice from a template recurring invoice if ($this->fac_rec > 0) { - $this->fk_fac_rec_source = $this->fac_rec; + $this->fk_fac_rec_source = $this->fac_rec; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; $_facrec = new FactureRec($this->db); @@ -481,8 +481,8 @@ class Facture extends CommonInvoice // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project; - $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'none') : $_facrec->note_public; - $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'none') : $_facrec->note_private; + $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public; + $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private; $this->modelpdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->modelpdf; $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id; $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id; @@ -503,9 +503,9 @@ class Facture extends CommonInvoice $this->ref_client = trim($this->ref_client); $this->note_public = trim($this->note_public); $this->note_private = trim($this->note_private); - $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); + $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref)); - $this->array_options = $_facrec->array_options; + $this->array_options = $_facrec->array_options; //if (! $this->remise) $this->remise = 0; if (!$this->mode_reglement_id) $this->mode_reglement_id = 0; @@ -520,12 +520,12 @@ class Facture extends CommonInvoice // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice if ($_facrec->frequency > 0) { - dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); - if (empty($_facrec->date_when)) $_facrec->date_when = $now; - $next_date = $_facrec->getNextDate(); // Calculate next date - $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); - //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. - $result = $_facrec->setNextDate($next_date, 1); + dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); + if (empty($_facrec->date_when)) $_facrec->date_when = $now; + $next_date = $_facrec->getNextDate(); // Calculate next date + $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); + //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. + $result = $_facrec->setNextDate($next_date, 1); } // Define lang of customer @@ -536,8 +536,8 @@ class Facture extends CommonInvoice if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) @@ -567,16 +567,16 @@ class Facture extends CommonInvoice } // Define due date if not already defined - if (empty($forceduedate)) { - $duedate = $this->calculate_date_lim_reglement(); - /*if ($duedate < 0) { Regression, a date can be negative if before 1970. + if (empty($forceduedate)) { + $duedate = $this->calculate_date_lim_reglement(); + /*if ($duedate < 0) { Regression, a date can be negative if before 1970. dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR); return -1; }*/ - $this->date_lim_reglement = $duedate; - } else { - $this->date_lim_reglement = $forceduedate; - } + $this->date_lim_reglement = $duedate; + } else { + $this->date_lim_reglement = $forceduedate; + } // Insert into database $socid = $this->socid; @@ -595,24 +595,24 @@ class Facture extends CommonInvoice $sql .= ", note_private"; $sql .= ", note_public"; $sql .= ", ref_client, ref_int"; - $sql .= ", fk_account"; + $sql .= ", fk_account"; $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet"; $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf"; $sql .= ", situation_cycle_ref, situation_counter, situation_final"; $sql .= ", fk_incoterms, location_incoterms"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ", retained_warranty"; - $sql .= ", retained_warranty_date_limit"; - $sql .= ", retained_warranty_fk_cond_reglement"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ", retained_warranty"; + $sql .= ", retained_warranty_date_limit"; + $sql .= ", retained_warranty_fk_cond_reglement"; $sql .= ")"; $sql .= " VALUES ("; $sql .= "'(PROV)'"; $sql .= ", ".setEntity($this); $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null"); $sql .= ", '".$this->db->escape($this->type)."'"; - $sql .= ", '".$socid."'"; + $sql .= ", ".((int) $socid); $sql .= ", '".$this->db->idate($now)."'"; $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL'); $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL'); @@ -627,7 +627,7 @@ class Facture extends CommonInvoice $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null"); $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null"); $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null"); - $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null"); + $sql .= ", ".($user->id > 0 ? (int) $user->id : "null"); $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); $sql .= ", ".$this->cond_reglement_id; $sql .= ", ".$this->mode_reglement_id; @@ -636,7 +636,7 @@ class Facture extends CommonInvoice $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null"); $sql .= ", ".($this->situation_final ? $this->situation_final : 0); $sql .= ", ".(int) $this->fk_incoterms; - $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql .= ", ".(double) $this->multicurrency_tx; @@ -667,27 +667,27 @@ class Facture extends CommonInvoice { 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) - { - $this->error = $this->db->lasterror(); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $tmp_origin_id; - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - $this->error = $this->db->lasterror(); - $error++; - } - } + 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) + { + $this->error = $this->db->lasterror(); + $error++; + } + } + } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + $this->error = $this->db->lasterror(); + $error++; + } + } } } @@ -698,33 +698,33 @@ class Facture extends CommonInvoice $originidforcontact = $this->origin_id; 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(null, '', null, '', 'OR', 1, 'sourcetype', 0); - 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; - break; // We take first one - } - } + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; + $exp = new Expedition($this->db); + $exp->fetch($this->origin_id); + $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); + 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; + break; // We take first one + } + } } $sqlcontact = "SELECT ctc.code, ctc.source, ec.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 = '".$originforcontact."'"; + $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)) - { - //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 - } + 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); } @@ -764,12 +764,12 @@ class Facture extends CommonInvoice $newinvoiceline->fk_parent_line = $fk_parent_line; if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) { - $discount = new DiscountAbsolute($this->db); - $discount->fetch($newinvoiceline->fk_remise_except); + $discount = new DiscountAbsolute($this->db); + $discount->fetch($newinvoiceline->fk_remise_except); - $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); - $newinvoiceline->fk_remise_except = $discountId; - } + $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx); + $newinvoiceline->fk_remise_except = $discountId; + } $result = $newinvoiceline->insert(); @@ -793,13 +793,13 @@ class Facture extends CommonInvoice foreach ($this->lines as $i => $val) { - $line = $this->lines[$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; + // 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 ($result >= 0) + if ($result >= 0) { // 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) { @@ -818,7 +818,12 @@ class Facture extends CommonInvoice $origintype = $this->element; } - $result = $this->addline( + // init ref_ext + if (empty($line->ref_ext)) { + $line->ref_ext = ''; + } + + $result = $this->addline( $line->desc, $line->subprice, $line->qty, @@ -837,8 +842,8 @@ class Facture extends CommonInvoice $line->product_type, $line->rang, $line->special_code, - $origintype, - $originid, + $origintype, + $originid, $fk_parent_line, $line->fk_fournprice, $line->pa_ht, @@ -847,7 +852,8 @@ class Facture extends CommonInvoice $line->situation_percent, $line->fk_prev_id, $line->fk_unit, - $line->pu_ht_devise + $line->pu_ht_devise, + $line->ref_ext ); if ($result < 0) { @@ -896,26 +902,26 @@ class Facture extends CommonInvoice $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice; // If buyprice not defined from template invoice, we try to guess the best value if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) - { - require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - $producttmp = new ProductFournisseur($this->db); - $producttmp->fetch($_facrec->lines[$i]->fk_product); + { + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; + $producttmp = new ProductFournisseur($this->db); + $producttmp->fetch($_facrec->lines[$i]->fk_product); - // If margin module defined on costprice, we try the costprice - // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price - // else we get the best supplier price - if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; - elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; - else { - if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) - { - if ($producttmp->product_fourn_price_id > 0) - { - $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); - } - } - } - } + // If margin module defined on costprice, we try the costprice + // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price + // else we get the best supplier price + if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; + elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; + else { + if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) + { + if ($producttmp->product_fourn_price_id > 0) + { + $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); + } + } + } + } $result_insert = $this->addline( $_facrec->lines[$i]->desc, @@ -939,7 +945,7 @@ class Facture extends CommonInvoice '', 0, 0, - $fk_product_fournisseur_price, + $fk_product_fournisseur_price, $buyprice, $_facrec->lines[$i]->label, empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options, @@ -968,17 +974,17 @@ class Facture extends CommonInvoice // Actions on extra fields if (!$error) { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; + $result = $this->insertExtraFields(); + if ($result < 0) $error++; } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILL_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILL_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } if (!$error) { @@ -1013,7 +1019,7 @@ class Facture extends CommonInvoice * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - public function createFromCurrent(User $user, $invertdetail = 0) + public function createFromCurrent(User $user, $invertdetail = 0) { global $conf; @@ -1024,13 +1030,13 @@ class Facture extends CommonInvoice // fetch optionals attributes and labels $this->fetch_optionals(); - if (!empty($this->array_options)) { - $facture->array_options = $this->array_options; - } + if (!empty($this->array_options)) { + $facture->array_options = $this->array_options; + } - foreach ($this->lines as &$line) { - $line->fetch_optionals(); //fetch extrafields - } + foreach ($this->lines as &$line) { + $line->fetch_optionals(); //fetch extrafields + } $facture->fk_facture_source = $this->fk_facture_source; $facture->type = $this->type; @@ -1056,9 +1062,9 @@ class Facture extends CommonInvoice $facture->situation_cycle_ref = $this->situation_cycle_ref; $facture->situation_final = $this->situation_final; - $facture->retained_warranty = $this->retained_warranty; - $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; - $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; + $facture->retained_warranty = $this->retained_warranty; + $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; + $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; // Loop on each line of new invoice @@ -1073,6 +1079,7 @@ class Facture extends CommonInvoice $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1; $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2; $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc; + $facture->lines[$i]->ref_ext = ''; } } @@ -1105,7 +1112,7 @@ class Facture extends CommonInvoice /** * Load an object from its id and create a new one in database * - * @param User $user User that clone + * @param User $user User that clone * @param int $fromid Id of object to clone * @return int New id of clone */ @@ -1128,11 +1135,11 @@ class Facture extends CommonInvoice if ($objsoc->fetch($this->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_project = ''; - $object->fk_delivery_address = ''; + $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_project = ''; + $object->fk_delivery_address = ''; } // TODO Change product price if multi-prices @@ -1161,14 +1168,14 @@ class Facture extends CommonInvoice // Loop on each line of new invoice foreach ($object->lines as $i => $line) { - if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts + if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts { - unset($object->lines[$i]); - unset($object->products[$i]); // Tant que products encore utilise + unset($object->lines[$i]); + unset($object->products[$i]); // Tant que products encore utilise } // Bloc to update dates of service (month by month only if previously filled at 1d near start or end of month) // If it's a service with start and end dates - if (!empty($line->date_start) && !empty($line->date_end) ) { + if (!empty($line->date_start) && !empty($line->date_end)) { // Get the dates $start = dol_getdate($line->date_start); $end = dol_getdate($line->date_end); @@ -1190,6 +1197,8 @@ class Facture extends CommonInvoice $object->lines[$i]->date_end = $newLast; } } + + $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext } // Create clone @@ -1198,13 +1207,13 @@ class Facture extends CommonInvoice if ($result < 0) $error++; else { // copy internal contacts - if ($object->copy_linked_contact($this, 'internal') < 0) + if ($object->copy_linked_contact($this, 'internal') < 0) $error++; // copy external contacts if same company elseif ($this->socid == $object->socid) { - if ($object->copy_linked_contact($this, 'external') < 0) + if ($object->copy_linked_contact($this, 'external') < 0) $error++; } } @@ -1241,7 +1250,7 @@ class Facture extends CommonInvoice * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - public function createFromOrder($object, User $user) + public function createFromOrder($object, User $user) { global $conf, $hookmanager; @@ -1294,7 +1303,7 @@ class Facture extends CommonInvoice $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht); $line->pa_ht = $marginInfos[0]; - // get extrafields from original line + // get extrafields from original line $object->lines[$i]->fetch_optionals(); foreach ($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; @@ -1316,17 +1325,17 @@ class Facture extends CommonInvoice if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { - $this->note_private = $object->note_private; - $this->note_public = $object->note_public; + $this->note_private = $object->note_private; + $this->note_public = $object->note_public; } - $this->module_source = $object->module_source; + $this->module_source = $object->module_source; $this->pos_source = $object->pos_source; $this->origin = $object->element; $this->origin_id = $object->id; - // get extrafields from original line + // get extrafields from original line $object->fetch_optionals(); foreach ($object->array_options as $options_key => $value) $this->array_options[$options_key] = $value; @@ -1365,13 +1374,13 @@ class Facture extends CommonInvoice * @param int $max Maxlength of ref * @param int $short 1=Return just URL * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $addlinktonotes 1=Add link to notes - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) + * @param int $notooltip 1=Disable tooltip + * @param int $addlinktonotes 1=Add link to notes + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...) * @return string String with URL */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '') { global $langs, $conf, $user, $mysoc; @@ -1382,8 +1391,8 @@ class Facture extends CommonInvoice if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id; else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id; - if (!$user->rights->facture->lire) - $option = 'nolink'; + if (!$user->rights->facture->lire) + $option = 'nolink'; if ($option !== 'nolink') { @@ -1399,56 +1408,56 @@ class Facture extends CommonInvoice 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 = ''; + $label = ''; - if ($user->rights->facture->lire) { - $label = ''.$langs->trans("Invoice").''; - if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("ReplacementInvoice").''; - if ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; - if ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; - if ($this->type == self::TYPE_SITUATION) $label = ''.$langs->transnoentitiesnoconv("InvoiceSituation").''; - if (!empty($this->ref)) - $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_client)) - $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; - if (!empty($this->date)) - $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); - 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)) - $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' - $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) - $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); - 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 (isset($this->statut) && isset($this->alreadypaid)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); - } - } + if ($user->rights->facture->lire) { + $label = img_picto('', $this->picto).' '.$langs->trans("Invoice").''; + if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("ReplacementInvoice").''; + if ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; + if ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; + if ($this->type == self::TYPE_SITUATION) $label = ''.$langs->transnoentitiesnoconv("InvoiceSituation").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_client)) + $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; + if (!empty($this->date)) + $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); + 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)) + $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' + $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) + $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); + 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 (isset($this->statut) && isset($this->alreadypaid)) { + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); + } + } $linkclose = ($target ? ' target="'.$target.'"' : ''); if (empty($notooltip) && $user->rights->facture->lire) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("Invoice"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("Invoice"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; } - $linkstart = ''; + $linkstart = ''; $linkend = ''; - if ($option == 'nolink') { - $linkstart = ''; - $linkend = ''; - } + if ($option == 'nolink') { + $linkstart = ''; + $linkend = ''; + } $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); @@ -1457,19 +1466,19 @@ class Facture extends CommonInvoice if ($addlinktonotes) { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); - $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); + $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } } return $result; @@ -1507,10 +1516,10 @@ class Facture extends CommonInvoice $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc"; $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; - $sql .= ', f.fk_incoterms, f.location_incoterms'; - $sql .= ', f.module_source, f.pos_source'; - $sql .= ", i.libelle as label_incoterms"; - $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; + $sql .= ', f.fk_incoterms, f.location_incoterms'; + $sql .= ', f.module_source, f.pos_source'; + $sql .= ", i.libelle as label_incoterms"; + $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement"; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; @@ -1581,7 +1590,8 @@ class Facture extends CommonInvoice $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; $this->user_valid = $obj->fk_user_valid; - $this->modelpdf = $obj->model_pdf; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated $this->last_main_doc = $obj->last_main_doc; $this->situation_cycle_ref = $obj->situation_cycle_ref; $this->situation_counter = $obj->situation_counter; @@ -1641,7 +1651,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load all detailed lines into this->lines * @@ -1653,11 +1663,11 @@ class Facture extends CommonInvoice public function fetch_lines($only_product = 0, $loadalsotranslation = 0) { global $langs, $conf; - // phpcs:enable + // phpcs:enable $this->lines = array(); $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; - $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; + $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,'; $sql .= ' l.situation_percent, l.fk_prev_id,'; $sql .= ' l.rang, l.special_code,'; $sql .= ' l.date_start as date_start, l.date_end as date_end,'; @@ -1696,8 +1706,9 @@ class Facture extends CommonInvoice $line->fk_product_type = $objp->fk_product_type; // Type of product $line->qty = $objp->qty; $line->subprice = $objp->subprice; + $line->ref_ext = $objp->ref_ext; // line external ref - $line->vat_src_code = $objp->vat_src_code; + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; @@ -1740,14 +1751,14 @@ class Facture extends CommonInvoice $line->multicurrency_total_tva = $objp->multicurrency_total_tva; $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $line->fetch_optionals(); + $line->fetch_optionals(); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { - $line = new Product($this->db); - $line->fetch($objp->fk_product); - $line->getMultiLangs(); - } + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) { + $line = new Product($this->db); + $line->fetch($objp->fk_product); + $line->getMultiLangs(); + } $this->lines[$i] = $line; @@ -1767,7 +1778,7 @@ class Facture extends CommonInvoice * * @return void */ - public function fetchPreviousNextSituationInvoice() + public function fetchPreviousNextSituationInvoice() { global $conf; @@ -1789,13 +1800,13 @@ class Facture extends CommonInvoice $invoice = new Facture($this->db); if ($invoice->fetch($objp->rowid) > 0) { - if ($objp->situation_counter < $this->situation_counter - || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes - ) + if ($objp->situation_counter < $this->situation_counter + || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes + ) { - $this->tab_previous_situation_invoice[] = $invoice; + $this->tab_previous_situation_invoice[] = $invoice; } else { - $this->tab_next_situation_invoice[] = $invoice; + $this->tab_next_situation_invoice[] = $invoice; } } } @@ -1809,7 +1820,7 @@ class Facture extends CommonInvoice * @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) + public function update(User $user, $notrigger = 0) { global $conf; @@ -1818,6 +1829,7 @@ class Facture extends CommonInvoice // Clean parameters if (empty($this->type)) $this->type = self::TYPE_STANDARD; if (isset($this->ref)) $this->ref = trim($this->ref); + if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext); if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client); if (isset($this->increment)) $this->increment = trim($this->increment); if (isset($this->close_code)) $this->close_code = trim($this->close_code); @@ -1825,7 +1837,7 @@ class Facture extends CommonInvoice if (isset($this->note) || isset($this->note_private)) $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated 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->modelpdf)) $this->modelpdf = trim($this->modelpdf); + 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->retained_warranty)) $this->retained_warranty = floatval($this->retained_warranty); @@ -1836,6 +1848,7 @@ class Facture extends CommonInvoice // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET"; $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; + $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").","; $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").","; $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").","; @@ -1917,16 +1930,16 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) * * @param int $idremise Id of absolute discount * @return int >0 if OK, <0 if KO */ - public function insert_discount($idremise) + public function insert_discount($idremise) { - // phpcs:enable + // phpcs:enable global $langs; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1962,12 +1975,12 @@ class Facture extends CommonInvoice // Get buy/cost price of invoice that is source of discount if ($remise->fk_facture_source > 0) { - $srcinvoice = new Facture($this->db); - $srcinvoice->fetch($remise->fk_facture_source); - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject - $formmargin = new FormMargin($this->db); - $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); - $facligne->pa_ht = $arraytmp['pa_total']; + $srcinvoice = new Facture($this->db); + $srcinvoice->fetch($remise->fk_facture_source); + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin = new FormMargin($this->db); + $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; } $facligne->total_ht = -$remise->amount_ht; @@ -2012,7 +2025,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set customer ref * @@ -2020,10 +2033,10 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_ref_client($ref_client, $notrigger = 0) + public function set_ref_client($ref_client, $notrigger = 0) { - // phpcs:enable - global $user; + // phpcs:enable + global $user; $error = 0; @@ -2081,7 +2094,7 @@ class Facture extends CommonInvoice * @param int $idwarehouse Id warehouse to use for stock change. * @return int <0 if KO, 0=Refused, >0 if OK */ - public function delete($user, $notrigger = 0, $idwarehouse = -1) + public function delete($user, $notrigger = 0, $idwarehouse = -1) { global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -2101,10 +2114,10 @@ class Facture extends CommonInvoice if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_DELETE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_DELETE', $user); + if ($result < 0) $error++; + // End call triggers } // Removed extrafields @@ -2176,7 +2189,7 @@ class Facture extends CommonInvoice } } - // Invoice line extrafileds + // Invoice line extrafileds $main = MAIN_DB_PREFIX.'facturedet'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture = $rowid)"; @@ -2194,6 +2207,9 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { + // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive + $this->deleteEcmFiles(); + // On efface le repertoire de pdf provisoire $ref = dol_sanitizeFileName($this->ref); if ($conf->facture->dir_output && !empty($this->ref)) @@ -2242,7 +2258,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0 @@ -2252,9 +2268,9 @@ class Facture extends CommonInvoice * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) * @return int <0 if KO, >0 if OK */ - public function set_paid($user, $close_code = '', $close_note = '') + public function set_paid($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable $error = 0; if ($this->paye != 1) @@ -2277,10 +2293,10 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_PAYED', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_PAYED', $user); + if ($result < 0) $error++; + // End call triggers } else { $error++; $this->error = $this->db->lasterror(); @@ -2300,7 +2316,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED * Fonction utilisee quand un paiement prelevement est refuse, @@ -2309,9 +2325,9 @@ class Facture extends CommonInvoice * @param User $user Object user that change status * @return int <0 if KO, >0 if OK */ - public function set_unpaid($user) + public function set_unpaid($user) { - // phpcs:enable + // phpcs:enable $error = 0; $this->db->begin(); @@ -2326,10 +2342,10 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_UNPAYED', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_UNPAYED', $user); + if ($result < 0) $error++; + // End call triggers } else { $error++; $this->error = $this->db->error(); @@ -2347,7 +2363,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because @@ -2358,9 +2374,9 @@ class Facture extends CommonInvoice * @param string $close_note Comment * @return int <0 if KO, >0 if OK */ - public function set_canceled($user, $close_code = '', $close_note = '') + public function set_canceled($user, $close_code = '', $close_note = '') { - // phpcs:enable + // phpcs:enable dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG); @@ -2384,14 +2400,14 @@ class Facture extends CommonInvoice $resql = $this->db->query($sql); if ($resql) { - // Call trigger - $result = $this->call_trigger('BILL_CANCEL', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('BILL_CANCEL', $user); + if ($result < 0) + { $this->db->rollback(); return -1; } - // End call triggers + // End call triggers $this->db->commit(); return 1; @@ -2417,9 +2433,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @param int $batch_rule 0=do not decrement batch, else batch rule to use * 1=take in batches ordered by sellby and eatby dates - * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK + * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ - public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) + public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -2450,12 +2466,12 @@ class Facture extends CommonInvoice } if (count($this->lines) <= 0) { - $langs->load("errors"); + $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; } if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR); @@ -2667,10 +2683,10 @@ class Facture extends CommonInvoice // Trigger calls if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('BILL_VALIDATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers } if (!$error) @@ -2698,16 +2714,16 @@ class Facture extends CommonInvoice if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -2731,20 +2747,20 @@ class Facture extends CommonInvoice $this->date_validation = $now; $i = 0; - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { - $final = true; - $nboflines = count($this->lines); - while (($i < $nboflines) && $final) { - $final = ($this->lines[$i]->situation_percent == 100); - $i++; - } + if (!empty($conf->global->INVOICE_USE_SITUATION)) + { + $final = true; + $nboflines = count($this->lines); + while (($i < $nboflines) && $final) { + $final = ($this->lines[$i]->situation_percent == 100); + $i++; + } - if (empty($final)) $this->situation_final = 0; - else $this->situation_final = 1; + if (empty($final)) $this->situation_final = 0; + else $this->situation_final = 1; - $this->setFinal($user); - } + $this->setFinal($user); + } } } else { $error++; @@ -2766,7 +2782,7 @@ class Facture extends CommonInvoice * @param Translate $langs Translate object * @return bool false if KO, true if OK */ - public function updatePriceNextInvoice(&$langs) + public function updatePriceNextInvoice(&$langs) { foreach ($this->tab_next_situation_invoice as $next_invoice) { @@ -2810,7 +2826,7 @@ class Facture extends CommonInvoice */ public function setDraft($user, $idwarehouse = -1) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $error = 0; @@ -2929,39 +2945,41 @@ class Facture extends CommonInvoice * @param int $fk_prev_id Previous situation line id reference * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency + * @param string $ref_ext External reference of the line * @return int <0 if KO, Id of line if OK */ - public function addline( - $desc, - $pu_ht, - $qty, - $txtva, - $txlocaltax1 = 0, - $txlocaltax2 = 0, - $fk_product = 0, - $remise_percent = 0, - $date_start = '', - $date_end = '', - $ventil = 0, - $info_bits = 0, - $fk_remise_except = '', - $price_base_type = 'HT', - $pu_ttc = 0, - $type = self::TYPE_STANDARD, - $rang = -1, - $special_code = 0, - $origin = '', - $origin_id = 0, - $fk_parent_line = 0, - $fk_fournprice = null, - $pa_ht = 0, - $label = '', - $array_options = 0, - $situation_percent = 100, - $fk_prev_id = 0, - $fk_unit = null, - $pu_ht_devise = 0 - ) { + public function addline( + $desc, + $pu_ht, + $qty, + $txtva, + $txlocaltax1 = 0, + $txlocaltax2 = 0, + $fk_product = 0, + $remise_percent = 0, + $date_start = '', + $date_end = '', + $ventil = 0, + $info_bits = 0, + $fk_remise_except = '', + $price_base_type = 'HT', + $pu_ttc = 0, + $type = self::TYPE_STANDARD, + $rang = -1, + $special_code = 0, + $origin = '', + $origin_id = 0, + $fk_parent_line = 0, + $fk_fournprice = null, + $pa_ht = 0, + $label = '', + $array_options = 0, + $situation_percent = 100, + $fk_prev_id = 0, + $fk_unit = null, + $pu_ht_devise = 0, + $ref_ext = '' + ) { // Deprecation warning if ($label) { dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING); @@ -2988,6 +3006,7 @@ class Facture extends CommonInvoice if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; if (empty($fk_prev_id)) $fk_prev_id = 'null'; if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; + if (empty($ref_ext)) $ref_ext = ''; $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -3027,8 +3046,8 @@ class Facture extends CommonInvoice $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3061,8 +3080,8 @@ class Facture extends CommonInvoice // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Rank to use @@ -3081,6 +3100,7 @@ class Facture extends CommonInvoice $this->line->fk_facture = $this->id; $this->line->label = $label; // deprecated $this->line->desc = $desc; + $this->line->ref_ext = $ref_ext; $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise @@ -3125,8 +3145,8 @@ class Facture extends CommonInvoice $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; if (is_array($array_options) && count($array_options) > 0) { $this->line->array_options = $array_options; @@ -3156,7 +3176,7 @@ class Facture extends CommonInvoice return -2; } } else { - dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); + dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR); return -3; } } @@ -3183,14 +3203,15 @@ class Facture extends CommonInvoice * @param int $pa_ht Price (without tax) of product when it was bought * @param string $label Label of the line (deprecated, do not use) * @param int $special_code Special code (also used by externals modules!) - * @param array $array_options extrafields array + * @param array $array_options extrafields array * @param int $situation_percent Situation advance percentage * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger + * @param string $ref_ext External reference of the line * @return int < 0 if KO, > 0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0) + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '') { global $conf, $user; // Deprecation warning @@ -3228,11 +3249,12 @@ class Facture extends CommonInvoice if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; if (empty($special_code) || $special_code == 3) $special_code = 0; if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; + if (empty($ref_ext)) $ref_ext = ''; $remise_percent = price2num($remise_percent); $qty = price2num($qty); $pu = price2num($pu); - $pu_ht_devise = price2num($pu_ht_devise); + $pu_ht_devise = price2num($pu_ht_devise); $pa_ht = price2num($pa_ht); $txtva = price2num($txtva); $txlocaltax1 = price2num($txlocaltax1); @@ -3248,12 +3270,12 @@ class Facture extends CommonInvoice $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise); @@ -3268,8 +3290,8 @@ class Facture extends CommonInvoice // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; // Old properties: $price, $remise (deprecated) @@ -3294,8 +3316,8 @@ class Facture extends CommonInvoice $product_type = $product->type; if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); + $langs->load("errors"); + $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref); $this->db->rollback(); return -3; } @@ -3305,7 +3327,7 @@ class Facture extends CommonInvoice $line->oldline = $staticline; $this->line = $line; - $this->line->context = $this->context; + $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) @@ -3318,6 +3340,7 @@ class Facture extends CommonInvoice $this->line->rowid = $rowid; $this->line->label = $label; $this->line->desc = $desc; + $this->line->ref_ext = $ref_ext; $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative $this->line->vat_src_code = $vat_src_code; @@ -3328,7 +3351,7 @@ class Facture extends CommonInvoice $this->line->localtax2_type = $localtaxes_type[2]; $this->line->remise_percent = $remise_percent; - $this->line->subprice = ($this->type == 2 ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise + $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise $this->line->date_start = $date_start; $this->line->date_end = $date_end; $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative @@ -3348,10 +3371,10 @@ class Facture extends CommonInvoice $this->line->pa_ht = $pa_ht; // Multicurrency - $this->line->multicurrency_subprice = $pu_ht_devise; - $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise + $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative + $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva); + $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc); if (is_array($array_options) && count($array_options) > 0) { // We replace values in this->line->array_options only for entries defined into $array_options @@ -3371,7 +3394,7 @@ class Facture extends CommonInvoice $this->db->commit(); return $result; } else { - $this->error = $this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -1; } @@ -3388,7 +3411,7 @@ class Facture extends CommonInvoice * @param float $situation_percent progress percentage need to be test * @return false if KO, true if OK */ - public function checkProgressLine($idline, $situation_percent) + public function checkProgressLine($idline, $situation_percent) { $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid) @@ -3408,7 +3431,7 @@ class Facture extends CommonInvoice else return $situation_percent < $obj->situation_percent; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update invoice line with percentage * @@ -3416,16 +3439,16 @@ class Facture extends CommonInvoice * @param int $percent Percentage * @return void */ - public function update_percent($line, $percent) + public function update_percent($line, $percent) { - // phpcs:enable - global $mysoc, $user; + // phpcs:enable + global $mysoc, $user; - // Progress should never be changed for discount lines - if (($line->info_bits & 2) == 2) - { - return; - } + // Progress should never be changed for discount lines + if (($line->info_bits & 2) == 2) + { + return; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -3451,9 +3474,9 @@ class Facture extends CommonInvoice * @param int $rowid Id of line to delete * @return int <0 if KO, >0 if OK */ - public function deleteline($rowid) + public function deleteline($rowid) { - global $user; + global $user; dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG); @@ -3481,7 +3504,7 @@ class Facture extends CommonInvoice $line = new FactureLigne($this->db); - $line->context = $this->context; + $line->context = $this->context; // For triggers $result = $line->fetch($rowid); @@ -3507,7 +3530,7 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set percent discount * @@ -3516,9 +3539,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ - public function set_remise($user, $remise, $notrigger = 0) + public function set_remise($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable // Clean parameters if (empty($remise)) $remise = 0; @@ -3571,7 +3594,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set absolute discount * @@ -3580,9 +3603,9 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function set_remise_absolue($user, $remise, $notrigger = 0) + public function set_remise_absolue($user, $remise, $notrigger = 0) { - // phpcs:enable + // phpcs:enable if (empty($remise)) $remise = 0; if ($user->rights->facture->creer) @@ -3645,7 +3668,7 @@ class Facture extends CommonInvoice * @param string $mode 'next' for next value or 'last' for last value * @return string free ref or last ref */ - public function getNextNumRef($soc, $mode = 'next') + public function getNextNumRef($soc, $mode = 'next') { global $conf, $langs; @@ -3743,7 +3766,7 @@ class Facture extends CommonInvoice * @param int $id Id of object to load * @return void */ - public function info($id) + public function info($id) { $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,'; $sql .= ' date_closing as dateclosing,'; @@ -3789,7 +3812,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices (eventually filtered on a user) into an array * @@ -3803,9 +3826,9 @@ class Facture extends CommonInvoice * @param string $sortorder Sort order * @return array|int -1 if KO, array with result if OK */ - public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') + public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') { - // phpcs:enable + // phpcs:enable global $conf, $user; $ga = array(); @@ -3860,7 +3883,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be replaced by another invoice. * Invoices matching the following rules are returned: @@ -3869,9 +3892,9 @@ class Facture extends CommonInvoice * @param int $socid Id thirdparty * @return array|int Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) */ - public function list_replacable_invoices($socid = 0) + public function list_replacable_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3908,7 +3931,7 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of invoices qualified to be corrected by a credit note. * Invoices matching the following rules are returned: @@ -3917,9 +3940,9 @@ class Facture extends CommonInvoice * @param int $socid Id thirdparty * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) */ - public function list_qualified_avoir_invoices($socid = 0) + public function list_qualified_avoir_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -3938,17 +3961,17 @@ class Facture extends CommonInvoice $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) { - // Select the last situation invoice - $sqlSit = 'SELECT MAX(fs.rowid)'; - $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; - $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; - $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; - $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; - $sqlSit .= " GROUP BY fs.situation_cycle_ref"; - $sqlSit .= " ORDER BY fs.situation_counter"; - $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir + // Select the last situation invoice + $sqlSit = 'SELECT MAX(fs.rowid)'; + $sqlSit .= " FROM ".MAIN_DB_PREFIX."facture as fs"; + $sqlSit .= " WHERE fs.entity IN (".getEntity('invoice').")"; + $sqlSit .= " AND fs.type = ".self::TYPE_SITUATION; + $sqlSit .= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; + $sqlSit .= " GROUP BY fs.situation_cycle_ref"; + $sqlSit .= " ORDER BY fs.situation_counter"; + $sql .= " AND ( f.type != ".self::TYPE_SITUATION." OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir } else { - $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir + $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir } if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; @@ -3979,16 +4002,16 @@ class Facture extends CommonInvoice } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Object user * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - public function load_board($user) + public function load_board($user) { - // phpcs:enable + // phpcs:enable global $conf, $langs; $clause = " WHERE"; @@ -4051,7 +4074,7 @@ class Facture extends CommonInvoice * * @return array Liste des id contacts facturation */ - public function getIdBillingContact() + public function getIdBillingContact() { return $this->getIdContact('external', 'BILLING'); } @@ -4061,7 +4084,7 @@ class Facture extends CommonInvoice * * @return array Liste des id contacts livraison */ - public function getIdShippingContact() + public function getIdShippingContact() { return $this->getIdContact('external', 'SHIPPING'); } @@ -4075,7 +4098,7 @@ class Facture extends CommonInvoice * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines * @return void */ - public function initAsSpecimen($option = '') + public function initAsSpecimen($option = '') { global $conf, $langs; @@ -4083,12 +4106,14 @@ class Facture extends CommonInvoice $arraynow = dol_getdate($now); $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); - // Load array of products prodids + // Load array of products prodids $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->plimit(100); + $resql = $this->db->query($sql); if ($resql) { @@ -4228,15 +4253,15 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @return int <0 if KO, >0 if OK */ - public function load_state_board() + public function load_state_board() { - // phpcs:enable + // phpcs:enable global $conf, $user; $this->nb = array(); @@ -4261,7 +4286,7 @@ class Facture extends CommonInvoice { $this->nb["invoices"] = $obj->nb; } - $this->db->free($resql); + $this->db->free($resql); return 1; } else { dol_print_error($this->db); @@ -4275,9 +4300,9 @@ class Facture extends CommonInvoice * * @return int >0 if OK, <0 if KO */ - public function getLinesArray() + public function getLinesArray() { - return $this->fetch_lines(); + return $this->fetch_lines(); } /** @@ -4322,7 +4347,7 @@ class Facture extends CommonInvoice * * @return int >= 1 if OK, -1 if error */ - public function newCycle() + public function newCycle() { $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")"; @@ -4345,27 +4370,27 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the first of a cycle * * @return boolean */ - public function is_first() + public function is_first() { - // phpcs:enable + // phpcs:enable return ($this->situation_counter == 1); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns an array containing the previous situations as Facture objects * * @return mixed -1 if error, array of previous situations */ - public function get_prev_sits() + public function get_prev_sits() { - // phpcs:enable + // phpcs:enable global $conf; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture'; @@ -4397,7 +4422,7 @@ class Facture extends CommonInvoice * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - public function setFinal(User $user, $notrigger = 0) + public function setFinal(User $user, $notrigger = 0) { $error = 0; @@ -4436,15 +4461,15 @@ class Facture extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Checks if the invoice is the last in its cycle * * @return bool Last of the cycle status */ - public function is_last_in_cycle() + public function is_last_in_cycle() { - // phpcs:enable + // phpcs:enable global $conf; if (!empty($this->situation_cycle_ref)) { @@ -4502,21 +4527,21 @@ class Facture extends CommonInvoice $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) { - $totalpaye = $this->getSommePaiement(); - $totalpaye = floatval($totalpaye); - $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); - if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) - { - if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) - { - $hasDelay = 1; - } else { - $hasDelay = 0; - } - } + $totalpaye = $this->getSommePaiement(); + $totalpaye = floatval($totalpaye); + $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); + if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) + { + if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } else { + $hasDelay = 0; + } + } } return $hasDelay; @@ -4567,45 +4592,45 @@ class Facture extends CommonInvoice public function getRetainedWarrantyAmount($rounding = -1) { global $conf; - if (empty($this->retained_warranty)) { - return -1; - } + if (empty($this->retained_warranty)) { + return -1; + } - $retainedWarrantyAmount = 0; + $retainedWarrantyAmount = 0; - // Billed - retained warranty - if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) - { - $displayWarranty = true; - // Check if this situation invoice is 100% for real - if (!empty($this->lines)) { - foreach ($this->lines as $i => $line) { - if ($line->product_type < 2 && $line->situation_percent < 100) { - $displayWarranty = false; - break; - } - } - } + // Billed - retained warranty + if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) + { + $displayWarranty = true; + // Check if this situation invoice is 100% for real + if (!empty($this->lines)) { + foreach ($this->lines as $i => $line) { + if ($line->product_type < 2 && $line->situation_percent < 100) { + $displayWarranty = false; + break; + } + } + } - if ($displayWarranty && !empty($this->situation_final)) - { - $this->fetchPreviousNextSituationInvoice(); - $TPreviousIncoice = $this->tab_previous_situation_invoice; + if ($displayWarranty && !empty($this->situation_final)) + { + $this->fetchPreviousNextSituationInvoice(); + $TPreviousIncoice = $this->tab_previous_situation_invoice; - $total2BillWT = 0; - foreach ($TPreviousIncoice as &$fac) { - $total2BillWT += $fac->total_ttc; - } - $total2BillWT += $this->total_ttc; + $total2BillWT = 0; + foreach ($TPreviousIncoice as &$fac) { + $total2BillWT += $fac->total_ttc; + } + $total2BillWT += $this->total_ttc; - $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; - } else { - return -1; - } - } else { - // Because one day retained warranty could be used on standard invoices - $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; - } + $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100; + } else { + return -1; + } + } else { + // Because one day retained warranty could be used on standard invoices + $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; + } if ($rounding < 0) { $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); @@ -4615,7 +4640,7 @@ class Facture extends CommonInvoice return round($retainedWarrantyAmount, $rounding); } - return $retainedWarrantyAmount; + return $retainedWarrantyAmount; } /** @@ -4626,28 +4651,28 @@ class Facture extends CommonInvoice */ public function setRetainedWarranty($value) { - dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.floatval($value); - $sql .= ' WHERE rowid='.$this->id; + dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.floatval($value); + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->retained_warranty = floatval($value); - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if ($this->db->query($sql)) + { + $this->retained_warranty = floatval($value); + return 1; + } else { + dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } @@ -4660,33 +4685,33 @@ class Facture extends CommonInvoice */ public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false) { - if (!$timestamp && $dateYmd) { - $timestamp = $this->db->jdate($dateYmd); - } + if (!$timestamp && $dateYmd) { + $timestamp = $this->db->jdate($dateYmd); + } - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); - if ($this->statut >= 0) - { - $fieldname = 'retained_warranty_date_limit'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); - $sql .= ' WHERE rowid='.$this->id; + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); + if ($this->statut >= 0) + { + $fieldname = 'retained_warranty_date_limit'; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->retained_warranty_date_limit = $timestamp; - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if ($this->db->query($sql)) + { + $this->retained_warranty_date_limit = $timestamp; + return 1; + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } } @@ -4696,12 +4721,12 @@ class Facture extends CommonInvoice */ class FactureLigne extends CommonInvoiceLine { - /** + /** * @var string ID to identify managed object */ public $element = 'facturedet'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'facturedet'; @@ -4719,6 +4744,7 @@ class FactureLigne extends CommonInvoiceLine public $label; //! Description ligne public $desc; + public $ref_ext; // External reference of the line public $localtax1_type; // Local tax 1 type public $localtax2_type; // Local tax 2 type @@ -4786,10 +4812,10 @@ class FactureLigne extends CommonInvoiceLine * @param int $rowid id of invoice line to get * @return int <0 if KO, >0 if OK */ - public function fetch($rowid) + public function fetch($rowid) { $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,'; - $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,'; + $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,'; $sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,'; $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,'; $sql .= ' fd.fk_code_ventilation,'; @@ -4817,6 +4843,7 @@ class FactureLigne extends CommonInvoiceLine $this->desc = $objp->description; $this->qty = $objp->qty; $this->subprice = $objp->subprice; + $this->ref_ext = $objp->ref_ext; $this->vat_src_code = $objp->vat_src_code; $this->tva_tx = $objp->tva_tx; $this->localtax1_tx = $objp->localtax1_tx; @@ -4864,7 +4891,7 @@ class FactureLigne extends CommonInvoiceLine return 1; } else { - $this->error = $this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -4876,15 +4903,15 @@ class FactureLigne extends CommonInvoiceLine * @param int $noerrorifdiscountalreadylinked 1=Do not make error if lines is linked to a discount and discount already linked to another * @return int <0 if KO, >0 if OK */ - public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) + public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0) { global $langs, $user, $conf; $error = 0; - $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'. + $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'. - dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); + dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); // Clean parameters $this->desc = trim($this->desc); @@ -4899,6 +4926,7 @@ class FactureLigne extends CommonInvoiceLine 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->ref_ext)) $this->ref_ext = ''; if (empty($this->special_code)) $this->special_code = 0; if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; @@ -4945,7 +4973,7 @@ class FactureLigne extends CommonInvoiceLine $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet'; $sql .= ' (fk_facture, fk_parent_line, label, description, qty,'; $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql .= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,'; + $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,'; $sql .= ' date_start, date_end, fk_code_ventilation, '; $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,'; $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,'; @@ -4958,7 +4986,7 @@ class FactureLigne extends CommonInvoiceLine $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " '".$this->db->escape($this->desc)."',"; $sql .= " ".price2num($this->qty).","; - $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; $sql .= " ".price2num($this->tva_tx).","; $sql .= " ".price2num($this->localtax1_tx).","; $sql .= " ".price2num($this->localtax2_tx).","; @@ -4968,6 +4996,7 @@ class FactureLigne extends CommonInvoiceLine $sql .= " ".((int) $this->product_type).","; $sql .= " ".price2num($this->remise_percent).","; $sql .= " ".price2num($this->subprice).","; + $sql .= " '".$this->db->escape($this->ref_ext)."',"; $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").','; $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").","; $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").","; @@ -5002,14 +5031,14 @@ class FactureLigne extends CommonInvoiceLine $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); $this->rowid = $this->id; // For backward compatibility - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } // Si fk_remise_except defini, on lie la remise a la facture // ce qui la flague comme "consommee". @@ -5022,16 +5051,16 @@ class FactureLigne extends CommonInvoiceLine // Check if discount was found if ($result > 0) { - // Check if discount not already affected to another invoice + // Check if discount not already affected to another invoice if ($discount->fk_facture_line > 0) { - if (empty($noerrorifdiscountalreadylinked)) - { - $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); - dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -3; - } + if (empty($noerrorifdiscountalreadylinked)) + { + $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); + dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -3; + } } else { $result = $discount->link_to_invoice($this->rowid, 0); if ($result < 0) @@ -5058,14 +5087,14 @@ class FactureLigne extends CommonInvoiceLine if (!$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_INSERT', $user); - if ($result < 0) - { + // Call trigger + $result = $this->call_trigger('LINEBILL_INSERT', $user); + if ($result < 0) + { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); @@ -5084,7 +5113,7 @@ class FactureLigne extends CommonInvoiceLine * @param int $notrigger Disable triggers * @return int <0 if KO, >0 if OK */ - public function update($user = '', $notrigger = 0) + public function update($user = '', $notrigger = 0) { global $user, $conf; @@ -5094,6 +5123,7 @@ class FactureLigne extends CommonInvoiceLine // Clean parameters $this->desc = trim($this->desc); + 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; @@ -5130,34 +5160,35 @@ class FactureLigne extends CommonInvoiceLine $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; - $sql .= " description='".$this->db->escape($this->desc)."'"; - $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); - $sql .= ", subprice=".price2num($this->subprice).""; - $sql .= ", remise_percent=".price2num($this->remise_percent).""; - if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; - else $sql .= ", fk_remise_except=null"; + // Update line in database + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'"; + $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= ", subprice=".price2num($this->subprice).""; + $sql .= ", remise_percent=".price2num($this->remise_percent).""; + if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; + else $sql .= ", fk_remise_except=null"; $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'"; - $sql .= ", tva_tx=".price2num($this->tva_tx).""; - $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; - $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; + $sql .= ", tva_tx=".price2num($this->tva_tx).""; + $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; + $sql .= ", localtax2_tx=".price2num($this->localtax2_tx).""; $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", qty=".price2num($this->qty); - $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 .= ", product_type=".$this->product_type; - $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; - $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; - 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); - $sql .= ", total_localtax1=".price2num($this->total_localtax1); - $sql .= ", total_localtax2=".price2num($this->total_localtax2); - } + $sql .= ", qty=".price2num($this->qty); + $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 .= ", product_type=".$this->product_type; + $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; + 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); + $sql .= ", total_localtax1=".price2num($this->total_localtax1); + $sql .= ", total_localtax2=".price2num($this->total_localtax2); + } $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= ", buy_price_ht='".price2num($this->pa_ht)."'"; $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); @@ -5168,9 +5199,9 @@ class FactureLigne extends CommonInvoiceLine // Multicurrency $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql .= " WHERE rowid = ".$this->rowid; @@ -5178,26 +5209,26 @@ class FactureLigne extends CommonInvoiceLine $resql = $this->db->query($sql); if ($resql) { - if (!$error) - { - $this->id = $this->rowid; - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $this->id = $this->rowid; + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('LINEBILL_UPDATE', $user); - if ($result < 0) + // Call trigger + $result = $this->call_trigger('LINEBILL_UPDATE', $user); + if ($result < 0) { $this->db->rollback(); return -2; } - // End call triggers + // End call triggers } $this->db->commit(); return 1; @@ -5211,10 +5242,10 @@ class FactureLigne extends CommonInvoiceLine /** * Delete line in database * TODO Add param User $user and notrigger (see skeleton) - * + * * @return int <0 if KO, >0 if OK */ - public function delete() + public function delete() { global $user; @@ -5229,13 +5260,13 @@ class FactureLigne extends CommonInvoiceLine } // End call triggers - // extrafields - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + // extrafields + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); @@ -5250,16 +5281,16 @@ class FactureLigne extends CommonInvoiceLine } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Update DB line fields total_xxx + * Update DB line fields total_xxx * Used by migration * * @return int <0 if KO, >0 if OK */ - public function update_total() + public function update_total() { - // phpcs:enable + // phpcs:enable $this->db->begin(); dol_syslog(get_class($this)."::update_total", LOG_DEBUG); @@ -5290,7 +5321,7 @@ class FactureLigne extends CommonInvoiceLine } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Returns situation_percent of the previous line. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line. @@ -5299,14 +5330,14 @@ class FactureLigne extends CommonInvoiceLine * @param bool $include_credit_note Include credit note or not * @return int >= 0 */ - public function get_prev_progress($invoiceid, $include_credit_note = true) + public function get_prev_progress($invoiceid, $include_credit_note = true) { - // phpcs:enable + // phpcs:enable global $invoicecache; if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") { return 0; } else { - // If invoice is not a situation invoice, this->fk_prev_id is used for something else + // If invoice is not a situation invoice, this->fk_prev_id is used for something else if (!isset($invoicecache[$invoiceid])) { $invoicecache[$invoiceid] = new Facture($this->db); $invoicecache[$invoiceid]->fetch($invoiceid); @@ -5321,20 +5352,20 @@ class FactureLigne extends CommonInvoiceLine $returnPercent = floatval($res['situation_percent']); if ($include_credit_note) { - $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; - $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; - $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; - $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed - $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; + $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; + $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) '; + $sql .= ' WHERE fd.fk_prev_id ='.$this->fk_prev_id; + $sql .= ' AND f.situation_cycle_ref = '.$invoicecache[$invoiceid]->situation_cycle_ref; // Prevent cycle outed + $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE; - $res = $this->db->query($sql); - if ($res) { - while ($obj = $this->db->fetch_object($res)) { - $returnPercent = $returnPercent + floatval($obj->situation_percent); - } - } else { - dol_print_error($this->db); - } + $res = $this->db->query($sql); + if ($res) { + while ($obj = $this->db->fetch_object($res)) { + $returnPercent = $returnPercent + floatval($obj->situation_percent); + } + } else { + dol_print_error($this->db); + } } return $returnPercent; diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index c88fef5015c..459543dfc74 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -42,7 +42,7 @@ $id = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // Fo $ref = GETPOST('ref', 'alpha'); $lineid = GETPOST('lineid', 'int'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index ed9b032ae90..722286044cc 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -45,7 +45,7 @@ $langs->loadLangs(array('propal', 'compta', 'other', 'bills', 'companies')); $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check diff --git a/htdocs/compta/facture/index.php b/htdocs/compta/facture/index.php index 5c0aacfdb35..fb044280a21 100644 --- a/htdocs/compta/facture/index.php +++ b/htdocs/compta/facture/index.php @@ -51,7 +51,7 @@ $maxOpenCount = empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->glob llxHeader("", $langs->trans("CustomersInvoicesArea"), "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes"); -print load_fiche_titre($langs->trans("CustomersInvoicesArea"), '', 'invoicing'); +print load_fiche_titre($langs->trans("CustomersInvoicesArea"), '', 'bill'); print '
'; diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index 400fb3be7ed..16d163c4fe6 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -357,7 +357,7 @@ if ($resql) if (!empty($arrayfields['f.titre']['checked'])) { print ''; - print ''; + print ''; print ''; } // Thirpdarty @@ -478,7 +478,7 @@ if ($resql) } // Action column print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0, 'checkforselect', 1); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print ''; print "\n"; @@ -502,7 +502,7 @@ if ($resql) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER['PHP_SELF'], "f.suspended,f.frequency", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'nomaxwidthsearch '); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; if ($num > 0) @@ -529,7 +529,7 @@ if ($resql) if (!empty($arrayfields['f.titre']['checked'])) { - print ''; + print ''; print $invoicerectmp->getNomUrl(1); print ""; print "\n"; diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 0e4270e04f7..e12e21e70b4 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -61,7 +61,7 @@ $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -100,7 +100,7 @@ $search_module_source = GETPOST('search_module_source', 'alpha'); $search_pos_source = GETPOST('search_pos_source', 'alpha'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); -$search_state = trim(GETPOST("search_state")); +$search_state = GETPOST("search_state"); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_user = GETPOST('search_user', 'int'); @@ -111,7 +111,7 @@ $search_date_valid_start = dol_mktime(0, 0, 0, GETPOST('search_date_valid_startm $search_date_valid_end = dol_mktime(23, 59, 59, GETPOST('search_date_valid_endmonth', 'int'), GETPOST('search_date_valid_endday', 'int'), GETPOST('search_date_valid_endyear', 'int')); $search_datelimit_start = dol_mktime(0, 0, 0, GETPOST('search_datelimit_startmonth', 'int'), GETPOST('search_datelimit_startday', 'int'), GETPOST('search_datelimit_startyear', 'int')); $search_datelimit_end = dol_mktime(23, 59, 59, GETPOST('search_datelimit_endmonth', 'int'), GETPOST('search_datelimit_endday', 'int'), GETPOST('search_datelimit_endyear', 'int')); -$search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); +$search_categ_cus = GETPOST("search_categ_cus", 'int'); $search_btn = GETPOST('button_search', 'alpha'); $search_remove_btn = GETPOST('button_removefilter', 'alpha'); @@ -205,6 +205,8 @@ $arrayfields = array( 'multicurrency_rtp'=>array('label'=>'MulticurrencyRemainderToPay', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>220), // Not enabled by default because slow 'f.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), 'f.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 'f.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'position'=>510, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PUBLIC_NOTES))), + 'f.note_private'=>array('label'=>'NotePrivate', 'checked'=>0, 'position'=>511, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PRIVATE_NOTES))), 'f.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), ); @@ -478,15 +480,15 @@ if ($filtre) } if ($search_ref) $sql .= natural_search('f.ref', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); -if ($search_type != '' && $search_type != '-1') $sql .= " AND f.type IN (".$db->escape($search_type).")"; +if ($search_type != '' && $search_type != '-1') $sql .= " AND f.type IN (".$db->sanitize($db->escape($search_type)).")"; if ($search_project_ref) $sql .= natural_search('p.ref', $search_project_ref); if ($search_project) $sql .= natural_search('p.title', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); 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->escape($search_country).')'; -if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$db->escape($search_type_thirdparty).')'; +if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +if ($search_type_thirdparty) $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_montant_ht != '') $sql .= natural_search('f.total', $search_montant_ht, 1); if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_vat, 1); @@ -510,7 +512,7 @@ if ($search_status != '-1' && $search_status != '') if ($search_status == '2') $sql .= " AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) if ($search_status == '3') $sql .= " AND f.fk_statut = 3"; // abandonned } else { - $sql .= " AND f.fk_statut IN (".$db->escape($search_status).")"; // When search_status is '1,2' for example + $sql .= " AND f.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; // When search_status is '1,2' for example } } @@ -674,10 +676,12 @@ if ($resql) if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton = ''; - if ($user->rights->facture->creer && $contextpage != 'poslist') + // Show the new button only when this page is not opend from the Extended POS + if ($contextpage != 'poslist') { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/facture/card.php?action=create'); + $url = DOL_URL_ROOT.'/compta/facture/card.php?action=create'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->rights->facture->creer); } $i = 0; @@ -725,7 +729,7 @@ if ($resql) $moreforfilter .= '
'; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($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 .= '
'; @@ -734,7 +738,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)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
'; @@ -756,6 +760,7 @@ if ($resql) $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); print '
'; @@ -804,12 +809,10 @@ if ($resql) { print ''; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1); + print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1); + print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '
'; print ''; } @@ -818,12 +821,10 @@ if ($resql) { print ''; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_valid_start ? $search_date_valid_start : -1, 'search_date_valid_start', 0, 0, 1); + print $form->selectDate($search_date_valid_start ? $search_date_valid_start : -1, 'search_date_valid_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_valid_end ? $search_date_valid_end : -1, 'search_date_valid_end', 0, 0, 1); + print $form->selectDate($search_date_valid_end ? $search_date_valid_end : -1, 'search_date_valid_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '
'; print ''; } @@ -838,8 +839,7 @@ if ($resql) print '
'; print '
'; print $langs->trans('to').' ';*/ - print $langs->trans("Before").' '; - print $form->selectDate($search_datelimit_end ? $search_datelimit_end : -1, 'search_datelimit_end', 0, 0, 1); + print $form->selectDate($search_datelimit_end ? $search_datelimit_end : -1, 'search_datelimit_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("Before")); print '
'.$langs->trans("Alert"); print '
'; print ''; @@ -1039,6 +1039,18 @@ if ($resql) print ''; print ''; } + if (!empty($arrayfields['f.note_public']['checked'])) + { + // Note public + print ''; + print ''; + } + if (!empty($arrayfields['f.note_private']['checked'])) + { + // Note private + print ''; + print ''; + } // Status if (!empty($arrayfields['f.fk_statut']['checked'])) { @@ -1099,6 +1111,8 @@ if ($resql) if (!empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); if (!empty($arrayfields['f.date_closing']['checked'])) print_liste_field_titre($arrayfields['f.date_closing']['label'], $_SERVER["PHP_SELF"], "f.date_closing", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + 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,f.paye,f.type,dynamount_payed", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -1206,7 +1220,7 @@ if ($resql) // Ref if (!empty($arrayfields['f.ref']['checked'])) { - print ''; + print ''; print ''; @@ -1242,7 +1256,7 @@ if ($resql) // Type if (!empty($arrayfields['f.type']['checked'])) { - print '"; if (!$i) $totalarray['nbfield']++; @@ -1251,7 +1265,7 @@ if ($resql) // Date if (!empty($arrayfields['f.date']['checked'])) { - print ''; if (!$i) $totalarray['nbfield']++; @@ -1260,7 +1274,7 @@ if ($resql) // Date if (!empty($arrayfields['f.date_valid']['checked'])) { - print ''; if (!$i) $totalarray['nbfield']++; @@ -1269,7 +1283,7 @@ if ($resql) // Date limit if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { - print ''; if (!$i) $totalarray['nbfield']++; @@ -1368,7 +1382,7 @@ if ($resql) // Payment mode if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print ''; if (!$i) $totalarray['nbfield']++; @@ -1404,7 +1418,7 @@ if ($resql) // Amount HT if (!empty($arrayfields['f.total_ht']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; $totalarray['val']['f.total_ht'] += $obj->total_ht; @@ -1412,7 +1426,7 @@ if ($resql) // Amount VAT if (!empty($arrayfields['f.total_vat']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; $totalarray['val']['f.total_vat'] += $obj->total_vat; @@ -1420,7 +1434,7 @@ if ($resql) // Amount LocalTax1 if (!empty($arrayfields['f.total_localtax1']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; $totalarray['val']['f.total_localtax1'] += $obj->total_localtax1; @@ -1428,7 +1442,7 @@ if ($resql) // Amount LocalTax2 if (!empty($arrayfields['f.total_localtax2']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; $totalarray['val']['f.total_localtax2'] += $obj->total_localtax2; @@ -1436,7 +1450,7 @@ if ($resql) // Amount TTC if (!empty($arrayfields['f.total_ttc']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; $totalarray['val']['f.total_ttc'] += $obj->total_ttc; @@ -1461,7 +1475,7 @@ if ($resql) if (!empty($arrayfields['dynamount_payed']['checked'])) { - print ''; // TODO Use a denormalized field + print ''; // TODO Use a denormalized field if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; $totalarray['val']['totalam'] += $totalpay; @@ -1470,7 +1484,7 @@ if ($resql) // Pending amount if (!empty($arrayfields['rtp']['checked'])) { - print ''; // TODO Use a denormalized field if (!$i) $totalarray['nbfield']++; @@ -1482,14 +1496,14 @@ if ($resql) // Currency if (!empty($arrayfields['f.multicurrency_code']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; } // Currency rate if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { - print '\n"; if (!$i) $totalarray['nbfield']++; @@ -1497,31 +1511,31 @@ if ($resql) // Amount HT if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; } // Amount VAT if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; } // Amount TTC if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { - print '\n"; + print '\n"; if (!$i) $totalarray['nbfield']++; } if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { - print ''; // TODO Use a denormalized field + print ''; // TODO Use a denormalized field if (!$i) $totalarray['nbfield']++; } // Pending amount if (!empty($arrayfields['multicurrency_rtp']['checked'])) { - print ''; // TODO Use a denormalized field if (!$i) $totalarray['nbfield']++; @@ -1557,6 +1571,22 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Note public + if (!empty($arrayfields['f.note_public']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Note private + if (!empty($arrayfields['f.note_private']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Status if (!empty($arrayfields['f.fk_statut']['checked'])) { @@ -1566,7 +1596,7 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } - // Action column + // Action column (Show the massaction button only when this page is not opend from the Extended POS) print ''; print ''; diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 82ba8a33467..81466651856 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -94,7 +94,7 @@ dol_mkdir($dir); $stats = new FactureStats($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 >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; if (is_array($custcats) && !empty($custcats)) { $stats->from .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cat ON (f.fk_soc = cat.fk_soc)'; $stats->where .= ' AND cat.fk_categorie IN ('.implode(',', $custcats).')'; @@ -102,7 +102,7 @@ if ($mode == 'customer') } if ($mode == 'supplier') { - if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; } // Build graphic number of object diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 3121aeffb17..0591d75d5a3 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -7,6 +7,7 @@ * Copyright (C) 2015 Raphaël Doursenaud * Copyright (C) 2016 Marcos García * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2020 Tobias Sekan * * 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,12 +33,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -if (!empty($conf->commande->enabled)) - require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (!empty($conf->commande->enabled)) - require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -if (!empty($conf->tax->enabled)) - require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; // L'espace compta/treso doit toujours etre actif car c'est un espace partage // par de nombreux modules (banque, facture, commande a facturer, etc...) independamment @@ -51,7 +49,7 @@ $langs->loadLangs(array('compta', 'bills')); if (!empty($conf->commande->enabled)) $langs->load("orders"); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $bid = GETPOST('bid', 'int'); // Security check @@ -62,7 +60,7 @@ if ($user->socid > 0) $socid = $user->socid; } -$max = 3; +$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array $hookmanager->initHooks(array('invoiceindex')); @@ -148,7 +146,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = 0"; + $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = ".Facture::STATUS_DRAFT; $sql .= " AND f.entity IN (".getEntity('invoice').")"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; @@ -161,8 +159,8 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $reshook = $hookmanager->executeHooks('printFieldListWhereCustomerDraft', $parameters); $sql .= $hookmanager->resPrint; - $sql.= " GROUP BY f.rowid, f.ref, f.datef, f.total, f.tva, f.total_ttc, f.ref_client, f.type, "; - $sql.= "s.email, s.nom, s.rowid, s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur"; + $sql .= " GROUP BY f.rowid, f.ref, f.datef, f.total, f.tva, f.total_ttc, f.ref_client, f.type, "; + $sql .= "s.email, s.nom, s.rowid, s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur"; // Add Group from hooks $parameters = array(); @@ -175,10 +173,18 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $num = $db->num_rows($resql); - print '
'; + print '
'; print '
'; + print ''; print $facturestatic->getLibType(); print "'; + print ''; print dol_print_date($db->jdate($obj->df), 'day'); print ''; + print ''; print dol_print_date($db->jdate($obj->date_valid), 'day'); print ''.dol_print_date($datelimit, 'day'); + print ''.dol_print_date($datelimit, 'day'); if ($facturestatic->hasDelay()) { print img_warning($langs->trans('Alert').' - '.$langs->trans('Late')); @@ -1281,7 +1295,7 @@ if ($resql) // Project ref if (!empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; if ($obj->project_id > 0) { print $projectstatic->getNomUrl(1); @@ -1293,7 +1307,7 @@ if ($resql) // Project title if (!empty($arrayfields['p.title']['checked'])) { - print ''; + print ''; if ($obj->project_id > 0) { print $projectstatic->title; @@ -1326,7 +1340,7 @@ if ($resql) // Zip if (!empty($arrayfields['s.zip']['checked'])) { - print ''; + print ''; print $obj->zip; print ''; + print ''; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print ''.price($obj->total_ht)."'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_vat)."'.price($obj->total_localtax1)."'.price($obj->total_localtax1)."'.price($obj->total_localtax2)."'.price($obj->total_localtax2)."'.price($obj->total_ttc)."'.price($obj->total_ttc)."'.(!empty($totalpay) ?price($totalpay, 0, $langs) : ' ').''.(!empty($totalpay) ?price($totalpay, 0, $langs) : ' ').''; + print ''; print (!empty($remaintopay) ? price($remaintopay, 0, $langs) : ' '); print ''.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; + print ''; $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_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."'.price($obj->multicurrency_total_ttc)."'.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : ' ').''.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : ' ').''; + print ''; print (!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : ' '); print ''; + print dol_escape_htmltag($obj->note_public); + print ''; + print dol_escape_htmltag($obj->note_private); + print ''; 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 { @@ -1597,19 +1627,22 @@ if ($resql) print "\n"; - $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + // Show the file area only when this page is not opend from the Extended POS + if ($contextpage != 'poslist') { + $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); + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); - $filedir = $diroutputmassaction; - $genallowed = $user->rights->facture->lire; - $delallowed = $user->rights->facture->creer; - $title = ''; + $filedir = $diroutputmassaction; + $genallowed = $user->rights->facture->lire; + $delallowed = $user->rights->facture->creer; + $title = ''; - print $formfile->showdocuments('massfilesarea_invoices', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); + print $formfile->showdocuments('massfilesarea_invoices', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); + } } else { dol_print_error($db); } diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 954c48ec0c9..249d2dd9b8c 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -39,7 +39,7 @@ $langs->loadLangs(array('companies', 'bills')); $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check $socid = 0; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 88a0b922e55..f69517c1037 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -44,7 +44,7 @@ $langs->loadLangs(array('bills', 'banks', 'withdrawals', 'companies')); $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $type = GETPOST('type', 'aZ09'); $fieldid = (!empty($ref) ? 'ref' : 'rowid'); @@ -752,7 +752,7 @@ if ($object->id > 0) print ''.$langs->trans("OrderWaiting").''; - print ''; + print ''; print img_delete(); print '
'; + print ''; - print ''; + print ''; + print ''; + if ($num) { $companystatic = new Societe($db); @@ -207,11 +213,11 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $companystatic->code_compta = $obj->code_compta; $companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; - print ''; - print ''; print ''; print ''; @@ -244,7 +250,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= ", cc.rowid as country_id, cc.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = 0"; + $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = ".FactureFournisseur::STATUS_DRAFT; $sql .= " AND f.entity IN (".getEntity('invoice').')'; 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; @@ -258,10 +264,18 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU { $num = $db->num_rows($resql); - print '
'; + print '
'; print '
'.$langs->trans("CustomersDraftInvoices").($num ? ''.$num.'' : '').'
'; + print $langs->trans("CustomersDraftInvoices").' '; + print ''; + print ''.$num.''; + print ''; + print '
'; + print '
'; print $facturestatic->getNomUrl(1, ''); print ''; - print $companystatic->getNomUrl(1, 'customer', 16); + print ''; + print $companystatic->getNomUrl(1, 'customer'); print ''.price($obj->total_ttc).'
'; + print ''; - print ''; + print ''; + print ''; + if ($num) { $companystatic = new Societe($db); @@ -291,11 +305,11 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $companystatic->code_compta = $obj->code_compta; $companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; - print ''; - print ''; print ''; print ''; @@ -356,6 +370,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $num = $db->num_rows($resql); $i = 0; + $othernb = 0; print '
'; print '
'.$langs->trans("SuppliersDraftInvoices").($num ? ''.$num.'' : '').'
'; + print $langs->trans("SuppliersDraftInvoices").' '; + print ''; + print ''.$num.''; + print ''; + print '
'; - print $facturesupplierstatic->getNomUrl(1, '', 16); + print '
'; + print $facturesupplierstatic->getNomUrl(1, ''); print ''; - print $companystatic->getNomUrl(1, 'supplier', 16); + print ''; + print $companystatic->getNomUrl(1, 'supplier'); print ''.price($obj->total_ttc).'
'; @@ -372,6 +387,14 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $facturestatic->ref = $obj->ref; $facturestatic->id = $obj->rowid; $facturestatic->total_ht = $obj->total_ht; @@ -428,6 +451,14 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $i++; } + + if ($othernb) { + print ''; + print ''; + print "\n"; + } } else { $colspan = 5; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; @@ -487,10 +518,20 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU { $i = 0; $total = $total_ttc = $totalam = 0; + $othernb = 0; + while ($i < $num) { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $facstatic->ref = $obj->ref; $facstatic->id = $obj->rowid; $facstatic->total_ht = $obj->total_ht; @@ -509,11 +550,11 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $thirdpartystatic->code_compta = ''; $thirdpartystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; - print ''; - print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; @@ -525,6 +566,14 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $totalam += $obj->am; $i++; } + + if ($othernb) { + print ''; + print ''; + print "\n"; + } } else { $colspan = 5; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; @@ -560,10 +609,10 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $result = $db->query($sql); if ($result) { - $var = false; $num = $db->num_rows($result); $i = 0; + $othernb = 0; print '
'; print '
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'; + print '
'; print $facstatic->getNomUrl(1, ''); print ''; - print $thirdpartystatic->getNomUrl(1, 'supplier', 44); + print ''; + print $thirdpartystatic->getNomUrl(1, 'supplier'); print ''.price($obj->total_ht).''.price($obj->total_ttc).'
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'; @@ -582,6 +631,14 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) { $objp = $db->fetch_object($result); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $donationstatic->id = $objp->rowid; $donationstatic->ref = $objp->rowid; $donationstatic->lastname = $objp->lastname; @@ -590,7 +647,7 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $label = $donationstatic->getFullName($langs); if ($objp->societe) $label .= ($label ? ' - ' : '').$objp->societe; - print ''; + print ''; print ''; print ''; print ''; @@ -600,6 +657,14 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $i++; } + + if ($othernb) { + print ''; + print ''; + print "\n"; + } } else { print ''; } @@ -649,17 +714,27 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { $i = 0; $tot_ttc = 0; + $othernb = 0; + while ($i < $num) { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $chargestatic->id = $obj->rowid; $chargestatic->ref = $obj->rowid; $chargestatic->label = $obj->label; $chargestatic->paye = $obj->paye; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -670,6 +745,14 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $i++; } + if ($othernb) { + print ''; + print ''; + print "\n"; + } + print ''; print ''; print ''; @@ -709,7 +792,7 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $sql .= " AND c.entity = ".$conf->entity; 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 .= " AND c.fk_statut = 3"; + $sql .= " AND c.fk_statut = ".Commande::STATUS_CLOSED; $sql .= " AND c.facture = 0"; // Add where from hooks $parameters = array(); @@ -726,11 +809,19 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user if ($num) { $i = 0; + $othernb = 0; print '
'; print '
'.$donationstatic->getNomUrl(1).''.$label.''.price($objp->amount).'
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'.$langs->trans("None").'
'.$chargestatic->getNomUrl(1).''.$chargestatic->getNomUrl(1).''.dol_print_date($db->jdate($obj->date_ech), 'day').''.price($obj->amount).''.price($obj->sumpaid).'
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'.$langs->trans("Total").''.price($tot_ttc).'
'; + print ""; - print ''; + print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; @@ -743,6 +834,14 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $societestatic->id = $obj->socid; $societestatic->name = $obj->name; $societestatic->email = $obj->email; @@ -776,8 +875,8 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user print ''; - print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; @@ -791,6 +890,14 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $i++; } + if ($othernb) { + print ''; + print ''; + print "\n"; + } + print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; @@ -822,7 +929,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays,".MAIN_DB_PREFIX."facture as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = 1"; + $sql .= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = ".Facture::STATUS_VALIDATED; $sql .= " AND f.entity IN (".getEntity('invoice').')'; 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; @@ -840,10 +947,19 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $num = $db->num_rows($resql); $i = 0; + $othernb = 0; print '
'; print '
'.$langs->trans("OrdersDeliveredToBill").' '.$num.''; + print $langs->trans("OrdersDeliveredToBill").' '; + print ''; + print ''.$num.''; + print ''; + print ''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("ToBill").''; - print $societestatic->getNomUrl(1, 'customer', 44); + print ''; + print $societestatic->getNomUrl(1, 'customer'); print ''.price($obj->total_ht).''.price($obj->total_ttc).'
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'.$langs->trans("Total").'   ('.$langs->trans("RemainderToBill").': '.price($tot_tobill).') '.price($tot_ht).''.price($tot_ttc).'
'; - print ''; + + print ''; + print ''; + print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; @@ -858,6 +974,14 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $facturestatic->ref = $obj->ref; $facturestatic->id = $obj->rowid; $facturestatic->total_ht = $obj->total_ht; @@ -898,14 +1022,14 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print '
'.$langs->trans("BillsCustomersUnpaid", $num).' '.$num.'
'; + print $langs->trans("BillsCustomersUnpaid", $num).' '; + print ''; + print ''.$num.''; + print ''; + print ''.$langs->trans("DateDue").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").'
'; print ''; - print ''; - print $societestatic->getNomUrl(1, 'customer', 44); + print ''; + print $societestatic->getNomUrl(1, 'customer'); print ''; print ''.dol_print_date($db->jdate($obj->datelimite), 'day').''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.price($obj->am).''; - print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am).''; + print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am, $obj->type).''; print ''; $total_ttc += $obj->total_ttc; @@ -915,6 +1039,16 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $i++; } + if ($othernb) { + $colspan = 6; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + print ''; + print ''; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print ''; + print "\n"; + } + print ''.$langs->trans("Total").'   ('.$langs->trans("RemainderToTake").': '.price($total_ttc - $totalam).') '; print ' '; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($total).''; @@ -941,7 +1075,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU { $facstatic = new FactureFournisseur($db); - $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.libelle as label, ff.total_ht, ff.total_tva, ff.total_ttc, ff.paye"; + $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.type, ff.libelle as label, ff.total_ht, ff.total_tva, ff.total_ttc, ff.paye"; $sql .= ", ff.date_lim_reglement"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; @@ -954,7 +1088,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= " WHERE s.rowid = ff.fk_soc"; $sql .= " AND ff.entity = ".$conf->entity; $sql .= " AND ff.paye = 0"; - $sql .= " AND ff.fk_statut = 1"; + $sql .= " AND ff.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 ff.fk_soc = ".$socid; // Add where from hooks @@ -962,7 +1096,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $reshook = $hookmanager->executeHooks('printFieldListWhereSupplierUnpaid', $parameters); $sql .= $hookmanager->resPrint; - $sql .= " GROUP BY ff.rowid, ff.ref, ff.fk_statut, ff.libelle, ff.total_ht, ff.tva, ff.total_tva, ff.total_ttc, ff.paye, ff.date_lim_reglement,"; + $sql .= " GROUP BY ff.rowid, ff.ref, ff.fk_statut, ff.type, ff.libelle, ff.total_ht, ff.tva, ff.total_tva, ff.total_ttc, ff.paye, ff.date_lim_reglement,"; $sql .= " s.nom, s.rowid, s.email, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur"; $sql .= " ORDER BY ff.date_lim_reglement ASC"; @@ -970,10 +1104,21 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU if ($resql) { $num = $db->num_rows($resql); + $othernb = 0; print '
'; print ''; - print ''; + + print ''; + print ''; + print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; @@ -989,8 +1134,17 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += 1; + $i++; + $total += $obj->total_ht; + $total_ttc += $obj->total_ttc; + continue; + } + $facstatic->ref = $obj->ref; $facstatic->id = $obj->rowid; + $facstatic->type = $obj->type; $facstatic->total_ht = $obj->total_ht; $facstatic->total_tva = $obj->total_tva; $facstatic->total_ttc = $obj->total_ttc; @@ -1005,15 +1159,15 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $societestatic->code_compta = $obj->code_compta; $societestatic->code_compta_fournisseur = $obj->code_compta_fournisseur; - print ''; - print ''; + print ''; print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; - print ''; + print ''; print ''; $total += $obj->total_ht; $total_ttc += $obj->total_ttc; @@ -1021,6 +1175,16 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $i++; } + if ($othernb) { + $colspan = 6; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + print ''; + print ''; + print "\n"; + } + print ''; print ''; if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index 78ef32072d6..d754760dd57 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -106,7 +106,7 @@ $sql .= " s.rowid as socid, s.nom as name, s.code_compta_fournisseur,"; $sql .= " p.rowid as pid, p.ref as ref, p.accountancy_code_buy,"; $sql .= " ct.accountancy_code_buy as account_tva, ct.recuperableonly"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva as ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva as ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = ".((int) $idpays); $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product"; $sql .= " JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = fd.fk_facture_fourn"; $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index bd44f6c47cc..62e8c77a133 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -109,7 +109,7 @@ $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product"; $sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = ".((int) $idpays); $sql .= " WHERE f.entity IN (".getEntity('invoice').")"; $sql .= " AND f.fk_statut > 0"; if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php index cd7bbfd11c2..6353d394f20 100644 --- a/htdocs/compta/localtax/card.php +++ b/htdocs/compta/localtax/card.php @@ -280,7 +280,7 @@ if ($id) print "
\n"; if ($object->rappro == 0) { - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; } else { print ''.$langs->trans("Delete").''; } diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index 10111dd7faa..1b1ad5351d3 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -88,7 +88,7 @@ if (empty($local)) } - +$calc = 0; /* * View */ @@ -120,11 +120,11 @@ $calc = $conf->global->MAIN_INFO_LOCALTAX_CALC.$local; if ($calc == 0 || $calc == 1) // Calculate on invoice for goods and services { $calcmode = $calc == 0 ? $langs->trans("CalcModeLT".$local) : $langs->trans("CalcModeLT".$local."Rec"); - $calcmode .= '
('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; + $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); $description .= $fsearch; - $description .= '
('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; + $description .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $builddate = dol_now(); $elementcust = $langs->trans("CustomersInvoices"); @@ -137,11 +137,11 @@ if ($calc == 0 || $calc == 1) // Calculate on invoice for goods and services if ($calc == 2) // Invoice for goods, payment for services { $calcmode = $langs->trans("CalcModeLT2Debt"); - $calcmode .= '
('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; + $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); $description .= $fsearch; - $description .= '
('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; + $description .= '('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $builddate = dol_now(); $elementcust = $langs->trans("CustomersInvoices"); @@ -157,10 +157,12 @@ report_header($name, '', $period, $periodlink, $description, $builddate, $export $vatcust = $langs->transcountry($local == 1 ? "LT1" : "LT2", $mysoc->country_code); $vatsup = $langs->transcountry($local == 1 ? "LT1" : "LT2", $mysoc->country_code); +print '
'; +print '
'.$langs->trans("BillsSuppliersUnpaid", $num).' '.$num.'
'; + print $langs->trans("BillsSuppliersUnpaid", $num).' '; + print ''; + // TODO: "impayees.php" looks very outdatetd and should be set to deprecated or directly remove in the next version + // + print ''.$num.''; + print ''; + print ''.$langs->trans("DateDue").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").'
'; + print '
'; print $facstatic->getNomUrl(1, ''); print ''.$societestatic->getNomUrl(1, 'supplier', 44).''.$societestatic->getNomUrl(1, 'supplier').''.dol_print_date($db->jdate($obj->date_lim_reglement), 'day').''.price($obj->total_ht).''.price($obj->total_ttc).''.price($obj->am).''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3).''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am, $obj->type).'
'; + print ''.$langs->trans("More").'... ('.$othernb.')'; + print '
'.$langs->trans("Total").'   ('.$langs->trans("RemainderToPay").': '.price($total_ttc - $totalam).')  '.price($total).'
'; + // IRPF that the customer has retained me if ($calc == 0 || $calc == 2) { - print '
'; print ''; print ''; print ''; @@ -235,7 +237,6 @@ if ($calc == 0 || $calc == 2) // IRPF I retained my supplier if ($calc == 0 || $calc == 1) { - print '
'.$langs->trans("Num").''.$langs->trans("Customer").'
'; print ''; print '"; print '"; @@ -291,8 +292,6 @@ if ($calc == 0 || $calc == 1) { print ''; print ''; print ''; - - print '
'.$langs->trans("Num")."'.$langs->trans("Supplier")."'.price($totalamount).''.price($total).'
'; } else { $langs->load("errors"); if ($coll_list == -1) @@ -305,15 +304,18 @@ if ($calc == 0 || $calc == 1) { if ($calc == 0) { // Total to pay - print '

'; - print ''; + print ''; + $diff = $x_coll_sum - $x_paye_sum; print ''; print ''; print '\n"; print "\n"; } + print '
'.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').''.price(price2num($diff, 'MT'))."
'; +print '
'; + // End of page llxFooter(); diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index 8e810495ff4..e8bcc89821b 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -227,10 +227,10 @@ $fsearch .= ''; $description = $fsearch; // Show report header -$name = $langs->trans("ReportByMonth"); +$name = $langs->transcountry($localTaxType == 1 ? "LT1ReportByMonth" : "LT2ReportByMonth", $mysoc->country_code); $description .= $langs->trans($LT); $calcmode = $langs->trans("LTReportBuildWithOptionDefinedInModule").' '; -$calcmode .= '('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')
'; +$calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; //if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); diff --git a/htdocs/compta/localtax/list.php b/htdocs/compta/localtax/list.php index a8b37c3ef93..2702a962281 100644 --- a/htdocs/compta/localtax/list.php +++ b/htdocs/compta/localtax/list.php @@ -31,7 +31,7 @@ $langs->load("compta"); $socid = GETPOST('socid', 'int'); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'tax', '', '', 'charges'); -$ltt = GETPOST("localTaxType"); +$ltt = GETPOST("localTaxType", 'int'); /* @@ -42,17 +42,15 @@ llxHeader(); $localtax_static = new Localtax($db); -$newcardbutton = ''; -if ($user->rights->tax->charges->creer) -{ - $newcardbutton .= dolGetButtonTitle($langs->trans('NewLocalTaxPayment', ($ltt + 1)), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/localtax/card.php?action=create&localTaxType='.$ltt); -} +$url = DOL_URL_ROOT.'/compta/localtax/card.php?action=create&localTaxType='.$ltt; +if (!empty($socid)) $url .= '&socid='.$socid; +$newcardbutton = dolGetButtonTitle($langs->trans('NewLocalTaxPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); print load_fiche_titre($langs->transcountry($ltt == 2 ? "LT2Payments" : "LT1Payments", $mysoc->country_code), $newcardbutton, 'title_accountancy'); $sql = "SELECT rowid, amount, label, f.datev, f.datep"; $sql .= " FROM ".MAIN_DB_PREFIX."localtax as f "; -$sql .= " WHERE f.entity = ".$conf->entity." AND localtaxtype=".$db->escape($ltt); +$sql .= " WHERE f.entity = ".$conf->entity." AND localtaxtype = ".$db->escape($ltt); $sql .= " ORDER BY datev DESC"; $result = $db->query($sql); diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index 058f6871c7d..ebb66778df7 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -134,7 +134,7 @@ $calcmode = ''; 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').')'; +$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; @@ -200,12 +200,13 @@ if ($local == 1) { } // VAT Received and paid +print '
'; echo ''; $y = $year_current; $total = 0; $i = 0; -$columns = 5; +$columns = 4; // Load arrays of datas $x_coll = tax_by_rate('localtax'.$local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); @@ -310,8 +311,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_sum = 0; $x_paye_ht = 0; - $span = $columns; - if ($modetax != 1) $span += 2; + $span = $columns - 1; + if ($modetax != 2) $span += 1; + if ($modetax != 1) $span += 1; // Customers invoices print ''; @@ -467,10 +469,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Blank line print ''; - print '
 
'; + //print ''; $diff = $x_coll_sum; - echo ''; + //echo '
'; //print table headers for this quadri - expenses now print ''; print ''; @@ -617,11 +619,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; } - print '
'.$elementsup.'
'; - // Total to pay - print '

'; - print ''; $diff = $x_coll_sum - $x_paye_sum; print ''; print ''; @@ -630,7 +628,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $i++; } + print '
'.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').'
'; +print '
'; // End of page llxFooter(); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 4eea16f706b..9d86cff65dd 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -47,7 +47,7 @@ $accountid = GETPOST('accountid', 'int'); $paymentnum = GETPOST('num_paiement', 'alpha'); $socid = GETPOST('socid', 'int'); -$sortfield = GETPOST('sortfield', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -107,7 +107,7 @@ if (empty($reshook)) if (substr($key, 0, 7) == 'amount_' && GETPOST($key) != '') { $cursorfacid = substr($key, 7); - $amounts[$cursorfacid] = price2num(trim(GETPOST($key))); + $amounts[$cursorfacid] = price2num(GETPOST($key)); $totalpayment = $totalpayment + $amounts[$cursorfacid]; if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++; $result = $tmpinvoice->fetch($cursorfacid); @@ -134,7 +134,7 @@ if (empty($reshook)) } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); - $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key))); + $multicurrency_amounts[$cursorfacid] = price2num(GETPOST($key)); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; $result = $tmpinvoice->fetch($cursorfacid); @@ -265,8 +265,6 @@ if (empty($reshook)) $paiement->paiementid = dol_getIdFromCode($db, GETPOST('paiementcode'), 'c_paiement', 'code', 'id', 1); $paiement->num_payment = GETPOST('num_paiement', 'alpha'); $paiement->note_private = GETPOST('comment', 'alpha'); - $paiement->num_paiement = $paiement->num_payment; // For bacward compatibility - $paiement->note = $paiement->note_private; // For bacward compatibility if (!$error) { @@ -526,7 +524,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie // Comments print ''.$langs->trans('Comments').''; print ''; - print ''; + print ''; print ''; @@ -851,7 +849,7 @@ if (!GETPOST('action', 'aZ09')) if (!$sortfield) $sortfield = 'p.datep'; $sql = 'SELECT p.datep as dp, p.amount, f.total_ttc as fa_amount, f.ref'; - $sql .= ', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; + $sql .= ', f.rowid as facid, c.libelle as paiement_type, p.num_paiement as num_payment'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql .= ', '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' WHERE p.fk_facture = f.rowid'; @@ -887,7 +885,7 @@ if (!GETPOST('action', 'aZ09')) print ''; print ''.$objp->ref."\n"; print ''.dol_print_date($db->jdate($objp->dp))."\n"; - print ''.$objp->paiement_type.' '.$objp->num_paiement."\n"; + print ''.$objp->paiement_type.' '.$objp->num_payment."\n"; print ''.price($objp->amount).''; print ' '; print ''; diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index 4acfd34a53a..dd7651a6147 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -39,7 +39,7 @@ $langs->loadLangs(array('bills', 'banks', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -60,7 +60,7 @@ if ($action == 'setnote' && $user->rights->facture->paiement) $db->begin(); $object->fetch($id); - $result = $object->update_note(GETPOST('note', 'none')); + $result = $object->update_note(GETPOST('note', 'restricthtml')); if ($result > 0) { $db->commit(); @@ -306,7 +306,7 @@ dol_fiche_end(); * List of invoices */ -$sql = 'SELECT f.rowid as facid, f.ref, f.type, f.total_ttc, f.paye, f.fk_statut, pf.amount, s.nom as name, s.rowid as socid'; +$sql = 'SELECT f.rowid as facid, f.ref, f.type, f.total_ttc, f.paye, f.entity, f.fk_statut, pf.amount, s.nom as name, s.rowid as socid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf,'.MAIN_DB_PREFIX.'facture as f,'.MAIN_DB_PREFIX.'societe as s'; $sql .= ' WHERE pf.fk_facture = f.rowid'; $sql .= ' AND f.fk_soc = s.rowid'; diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php index aaf216a7558..71cd900f915 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -38,7 +38,7 @@ $langs->loadLangs(array('banks', 'categories', 'bills', 'companies', 'compta')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -46,8 +46,8 @@ $fieldname = (!empty($ref) ? 'ref' : 'rowid'); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'cheque', $id, 'bordereau_cheque', '', 'fk_user_author', $fieldname); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "b.dateo,b.rowid"; @@ -57,7 +57,7 @@ $offset = $limit * $page; $dir = $conf->bank->dir_output.'/checkdeposits/'; $filterdate = dol_mktime(0, 0, 0, GETPOST('fdmonth'), GETPOST('fdday'), GETPOST('fdyear')); -$filteraccountid = GETPOST('accountid'); +$filteraccountid = GETPOST('accountid', 'int'); $object = new RemiseCheque($db); @@ -152,10 +152,10 @@ if ($action == 'create' && $_POST["accountid"] > 0 && $user->rights->banque->che } } -if ($action == 'remove' && $id > 0 && $_GET["lineid"] > 0 && $user->rights->banque->cheque) +if ($action == 'remove' && $id > 0 && GETPOST("lineid", 'int') > 0 && $user->rights->banque->cheque) { $object->id = $id; - $result = $object->removeCheck($_GET["lineid"]); + $result = $object->removeCheck(GETPOST("lineid", "int")); if ($result === 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); @@ -206,7 +206,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->banque->c if ($action == 'confirm_reject_check' && $confirm == 'yes' && $user->rights->banque->cheque) { $reject_date = dol_mktime(0, 0, 0, GETPOST('rejectdate_month'), GETPOST('rejectdate_day'), GETPOST('rejectdate_year')); - $rejected_check = GETPOST('bankid'); + $rejected_check = GETPOST('bankid', 'int'); $object->fetch($id); $paiement_id = $object->rejectCheck($rejected_check, $reject_date); @@ -333,7 +333,7 @@ if ($action == 'new') if ($action == 'reject_check') { $formquestion = array( - array('type' => 'hidden', 'name' => 'bankid', 'value' => GETPOST('lineid')), + array('type' => 'hidden', 'name' => 'bankid', 'value' => GETPOST('lineid', 'int')), array('type' => 'date', 'name' => 'rejectdate_', 'label' => $langs->trans("RejectCheckDate"), 'value' => dol_now()) ); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans("RejectCheck"), $langs->trans("ConfirmRejectCheck"), 'confirm_reject_check', $formquestion, '', 1); @@ -394,7 +394,7 @@ if ($action == 'new') $sql .= " AND b.fk_bordereau = 0"; $sql .= " AND b.amount > 0"; if ($filterdate) $sql .= " AND b.dateo = '".$db->idate($filterdate)."'"; - if ($filteraccountid > 0) $sql .= " AND ba.rowid= '".$filteraccountid."'"; + if ($filteraccountid > 0) $sql .= " AND ba.rowid = ".((int) $filteraccountid); $sql .= $db->order("b.dateo,b.rowid", "ASC"); $resql = $db->query($sql); @@ -734,12 +734,12 @@ print '
'; if ($user->socid == 0 && !empty($object->id) && $object->statut == 0 && $user->rights->banque->cheque) { - print ''.$langs->trans('Validate').''; + print ''.$langs->trans('Validate').''; } if ($user->socid == 0 && !empty($object->id) && $user->rights->banque->cheque) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } print '
'; diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 48c58dc7219..00815c90f7d 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -211,7 +211,7 @@ class RemiseCheque extends CommonObject $sql .= " WHERE b.fk_type = 'CHQ'"; $sql .= " AND b.amount > 0"; $sql .= " AND b.fk_bordereau = 0"; - $sql .= " AND b.fk_account='".$account_id."'"; + $sql .= " AND b.fk_account = ".((int) $account_id); if ($limit) $sql .= $this->db->plimit($limit); dol_syslog("RemiseCheque::Create", LOG_DEBUG); @@ -358,7 +358,7 @@ class RemiseCheque extends CommonObject if ($this->errno == 0 && $numref) { $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque"; - $sql .= " SET statut = 1, ref = '".$numref."'"; + $sql .= " SET statut = 1, ref = '".$this->db->escape($numref)."'"; $sql .= " WHERE rowid = ".$this->id; $sql .= " AND entity = ".$conf->entity; $sql .= " AND statut = 0"; @@ -662,6 +662,7 @@ class RemiseCheque extends CommonObject global $conf; $this->errno = 0; + $this->db->begin(); $total = 0; $nb = 0; @@ -681,8 +682,8 @@ class RemiseCheque extends CommonObject $this->db->free($resql); $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque"; - $sql .= " SET amount = '".price2num($total)."'"; - $sql .= ", nbcheque = ".$nb; + $sql .= " SET amount = ".price2num($total); + $sql .= ", nbcheque = ".((int) $nb); $sql .= " WHERE rowid = ".$this->id; $sql .= " AND entity = ".$conf->entity; @@ -722,8 +723,8 @@ class RemiseCheque extends CommonObject { $sql = "UPDATE ".MAIN_DB_PREFIX."bank"; $sql .= " SET fk_bordereau = 0"; - $sql .= " WHERE rowid = '".$account_id."'"; - $sql .= " AND fk_bordereau = ".$this->id; + $sql .= " WHERE rowid = ".((int) $account_id); + $sql .= " AND fk_bordereau = ".((int) $this->id); $resql = $this->db->query($sql); if ($resql) @@ -774,18 +775,18 @@ class RemiseCheque extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf'; $sql .= ' WHERE pf.fk_paiement = '.$payment->id; - $resql = $db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $rejectedPayment = new Paiement($db); + $rejectedPayment = new Paiement($this->db); $rejectedPayment->amounts = array(); $rejectedPayment->datepaye = $rejection_date; $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement', 'code', 'id', 1); $rejectedPayment->num_payment = $payment->num_payment; - while ($obj = $db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $invoice = new Facture($db); + $invoice = new Facture($this->db); $invoice->fetch($obj->fk_facture); $invoice->set_unpaid($user); diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index e76936c71fd..3bb45c4e312 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -124,11 +124,9 @@ if ($resql) if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; - $newcardbutton = ''; - if ($user->rights->banque->cheque) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewCheckDeposit'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/paiement/cheque/card.php?action=new'); - } + $url = DOL_URL_ROOT.'/compta/paiement/cheque/card.php?action=new'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('NewCheckDeposit'), '', 'fa fa-plus-circle', $url, '', $user->rights->banque->cheque); print '
'; if ($optioncss != '') print ''; diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 5e01454dd75..5cb16bdcbe3 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -9,6 +9,7 @@ * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2018 Thibault FOUCART * Copyright (C) 2018 Frédéric France + * Copyright (C) 2020 Andreu Bisquerra Gaya * * 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 @@ -73,6 +74,8 @@ class Paiement extends CommonObject public $amounts = array(); // array: invoice ID => amount for that invoice (in the main currency)> public $multicurrency_amounts = array(); // array: invoice ID => amount for that invoice (in the invoice's currency)> + public $pos_change = 0; // Excess received in TakePOS cash payment + public $author; public $paiementid; // Type of payment. Id saved into fields fk_paiement on llx_paiement public $paiementcode; // Code of payment. @@ -87,13 +90,6 @@ class Paiement extends CommonObject */ public $type_code; - /** - * @var string Numero du CHQ, VIR, etc... - * @deprecated - * @see $num_payment - */ - public $numero; - /** * @var string Numero du CHQ, VIR, etc... * @deprecated @@ -140,6 +136,10 @@ class Paiement extends CommonObject */ public $fk_paiement; // Type of payment + /** + * @var string payment external reference + */ + public $ref_ext; /** * Constructor @@ -161,7 +161,7 @@ class Paiement extends CommonObject */ public function fetch($id, $ref = '', $fk_bank = '') { - $sql = 'SELECT p.rowid, p.ref, p.datep as dp, p.amount, p.statut, p.ext_payment_id, p.ext_payment_site, p.fk_bank, p.multicurrency_amount,'; + $sql = 'SELECT p.rowid, p.ref, p.ref_ext, p.datep as dp, p.amount, p.statut, p.ext_payment_id, p.ext_payment_site, p.fk_bank, p.multicurrency_amount,'; $sql .= ' c.code as type_code, c.libelle as type_label,'; $sql .= ' p.num_paiement as num_payment, p.note,'; $sql .= ' b.fk_account'; @@ -184,9 +184,9 @@ class Paiement extends CommonObject $this->id = $obj->rowid; $this->ref = $obj->ref ? $obj->ref : $obj->rowid; + $this->ref_ext = $obj->ref_ext; $this->date = $this->db->jdate($obj->dp); $this->datepaye = $this->db->jdate($obj->dp); - $this->num_paiement = $obj->num_payment; // deprecated $this->num_payment = $obj->num_payment; $this->montant = $obj->amount; // deprecated $this->amount = $obj->amount; @@ -276,6 +276,10 @@ class Paiement extends CommonObject $this->ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : ''); + if (empty($this->ref_ext)) { + $this->ref_ext = ''; + } + if ($way == 'dolibarr') { $total = $totalamount; @@ -285,11 +289,12 @@ class Paiement extends CommonObject $mtotal = $totalamount; } - $num_payment = ($this->num_payment ? $this->num_payment : $this->num_paiement); - $note = ($this->note_public ? $this->note_public : $this->note); + $num_payment = $this->num_payment; + $note = ($this->note_private ? $this->note_private : $this->note); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, ext_payment_id, ext_payment_site, fk_user_creat)"; - $sql .= " VALUES (".$conf->entity.", '".$this->db->escape($this->ref)."', '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', ".$total.", ".$mtotal.", ".$this->paiementid.", '".$this->db->escape($num_payment)."', '".$this->db->escape($note)."', ".($this->ext_payment_id ? "'".$this->db->escape($this->ext_payment_id)."'" : "null").", ".($this->ext_payment_site ? "'".$this->db->escape($this->ext_payment_site)."'" : "null").", ".$user->id.")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, ref_ext, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, ext_payment_id, ext_payment_site, fk_user_creat, pos_change)"; + $sql .= " VALUES (".$conf->entity.", '".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', ".$total.", ".$mtotal.", ".$this->paiementid.", "; + $sql .= "'".$this->db->escape($num_payment)."', '".$this->db->escape($note)."', ".($this->ext_payment_id ? "'".$this->db->escape($this->ext_payment_id)."'" : "null").", ".($this->ext_payment_site ? "'".$this->db->escape($this->ext_payment_site)."'" : "null").", ".$user->id.", ".((int) $this->pos_change).")"; $resql = $this->db->query($sql); if ($resql) @@ -703,7 +708,7 @@ class Paiement extends CommonObject $bank_line_id, $this->id_prelevement, DOL_URL_ROOT.'/compta/prelevement/card.php?id=', - $this->num_paiement, + $this->num_payment, 'withdraw' ); } @@ -795,7 +800,7 @@ class Paiement extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.'bank'; $sql .= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'"; - $sql .= " WHERE rowid IN (SELECT fk_bank FROM ".MAIN_DB_PREFIX."bank_url WHERE type = '".$type."' AND url_id = ".$this->id.")"; + $sql .= " WHERE rowid IN (SELECT fk_bank FROM ".MAIN_DB_PREFIX."bank_url WHERE type = '".$this->db->escape($type)."' AND url_id = ".$this->id.")"; $sql .= " AND rappro = 0"; $result = $this->db->query($sql); @@ -1154,7 +1159,7 @@ class Paiement extends CommonObject if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips $result = ''; - $label = ''.$langs->trans("Payment").'
'; + $label = img_picto('', $this->picto).' '.$langs->trans("Payment").'
'; $label .= ''.$langs->trans("Ref").': '.$this->ref; if ($this->datepaye ? $this->datepaye : $this->date) $label .= '
'.$langs->trans("Date").': '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); if ($mode == 'withlistofinvoices') @@ -1167,7 +1172,7 @@ class Paiement extends CommonObject foreach ($arraybill as $billid) { $facturestatic->fetch($billid); - $label .= '
'.$facturestatic->getNomUrl(1).' '.$facturestatic->getLibStatut(2, 1); + $label .= '
'.$facturestatic->getNomUrl(1, '', 0, 0, '', 1).' '.$facturestatic->getLibStatut(2, 1); } } } diff --git a/htdocs/compta/paiement/info.php b/htdocs/compta/paiement/info.php index 00c3440b868..68d987b06ff 100644 --- a/htdocs/compta/paiement/info.php +++ b/htdocs/compta/paiement/info.php @@ -33,7 +33,7 @@ $langs->loadLangs(array('bills', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); /* diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index eb2523960f3..e2f3ea9012b 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -1,13 +1,14 @@ - * Copyright (C) 2004-2011 Laurent Destailleur - * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2013 Cédric Salvador - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2015 Juanjo Menent - * Copyright (C) 2017 Alexandre Spangaro - * Copyright (C) 2018 Ferran Marcet - * Copyright (C) 2018 Charlene Benke +/* Copyright (C) 2001-2006 Rodolphe Quiedeville + * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2013 Cédric Salvador + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2015 Juanjo Menent + * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Ferran Marcet + * Copyright (C) 2018 Charlene Benke + * Copyright (C) 2020 Tobias Sekan * * 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,6 +31,11 @@ */ require '../../main.inc.php'; + +// Security check +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'facture', $facid, ''); + require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; @@ -39,136 +45,159 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; // Load translation files required by the page $langs->loadLangs(array('bills', 'banks', 'compta', 'companies')); -$action = GETPOST('action', 'alpha'); -$confirm = GETPOST('confirm', 'alpha'); -$optioncss = GETPOST('optioncss', 'alpha'); +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'paymentlist'; -$facid = GETPOST('facid', 'int'); -$socid = GETPOST('socid', 'int'); -$userid = GETPOST('userid', 'int'); -$day = GETPOST('day', 'int'); -$month = GETPOST('month', 'int'); -$year = GETPOST('year', 'int'); +$facid = GETPOST('facid', 'int'); +$socid = GETPOST('socid', 'int'); +$userid = GETPOST('userid', 'int'); +$day = GETPOST('day', 'int'); +$month = GETPOST('month', 'int'); +$year = GETPOST('year', 'int'); -// Security check -if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'facture', $facid, ''); +$search_ref = GETPOST("search_ref", "alpha"); +$search_account = GETPOST("search_account", "int"); +$search_paymenttype = GETPOST("search_paymenttype"); +$search_amount = GETPOST("search_amount", 'alpha'); // alpha because we must be able to search on "< x" +$search_company = GETPOST("search_company", 'alpha'); +$search_payment_num = GETPOST('search_payment_num', 'alpha'); -$paymentstatic = new Paiement($db); -$accountstatic = new Account($db); -$companystatic = new Societe($db); +$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'); -$search_ref = GETPOST("search_ref", "alpha"); -$search_account = GETPOST("search_account", "int"); -$search_paymenttype = GETPOST("search_paymenttype"); -$search_amount = GETPOST("search_amount", 'alpha'); // alpha because we must be able to search on "< x" -$search_company = GETPOST("search_company", 'alpha'); -$search_payment_num = GETPOST('search_payment_num', '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) { $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"; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new Paiement($db); $hookmanager->initHooks(array('paymentlist')); $extrafields = new ExtraFields($db); -$arrayfields = array(); +$arrayfields = array( + 'p.rowid' => array('label'=>"RefPayment", 'checked'=>1, 'position'=>10), + 'p.datep' => array('label'=>"Date", 'checked'=>1, 'position'=>20), + 's.nom' => array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30), + 'c.libelle' => array('label'=>"Type", 'checked'=>1, 'position'=>40), + 'transaction' => array('label'=>"BankTransactionLine", 'checked'=>1, 'position'=>50, 'enabled'=>(!empty($conf->banque->enabled))), + 'ba.label' => array('label'=>"Account", 'checked'=>1, 'position'=>60, 'enabled'=>(!empty($conf->banque->enabled))), + 'p.num_payment' => array('label'=>"Numero", 'checked'=>1, 'position'=>70, 'tooltip'=>"ChequeOrTransferNumber"), + 'p.amount' => array('label'=>"Amount", 'checked'=>1, 'position'=>80), + 'p.statut' => array('label'=>"Status", 'checked'=>1, 'position'=>90, 'enabled'=>(!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION))), +); +$arrayfields = dol_sort_array($arrayfields, 'position'); /* * 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 -{ - $search_ref = ""; - $search_account = ""; - $search_amount = ""; - $search_paymenttype = ""; - $search_payment_num = ""; - $search_company = ""; - $day = ''; - $year = ''; - $month = ''; - $search_array_options = array(); +$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)) { + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // 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')) { + $search_ref = ''; + $search_account = ''; + $search_amount = ''; + $search_paymenttype = ''; + $search_payment_num = ''; + $search_company = ''; + $day = ''; + $year = ''; + $month = ''; + $option = ''; + $toselect = ''; + $search_array_options = array(); + } } - /* - * View + * View */ $form = new Form($db); $formother = new FormOther($db); +$accountstatic = new Account($db); +$companystatic = new Societe($db); +$bankline = new AccountLine($db); llxHeader('', $langs->trans('ListPayment')); -if (GETPOST("orphelins", "alpha")) -{ - // Payments not linked to an invoice. Should not happend. For debug only. - $sql = "SELECT p.rowid, p.ref, p.datep as dp, p.amount,"; - $sql .= " p.statut, p.num_paiement as num_payment,"; - $sql .= " c.code as paiement_code"; +if (GETPOST("orphelins", "alpha")) { + // Payments not linked to an invoice. Should not happend. For debug only. + $sql = "SELECT p.rowid, p.ref, p.datep, p.amount, p.statut, p.num_paiement as num_payment"; + $sql .= ", c.code as paiement_code"; + // 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."paiement as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; - $sql .= " WHERE p.entity IN (".getEntity('invoice').")"; - $sql .= " AND pf.fk_facture IS NULL"; + $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; + $sql .= " WHERE p.entity IN (".getEntity('invoice').")"; + $sql .= " AND pf.fk_facture IS NULL"; + // 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; } else { - $sql = "SELECT DISTINCT p.rowid, p.ref, p.datep as dp, p.amount,"; // DISTINCT is to avoid duplicate when there is a link to sales representatives - $sql .= " p.statut, p.num_paiement as num_payment,"; - $sql .= " c.code as paiement_code,"; - $sql .= " ba.rowid as bid, ba.ref as bref, ba.label as blabel, ba.number, ba.account_number as account_number, ba.fk_accountancy_journal as accountancy_journal,"; - $sql .= " s.rowid as socid, s.nom as name, s.email"; + // DISTINCT is to avoid duplicate when there is a link to sales representatives + $sql = "SELECT DISTINCT p.rowid, p.ref, p.datep, p.fk_bank, p.amount, p.statut, p.num_paiement as num_payment"; + $sql .= ", c.code as paiement_code"; + $sql .= ", ba.rowid as bid, ba.ref as bref, ba.label as blabel, ba.number, ba.account_number as account_number, ba.fk_accountancy_journal as accountancy_journal"; + $sql .= ", s.rowid as socid, s.nom as name, s.email"; + // 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."paiement as p"; - $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 .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON pf.fk_facture = f.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.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"; - } - $sql .= " WHERE p.entity IN (".getEntity('invoice').")"; - if (!$user->rights->societe->client->voir && !$socid) - { - $sql .= " AND sc.fk_user = ".$user->id; - } - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; - if ($userid) - { - if ($userid == -1) $sql .= " AND f.fk_user_author IS NULL"; - else $sql .= " AND f.fk_user_author = ".$userid; - } - // Search criteria - $sql .= dolSqlDateFilter("p.datep", $day, $month, $year); - if ($search_ref) $sql .= natural_search('p.ref', $search_ref); - if ($search_account > 0) $sql .= " AND b.fk_account=".$search_account; - if ($search_paymenttype != "") $sql .= " AND c.code='".$db->escape($search_paymenttype)."'"; - if ($search_payment_num != '') $sql .= natural_search('p.num_paiement', $search_payment_num); - if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); - if ($search_company) $sql .= natural_search('s.nom', $search_company); + $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p"; + $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 .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON pf.fk_facture = f.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.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"; + } + $sql .= " WHERE p.entity IN (".getEntity('invoice').")"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; + } + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } + if ($userid) { + if ($userid == -1) $sql .= " AND f.fk_user_author IS NULL"; + else $sql .= " AND f.fk_user_author = ".$userid; + } + + // Search criteria + $sql .= dolSqlDateFilter("p.datep", $day, $month, $year); + if ($search_ref) $sql .= natural_search('p.ref', $search_ref); + if ($search_account > 0) $sql .= " AND b.fk_account=".$search_account; + if ($search_paymenttype != '') $sql .= " AND c.code='".$db->escape($search_paymenttype)."'"; + if ($search_payment_num != '') $sql .= natural_search('p.num_paiement', $search_payment_num); + if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); + if ($search_company) $sql .= natural_search('s.nom', $search_company); + // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook @@ -177,209 +206,278 @@ if (GETPOST("orphelins", "alpha")) $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 total resultset is smaller then paging size (filtering), goto and load page 0 + if (($page * $limit) > $nbtotalofrecords) { $page = 0; $offset = 0; } } $sql .= $db->plimit($limit + 1, $offset); -//print "$sql"; $resql = $db->query($sql); -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); - $param .= (GETPOST("orphelins") ? "&orphelins=1" : ""); - $param .= ($search_ref ? "&search_ref=".urlencode($search_ref) : ""); - $param .= ($search_company ? "&search_company=".urlencode($search_company) : ""); - $param .= ($search_amount ? "&search_amount=".urlencode($search_amount) : ""); - $param .= ($search_payment_num ? "&search_payment_num=".urlencode($search_payment_num) : ""); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans("ReceivedCustomersPayments"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'bill', 0, '', '', $limit, 0, 0, 1); - - print '
'; - print ''."\n"; - - // Lines for filters fields - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->banque->enabled)) - { - print ''; - } - print ''; - print ''; - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { - print ''; - } - print "\n"; - - print ''; - print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "p.rowid", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "dp", "", $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "c.libelle", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("Numero", $_SERVER["PHP_SELF"], "p.num_paiement", "", $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("Amount", $_SERVER["PHP_SELF"], "p.amount", "", $param, 'class="right"', $sortfield, $sortorder); - //print_liste_field_titre("Invoices"),"","","",$param,'class="left"',$sortfield,$sortorder); - - $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($conf->global->BILL_ADD_PAYMENT_VALIDATION)) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.statut", "", $param, 'class="right"', $sortfield, $sortorder); - print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; - - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); - - $paymentstatic->id = $objp->rowid; - $paymentstatic->ref = $objp->ref; - - $companystatic->id = $objp->socid; - $companystatic->name = $objp->name; - $companystatic->email = $objp->email; - - print ''; - - print ''; - if (!$i) $totalarray['nbfield']++; - - // Date - $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; - print ''; - if (!$i) $totalarray['nbfield']++; - - // Thirdparty - print ''; - if (!$i) $totalarray['nbfield']++; - - // Type - print ''; - if (!$i) $totalarray['nbfield']++; - - // Payment number - print ''; - if (!$i) $totalarray['nbfield']++; - - // Account - if (!empty($conf->banque->enabled)) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Amount - print ''; - if (!$i) $totalarray['nbfield']++; - $totalarray['pos'][7] = 'amount'; - $totalarray['val']['amount'] += $objp->amount; - - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - print ''; - if (!$i) $totalarray['nbfield']++; - - print ''; - - $i++; - } - - // Show total line - include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - - - print "
'; - print ''; - print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); - print ''; - print ''; - print ''; - $form->select_types_paiements($search_paymenttype, 'search_paymenttype', '', 2, 1, 1); - print ''; - print ''; - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); - print ''; - print ''; - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print ''; - print '
'; - print $paymentstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), $dateformatforpayment).''; - if ($objp->socid > 0) - { - print $companystatic->getNomUrl(1, '', 24); - } - print ''.$langs->trans("PaymentTypeShort".$objp->paiement_code).''.$objp->num_payment.''; - if ($objp->bid > 0) - { - $accountstatic->id = $objp->bid; - $accountstatic->ref = $objp->bref; - $accountstatic->label = $objp->blabel; - $accountstatic->number = $objp->number; - $accountstatic->account_number = $objp->account_number; - - $accountingjournal = new AccountingJournal($db); - $accountingjournal->fetch($objp->accountancy_journal); - $accountstatic->accountancy_journal = $accountingjournal->code; - - print $accountstatic->getNomUrl(1); - } - print ''.price($objp->amount).''; - if ($objp->statut == 0) print ''; - print $paymentstatic->LibStatut($objp->statut, 5); - if ($objp->statut == 0) print ''; - print '
\n"; - print "
"; - print "\n"; -} else { - dol_print_error($db); +if (!$resql) { + dol_print_error($db); + llxFooter(); + $db->close(); + exit; } +$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); +$param .= (GETPOST("orphelins") ? "&orphelins=1" : ''); +$param .= ($search_ref ? "&search_ref=".urlencode($search_ref) : ''); +$param .= ($search_company ? "&search_company=".urlencode($search_company) : ''); +$param .= ($search_amount ? "&search_amount=".urlencode($search_amount) : ''); +$param .= ($search_payment_num ? "&search_payment_num=".urlencode($search_payment_num) : ''); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + +print '
'; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans("ReceivedCustomersPayments"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'bill', 0, '', '', $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); + +print '
'; +print ''; + +print ''; + +// Filters: Lines (placeholder) +print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; +} + +// Filter: Ref +if (!empty($arrayfields['p.rowid']['checked'])) { + print ''; +} + +// Filter: Date +if (!empty($arrayfields['p.datep']['checked'])) { + print ''; +} + +// Filter: Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print ''; +} + +// Filter: Payment type +if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; +} + +// Filter: Bank transaction number +if (!empty($arrayfields['transaction']['checked'])) { + print ''; +} + +// Filter: Cheque number (fund transfer) +if (!empty($arrayfields['p.num_payment']['checked'])) { + print ''; +} + +// Filter: Bank account +if (!empty($arrayfields['ba.label']['checked'])) { + print ''; +} + +// Filter: Amount +if (!empty($arrayfields['p.amount']['checked'])) { + print ''; +} + +// Filter: Status (only placeholder) +if (!empty($arrayfields['p.statut']['checked'])) { + print ''; +} + +// 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; + +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['p.rowid']['checked'])) print_liste_field_titre($arrayfields['p.rowid']['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_payment']['checked'])) print_liste_field_titre($arrayfields['p.num_payment']['label'], $_SERVER["PHP_SELF"], "p.num_payment", '', $param, '', $sortfield, $sortorder, '', $arrayfields['p.num_payment']['tooltip']); +if (!empty($arrayfields['transaction']['checked'])) print_liste_field_titre($arrayfields['transaction']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); +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, 'class="right"', $sortfield, $sortorder); +if (!empty($arrayfields['p.statut']['checked'])) print_liste_field_titre($arrayfields['p.statut']['label'], $_SERVER["PHP_SELF"], "p.statut", '', $param, 'class="right"', $sortfield, $sortorder); + +// 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; + +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); +print ""; + +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $objp = $db->fetch_object($resql); + + $object->id = $objp->rowid; + $object->ref = $objp->ref; + + $companystatic->id = $objp->socid; + $companystatic->name = $objp->name; + $companystatic->email = $objp->email; + + print ''; + + // No + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Ref + if (!empty($arrayfields['p.rowid']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Date + if (!empty($arrayfields['p.datep']['checked'])) { + $dateformatforpayment = 'day'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Thirdparty + if (!empty($arrayfields['s.nom']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Payment type + if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Filter: Cheque number (fund transfer) + if (!empty($arrayfields['p.num_payment']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Bank transaction + if (!empty($arrayfields['transaction']['checked'])) { + $bankline->fetch($objp->fk_bank); + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Bank account + if (!empty($arrayfields['ba.label']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Amount + if (!empty($arrayfields['p.amount']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + $totalarray['pos'][8] = 'amount'; + $totalarray['val']['amount'] += $objp->amount; + } + + // Status + if (!empty($arrayfields['p.statut']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Buttons + print ''; + if (!$i) $totalarray['nbfield']++; + + print ''; + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +print "
'; + print ''; + print ''; + print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); + print ''; + print ''; + print ''; + $form->select_types_paiements($search_paymenttype, 'search_paymenttype', '', 2, 1, 1); + print ''; + print ''; + print ''; + print ''; + $form->select_comptes($search_account, 'search_account', 0, '', 1); + print ''; + print ''; + print ''; + print ''; +print $form->showFilterAndCheckAddButtons(0); +print '
'.(($offset * $limit) + $i).''.$object->getNomUrl(1).''.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).''; + if ($objp->socid > 0) { + print $companystatic->getNomUrl(1, '', 24); + } + print ''.$langs->trans("PaymentTypeShort".$objp->paiement_code).''.$objp->num_payment.''.$bankline->getNomUrl(1, 0).''; + if ($objp->bid > 0) { + $accountstatic->id = $objp->bid; + $accountstatic->ref = $objp->bref; + $accountstatic->label = $objp->blabel; + $accountstatic->number = $objp->number; + $accountstatic->account_number = $objp->account_number; + + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($objp->accountancy_journal); + $accountstatic->accountancy_journal = $accountingjournal->code; + + print $accountstatic->getNomUrl(1); + } + print ''.price($objp->amount).''; + if ($objp->statut == 0) print ''; + print $object->LibStatut($objp->statut, 5); + if ($objp->statut == 0) print ''; + print '
"; +print "
"; +print "
"; + // End of page llxFooter(); $db->close(); diff --git a/htdocs/compta/paiement/tovalidate.php b/htdocs/compta/paiement/tovalidate.php index 349c483a5db..00e9a0c4074 100644 --- a/htdocs/compta/paiement/tovalidate.php +++ b/htdocs/compta/paiement/tovalidate.php @@ -40,8 +40,8 @@ if ($user->socid > 0) $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index 298866a2020..5f442ab0b18 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("bills"); $chid = GETPOST("id", 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $amounts = array(); // Security check @@ -112,8 +112,8 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm == 'y $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'); + $paiement->note = GETPOST("note", 'restricthtml'); + $paiement->note_private = GETPOST("note", 'restricthtml'); if (!$error) { diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index fbe5d926d33..0e71c83f6cb 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -182,7 +182,7 @@ print ''.$langs->trans('Date').''.dol_print_date($o print ''.$langs->trans('Mode').''.$langs->trans("PaymentType".$object->type_code).''; // Numero -print ''.$langs->trans('Numero').''.$object->num_paiement.''; +print ''.$langs->trans('Numero').''.$object->num_payment.''; // Montant print ''.$langs->trans('Amount').''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).''; @@ -311,7 +311,7 @@ if ($action == '') { if (!$disable_delete) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php index 4ec2b5d3443..2691e14504d 100644 --- a/htdocs/compta/prelevement/card.php +++ b/htdocs/compta/prelevement/card.php @@ -37,7 +37,7 @@ $langs->loadLangs(array('banks', 'categories', 'bills', 'companies', 'withdrawal if ($user->socid > 0) accessforbidden(); // Get supervariables -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); @@ -45,8 +45,8 @@ $type = GETPOST('type', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -81,38 +81,38 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($action == 'confirm_delete') - { - $res = $object->delete($user); - if ($res > 0) - { - if ($object->type == 'bank-transfer') { - header("Location: ".DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php'); - } else { - header("Location: ".DOL_URL_ROOT.'/compta/prelevement/index.php'); - } - exit; - } - } + if ($action == 'confirm_delete') + { + $res = $object->delete($user); + if ($res > 0) + { + if ($object->type == 'bank-transfer') { + header("Location: ".DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php'); + } else { + header("Location: ".DOL_URL_ROOT.'/compta/prelevement/index.php'); + } + exit; + } + } - // Seems to no be used and replaced with $action == 'infocredit' - if ($action == 'confirm_credite' && GETPOST('confirm', 'alpha') == 'yes') - { - $res = $object->set_credite(); - if ($res >= 0) - { - header("Location: card.php?id=".$id); - exit; - } - } + // Seems to no be used and replaced with $action == 'infocredit' + if ($action == 'confirm_credite' && GETPOST('confirm', 'alpha') == 'yes') + { + $res = $object->set_credite(); + if ($res >= 0) + { + header("Location: card.php?id=".$id); + exit; + } + } - if ($action == 'infotrans' && $user->rights->prelevement->bons->send) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if ($action == 'infotrans' && $user->rights->prelevement->bons->send) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - /* + /* if ($_FILES['userfile']['name'] && basename($_FILES['userfile']['name'],".ps") == $object->ref) { $dir = $conf->prelevement->dir_output.'/receipts'; @@ -133,24 +133,24 @@ if (empty($reshook)) $error = $object->set_infotrans($user, $dt, GETPOST('methode', 'alpha')); - if ($error) - { - header("Location: card.php?id=".$id."&error=$error"); - exit; - } - } + if ($error) + { + header("Location: card.php?id=".$id."&error=$error"); + exit; + } + } // Set direct debit order to credited, create payment and close invoices if ($action == 'infocredit' && $user->rights->prelevement->bons->credit) { $dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $error = $object->set_infocredit($user, $dt); - if ($error) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $error = $object->set_infocredit($user, $dt); + if ($error) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } @@ -179,7 +179,7 @@ if ($id > 0 || $ref) }*/ - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); @@ -317,15 +317,15 @@ if ($id > 0 || $ref) if (empty($object->date_trans) && $user->rights->prelevement->bons->send) { - print "id."\">".$langs->trans("SetToStatusSent").""; + print "id."\">".$langs->trans("SetToStatusSent").""; } if (!empty($object->date_trans) && $object->date_credit == 0) { - print "id."\">".$langs->trans("ClassCredited").""; + print "id."\">".$langs->trans("ClassCredited").""; } - print "id."\">".$langs->trans("Delete").""; + print "id."\">".$langs->trans("Delete").""; print "
"; } diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 1bea234abfc..9d3c5bef7a8 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -205,9 +205,9 @@ class BonPrelevement extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; $sql .= " WHERE fk_prelevement_bons = ".$this->id; $sql .= " AND fk_soc =".$client_id; - $sql .= " AND code_banque ='".$code_banque."'"; - $sql .= " AND code_guichet ='".$code_guichet."'"; - $sql .= " AND number ='".$number."'"; + $sql .= " AND code_banque = '".$this->db->escape($code_banque)."'"; + $sql .= " AND code_guichet = '".$this->db->escape($code_guichet)."'"; + $sql .= " AND number = '".$this->db->escape($number)."'"; $resql = $this->db->query($sql); if ($resql) @@ -234,10 +234,10 @@ class BonPrelevement extends CommonObject $sql .= ", ".$client_id; $sql .= ", '".$this->db->escape($client_nom)."'"; $sql .= ", '".price2num($amount)."'"; - $sql .= ", '".$code_banque."'"; - $sql .= ", '".$code_guichet."'"; - $sql .= ", '".$number."'"; - $sql .= ", '".$number_key."'"; + $sql .= ", '".$this->db->escape($code_banque)."'"; + $sql .= ", '".$this->db->escape($code_guichet)."'"; + $sql .= ", '".$this->db->escape($number)."'"; + $sql .= ", '".$this->db->escape($number_key)."'"; $sql .= ")"; if ($this->db->query($sql)) @@ -318,7 +318,7 @@ class BonPrelevement extends CommonObject $this->type = $obj->type; $this->status = $obj->status; - $this->statut = $obj->status; // For backward compatibility + $this->statut = $obj->status; // For backward compatibility $this->fetched = 1; @@ -507,10 +507,9 @@ class BonPrelevement extends CommonObject } $paiement->num_payment = $this->ref; // Set ref of direct debit note - $paiement->num_paiement = $this->ref; // For backward compatibility $paiement->id_prelevement = $this->id; - $paiement_id = $paiement->create($user); // This use ->paiementid, that is ID of payment mode + $paiement_id = $paiement->create($user); // This use ->paiementid, that is ID of payment mode if ($paiement_id < 0) { $error++; @@ -540,7 +539,7 @@ class BonPrelevement extends CommonObject // Update withdrawal line // TODO: Translate to ligneprelevement.class.php - if (! $error) { + if (!$error) { $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; $sql .= " SET statut = 2"; $sql .= " WHERE fk_prelevement_bons = ".$this->id; @@ -884,7 +883,7 @@ class BonPrelevement extends CommonObject $sql .= " AND f.rowid = pfd.fk_facture_fourn"; } $sql .= " AND s.rowid = f.fk_soc"; - $sql .= " AND f.fk_statut = 1"; // Invoice validated + $sql .= " AND f.fk_statut = 1"; // Invoice validated $sql .= " AND f.paye = 0"; $sql .= " AND pfd.traite = 0"; $sql .= " AND f.total_ttc > 0"; @@ -1179,7 +1178,7 @@ class BonPrelevement extends CommonObject /* * Update total defined after generation of file */ - if (! $error) { + if (!$error) { $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; $sql .= " SET amount = ".price2num($this->total); $sql .= " WHERE rowid = ".$this->id; @@ -1303,7 +1302,7 @@ class BonPrelevement extends CommonObject $result = ''; - $labeltoshow = 'Withdraw'; + $labeltoshow = 'PaymentByDirectDebit'; if ($this->type == 'bank-transfer') { $labeltoshow = 'PaymentByBankTransfer'; } @@ -1381,7 +1380,7 @@ class BonPrelevement extends CommonObject $result = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql .= " WHERE rowid = '".$rowid."'"; + $sql .= " WHERE rowid = ".((int) $rowid); if ($this->db->query($sql)) { @@ -1405,7 +1404,7 @@ class BonPrelevement extends CommonObject $result = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; + $sql .= " WHERE fk_user=".$user." AND fk_action='".$this->db->escape($action)."'"; if ($this->db->query($sql)) { @@ -1434,7 +1433,7 @@ class BonPrelevement extends CommonObject $now = dol_now(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; - $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; + $sql .= " VALUES ('".$this->db->idate($now)."', ".$user.", 'NULL', 'NULL', '".$this->db->escape($action)."')"; dol_syslog("adnotiff: ".$sql); if ($this->db->query($sql)) @@ -1542,7 +1541,7 @@ class BonPrelevement extends CommonObject { $obj = $this->db->fetch_object($resql); - if (! empty($cachearraytotestduplicate[$obj->idfac])) { + if (!empty($cachearraytotestduplicate[$obj->idfac])) { $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid); $this->invoice_in_error[$obj->idfac] = $this->error; $result = -2; @@ -1657,7 +1656,7 @@ class BonPrelevement extends CommonObject { $obj = $this->db->fetch_object($resql); - if (! empty($cachearraytotestduplicate[$obj->idfac])) { + if (!empty($cachearraytotestduplicate[$obj->idfac])) { $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid); $this->invoice_in_error[$obj->idfac] = $this->error; $result = -2; @@ -2192,7 +2191,7 @@ class BonPrelevement extends CommonObject $XML_SEPA_INFO .= ' '.$conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf;*/ - $XML_SEPA_INFO .= ' SLEV'.$CrLf; // Field "Responsible of fees". Must be SLEV + $XML_SEPA_INFO .= ' SLEV'.$CrLf; // Field "Responsible of fees". Must be SLEV $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; @@ -2254,7 +2253,7 @@ class BonPrelevement extends CommonObject $XML_SEPA_INFO .= ' '.$conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf;*/ - $XML_SEPA_INFO .= ' SLEV'.$CrLf; // Field "Responsible of fees". Must be SLEV + $XML_SEPA_INFO .= ' SLEV'.$CrLf; // Field "Responsible of fees". Must be SLEV /*$XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 8599987fb23..20d600bf9b4 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -153,7 +153,6 @@ class RejetPrelevement $pai->amounts[$facs[$i][0]] = price2num($facs[$i][1] * -1); $pai->datepaye = $date_rejet; $pai->paiementid = 3; // type of payment: withdrawal - $pai->num_paiement = $fac->ref; $pai->num_payment = $fac->ref; if ($pai->create($this->user) < 0) // we call with no_commit diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index f8d67de48c2..8c8dc01a22c 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -46,7 +46,7 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); $type = GETPOST('type', 'aZ09'); // Get supervariables -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $mode = GETPOST('mode', 'alpha') ?GETPOST('mode', 'alpha') : 'real'; $format = GETPOST('format', 'aZ09'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -84,10 +84,10 @@ if (empty($reshook)) $conf->global->PAYMENTBYBANKTRANSFER_ADDDAYS; } $bprev = new BonPrelevement($db); - $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), (GETPOST('reday', 'int') + $delayindays), GETPOST('reyear', 'int')); + $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), (GETPOST('reday', 'int') + $delayindays), GETPOST('reyear', 'int')); - // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty (we don't use them anymore) - $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format, $executiondate, 0, $type); + // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty (we don't use them anymore) + $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format, $executiondate, 0, $type); if ($result < 0) { setEventMessages($bprev->error, $bprev->errors, 'errors'); } elseif ($result == 0) { @@ -185,33 +185,33 @@ if ($mesg) print $mesg; print '
'."\n"; print '
'; -print ''; +print ''; print ''; if ($nb) { - if ($pricetowithdraw) { - print $langs->trans('ExecutionDate').' '; - $datere = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - print $form->selectDate($datere, 're'); + if ($pricetowithdraw) { + print $langs->trans('ExecutionDate').' '; + $datere = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + print $form->selectDate($datere, 're'); - if ($mysoc->isInEEC()) { - $title = $langs->trans("CreateForSepa"); - if ($type == 'bank-transfer') { - $title = $langs->trans("CreateSepaFileForPaymentByBankTransfer"); - } + if ($mysoc->isInEEC()) { + $title = $langs->trans("CreateForSepa"); + if ($type == 'bank-transfer') { + $title = $langs->trans("CreateSepaFileForPaymentByBankTransfer"); + } - if ($type != 'bank-transfer') { - print ''; - } - print ''; - } else { - $title = $langs->trans("CreateAll"); - if ($type == 'bank-transfer') { - $title = $langs->trans("CreateFileForPaymentByBankTransfer"); - } - print ''.$title."\n"; + if ($type != 'bank-transfer') { + print ''; + } + print ''; + } else { + $title = $langs->trans("CreateAll"); + if ($type == 'bank-transfer') { + $title = $langs->trans("CreateFileForPaymentByBankTransfer"); + } + print ''.$title."\n"; } } else { if ($mysoc->isInEEC()) @@ -301,12 +301,12 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - $param = ''; + $param = ''; if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($socid) $param .= '&socid='.urlencode($socid); - if ($option) $param .= "&option=".urlencode($option); + if ($option) $param .= "&option=".urlencode($option); - print ''; + print ''; print ''; print ''; if (!empty($limit)) { @@ -317,12 +317,12 @@ if ($resql) if ($type == 'bank-transfer') { $title = $langs->trans("InvoiceWaitingPaymentByBankTransfer"); } - print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, '', '', '', $num, $nbtotalofrecords, 'bill', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, '', '', '', $num, $nbtotalofrecords, 'bill', 0, '', '', $limit); - $tradinvoice = "Invoice"; - if ($type == 'bank-transfer') { - $tradinvoice = "SupplierInvoice"; - } + $tradinvoice = "Invoice"; + if ($type == 'bank-transfer') { + $tradinvoice = "SupplierInvoice"; + } print ''; print ''; diff --git a/htdocs/compta/prelevement/demandes.php b/htdocs/compta/prelevement/demandes.php index 53934deaac1..94c8c0639e1 100644 --- a/htdocs/compta/prelevement/demandes.php +++ b/htdocs/compta/prelevement/demandes.php @@ -40,14 +40,14 @@ $status = GETPOST('status', 'int'); if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'prelevement', '', '', 'bons'); -$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'directdebitcredittransferlist'; // 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') $type = GETPOST('type', 'aZ09'); $search_facture = GETPOST('search_facture', 'alpha'); -$search_societe = trim(GETPOST('search_societe', 'alpha')); +$search_societe = GETPOST('search_societe', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php index fcdb2f01404..4e3d191fdfa 100644 --- a/htdocs/compta/prelevement/factures.php +++ b/htdocs/compta/prelevement/factures.php @@ -45,8 +45,8 @@ $type = GETPOST('type', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -82,11 +82,11 @@ llxHeader('', $langs->trans("WithdrawalsReceipts")); if ($id > 0 || $ref) { if ($object->fetch($id, $ref) >= 0) - { - $head = prelevement_prepare_head($object); + { + $head = prelevement_prepare_head($object); dol_fiche_head($head, 'invoices', $langs->trans("WithdrawalsReceipts"), -1, 'payment'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); @@ -151,9 +151,9 @@ if ($id > 0 || $ref) print ''; dol_fiche_end(); - } else { - dol_print_error($db); - } + } else { + dol_print_error($db); + } } @@ -191,13 +191,13 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; 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 - { - $page = 0; - $offset = 0; - } + $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 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -212,13 +212,13 @@ if ($resql) // Lines of title fields print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -245,38 +245,38 @@ if ($resql) $invoicetmpsupplier = new FactureFournisseur($db); while ($i < min($num, $limit)) - { - $obj = $db->fetch_object($resql); + { + $obj = $db->fetch_object($resql); - if ($obj->type == 'bank-transfer') { - $invoicetmp = $invoicetmpsupplier; - } else { - $invoicetmp = $invoicetmpcustomer; - } - $invoicetmp->fetch($obj->facid); + if ($obj->type == 'bank-transfer') { + $invoicetmp = $invoicetmpsupplier; + } else { + $invoicetmp = $invoicetmpcustomer; + } + $invoicetmp->fetch($obj->facid); - $thirdpartytmp->fetch($obj->socid); + $thirdpartytmp->fetch($obj->socid); - print ''; + print ''; - print "\n"; + print "\n"; - print '\n"; + print '\n"; - // Amount of invoice - print '\n"; + // Amount of invoice + print '\n"; - // Amount requested - print '\n"; + // Amount requested + print '\n"; - // Status of requests - print '"; + print ""; - print ""; + print ""; - print "\n"; + print "\n"; - $totalinvoices += $obj->total_ttc; - $totalamount_requested += $obj->amount_requested; + $totalinvoices += $obj->total_ttc; + $totalamount_requested += $obj->amount_requested; - $i++; - } + $i++; + } if ($num > 0) - { - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print '\n"; - print '\n"; - print ''; - print ''; - print "\n"; - } + print "\n"; + print ''; + print ''; + print "\n"; + } print "
"; - print $invoicetmp->getNomUrl(1); - print ""; + print $invoicetmp->getNomUrl(1); + print "'; - print $thirdpartytmp->getNomUrl(1); - print "'; + print $thirdpartytmp->getNomUrl(1); + print "'.price($obj->total_ttc)."'.price($obj->total_ttc)."'.price($obj->amount_requested)."'.price($obj->amount_requested)."'; + // Status of requests + print ''; - if ($obj->statut == 0) { + if ($obj->statut == 0) { print '-'; } elseif ($obj->statut == 2) { if ($obj->type == 'bank-transfer') { @@ -288,34 +288,34 @@ if ($resql) print ''.$langs->trans("StatusRefused").''; } - print "
'.$langs->trans("Total").' '; + { + print '
'.$langs->trans("Total").' '; //if ($totalinvoices != $object->amount) print img_warning("AmountOfFileDiffersFromSumOfInvoices"); // It is normal to have total that differs. For an amount of invoice of 100, request to pay may be 50 only. - if ($totalamount_requested != $object->amount) print img_warning("AmountOfFileDiffersFromSumOfInvoices"); + if ($totalamount_requested != $object->amount) print img_warning("AmountOfFileDiffersFromSumOfInvoices"); print "'; + print ''; print price($totalamount_requested); - print "  
  
"; print '
'; diff --git a/htdocs/compta/prelevement/fiche-rejet.php b/htdocs/compta/prelevement/fiche-rejet.php index bddebaedda5..7783edd4673 100644 --- a/htdocs/compta/prelevement/fiche-rejet.php +++ b/htdocs/compta/prelevement/fiche-rejet.php @@ -45,8 +45,8 @@ $type = GETPOST('type', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -76,11 +76,11 @@ llxHeader('', $langs->trans("WithdrawalsReceipts")); if ($prev_id > 0 || $ref) { if ($object->fetch($prev_id, $ref) >= 0) - { - $head = prelevement_prepare_head($object); + { + $head = prelevement_prepare_head($object); dol_fiche_head($head, 'rejects', $langs->trans("WithdrawalsReceipts"), -1, 'payment'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); @@ -145,9 +145,9 @@ if ($prev_id > 0 || $ref) print '
'; dol_fiche_end(); - } else { - dol_print_error($db); - } + } else { + dol_print_error($db); + } } @@ -205,44 +205,44 @@ if ($resql) if ($num > 0) { - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); - print ''; + print ''; - print ''; - print img_picto('', 'statut'.$obj->statut).' '; - print substr('000000'.$obj->rowid, -6); - print ''; - print ''.$obj->name."\n"; + print ''; + print img_picto('', 'statut'.$obj->statut).' '; + print substr('000000'.$obj->rowid, -6); + print ''; + print ''.$obj->name."\n"; - print ''.price($obj->amount)."\n"; - print ''.$rej->motifs[$obj->motif].''; + print ''.price($obj->amount)."\n"; + print ''.$rej->motifs[$obj->motif].''; - print ''.yn($obj->afacturer).''; - print ''.$obj->fk_facture.''; - print "\n"; + print ''.yn($obj->afacturer).''; + print ''.$obj->fk_facture.''; + print "\n"; - $total += $obj->amount; + $total += $obj->amount; - $i++; - } + $i++; + } } else { - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; } if ($num > 0) - { - print ' '; - print ''.$langs->trans("Total").''; - print ''.price($total)."\n"; - print ' '; - print "\n"; - } - print "\n"; - print '
'; + { + print ' '; + print ''.$langs->trans("Total").''; + print ''.price($total)."\n"; + print ' '; + print "\n"; + } + print "\n"; + print '
'; $db->free($resql); } else { diff --git a/htdocs/compta/prelevement/fiche-stat.php b/htdocs/compta/prelevement/fiche-stat.php index c59ed2d4232..df5118df0cf 100644 --- a/htdocs/compta/prelevement/fiche-stat.php +++ b/htdocs/compta/prelevement/fiche-stat.php @@ -43,8 +43,8 @@ $type = GETPOST('type', 'aZ09'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -79,7 +79,7 @@ if ($prev_id > 0 || $ref) $head = prelevement_prepare_head($object); dol_fiche_head($head, 'statistics', $langs->trans("WithdrawalsReceipts"), -1, 'payment'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); diff --git a/htdocs/compta/prelevement/index.php b/htdocs/compta/prelevement/index.php index 50546d5bb1d..4104249df5c 100644 --- a/htdocs/compta/prelevement/index.php +++ b/htdocs/compta/prelevement/index.php @@ -181,6 +181,7 @@ $limit = 5; $sql = "SELECT p.rowid, p.ref, p.amount, p.datec, p.statut"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql .= " WHERE p.type = 'debit-order'"; +$sql .= " AND entity IN (" . getEntity('prelevement') . ")"; $sql .= " ORDER BY datec DESC"; $sql .= $db->plimit($limit); diff --git a/htdocs/compta/prelevement/line.php b/htdocs/compta/prelevement/line.php index ae146522f39..3c8d80d4931 100644 --- a/htdocs/compta/prelevement/line.php +++ b/htdocs/compta/prelevement/line.php @@ -39,15 +39,15 @@ $langs->loadlangs(array('banks', 'categories', 'bills', 'withdrawals')); if ($user->socid > 0) accessforbidden(); // Get supervariables -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); $socid = GETPOST('socid', 'int'); $type = GETPOST('type', 'aZ09'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortorder = GETPOST('sortorder', 'alpha'); -$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if ($page == -1 || $page == null) { $page = 0; } $offset = $limit * $page; diff --git a/htdocs/compta/prelevement/list.php b/htdocs/compta/prelevement/list.php index 2666e8587e6..36aa4bb8e5c 100644 --- a/htdocs/compta/prelevement/list.php +++ b/htdocs/compta/prelevement/list.php @@ -38,7 +38,7 @@ $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk $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') : 'myobjectlist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'directdebitcredittransferlinelist'; // 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') @@ -50,8 +50,8 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); $type = GETPOST('type', 'aZ09'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/prelevement/bons.php b/htdocs/compta/prelevement/orders_list.php similarity index 96% rename from htdocs/compta/prelevement/bons.php rename to htdocs/compta/prelevement/orders_list.php index 608c9fe594d..d4f16eab7f6 100644 --- a/htdocs/compta/prelevement/bons.php +++ b/htdocs/compta/prelevement/orders_list.php @@ -19,9 +19,9 @@ */ /** - * \file htdocs/compta/prelevement/bons.php + * \file htdocs/compta/prelevement/orders_list.php * \ingroup prelevement - * \brief Page liste des bons de prelevements + * \brief Page to list direct debit orders or credit transfer orders */ require '../../main.inc.php'; @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories', 'widthdrawals')); -$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'directdebitcredittransferlist'; // To manage different context of search // Security check $socid = GETPOST('socid', 'int'); @@ -41,8 +41,8 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); $type = GETPOST('type', 'aZ09'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php index a8481d25f7a..da2420aed3f 100644 --- a/htdocs/compta/prelevement/rejets.php +++ b/htdocs/compta/prelevement/rejets.php @@ -42,8 +42,8 @@ $type = GETPOST('type', 'aZ09'); // Get supervariables $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortorder = GETPOST('sortorder', 'alpha'); -$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$sortfield = GETPOST('sortfield', '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 $offset = $limit * $page; diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index 8b75ec38fce..63368fa94e8 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -46,8 +46,8 @@ $hookmanager->initHooks(array('recapcomptacard', 'globalcard')); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index bcdfe1f5238..c744bcc90e8 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -706,13 +706,13 @@ if ($id > 0) // Reopen if ($object->paye && $user->rights->tax->charges->creer) { - print ""; + print ''; } // Edit if ($object->paye == 0 && $user->rights->tax->charges->creer) { - print ""; + print ''; } // Emit payment @@ -724,19 +724,19 @@ if ($id > 0) // Classify 'paid' if ($object->paye == 0 && round($resteapayer) <= 0 && $user->rights->tax->charges->creer) { - print ""; + print ''; } // Clone if ($user->rights->tax->charges->creer) { - print ""; + print '"; } // Delete if ($user->rights->tax->charges->supprimer) { - print ""; + print ''; } print "
"; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 52939d6add7..62b02860f08 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -134,9 +134,8 @@ class PaymentSocialContribution extends CommonObject if (isset($this->fk_charge)) $this->fk_charge = (int) $this->fk_charge; 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->note_private)) $this->note_private = trim($this->note_private); 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; @@ -265,9 +264,8 @@ class PaymentSocialContribution extends CommonObject $this->datep = $this->db->jdate($obj->datep); $this->amount = $obj->amount; $this->fk_typepaiement = $obj->fk_typepaiement; - $this->num_paiement = $obj->num_payment; $this->num_payment = $obj->num_payment; - $this->note = $obj->note; + $this->note_private = $obj->note; $this->fk_bank = $obj->fk_bank; $this->fk_user_creat = $obj->fk_user_creat; $this->fk_user_modif = $obj->fk_user_modif; @@ -305,9 +303,8 @@ class PaymentSocialContribution extends CommonObject if (isset($this->fk_charge)) $this->fk_charge = (int) $this->fk_charge; 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->note_private)) $this->note_private = trim($this->note_private); 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; @@ -326,7 +323,7 @@ class PaymentSocialContribution extends CommonObject $sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").","; $sql .= " fk_typepaiement=".(isset($this->fk_typepaiement) ? $this->fk_typepaiement : "null").","; - $sql .= " num_paiement=".(isset($this->num_paiement) ? "'".$this->db->escape($this->num_paiement)."'" : "null").","; + $sql .= " num_paiement=".(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_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; @@ -504,7 +501,7 @@ class PaymentSocialContribution extends CommonObject global $conf; // Clean data - $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); + $this->num_payment = trim($this->num_payment); $error = 0; diff --git a/htdocs/compta/sociales/list.php b/htdocs/compta/sociales/list.php index 40ebcd1cb7c..bd7f6147f2d 100644 --- a/htdocs/compta/sociales/list.php +++ b/htdocs/compta/sociales/list.php @@ -35,7 +35,7 @@ if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/clas // Load translation files required by the page $langs->loadLangs(array('compta', 'banks', 'bills')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -138,8 +138,8 @@ 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 - $sql .= " (cs.periode IS NOT NULL AND date_format(cs.periode, '%Y') = '".$year."') "; - $sql .= "OR (cs.periode IS NULL AND date_format(cs.date_ech, '%Y') = '".$year."')"; + $sql .= " (cs.periode IS NOT NULL AND date_format(cs.periode, '%Y') = '".$db->escape($year)."') "; + $sql .= "OR (cs.periode IS NULL AND date_format(cs.date_ech, '%Y') = '".$db->escape($year)."')"; $sql .= ")"; } if ($filtre) { @@ -220,7 +220,7 @@ if ($resql) print ''; // Type print ''; - $formsocialcontrib->select_type_socialcontrib($search_typeid, 'search_typeid', 1, 0, 0, 'maxwidth100onsmartphone'); + $formsocialcontrib->select_type_socialcontrib($search_typeid, 'search_typeid', 1, 0, 0, 'maxwidth100onsmartphone', 1); print ''; // Ref Project if (!empty($conf->projet->enabled)) print ''; diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index ab2c1dcadb1..fbecc1df335 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -60,6 +60,9 @@ if (GETPOST('subcat', 'alpha') === 'yes') { $selected_type = GETPOST('search_type', 'int'); if ($selected_type == '') $selected_type = -1; +// Hook +$hookmanager->initHooks(array('cabyprodservlist')); + // Date range $year = GETPOST("year"); $month = GETPOST("month"); diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index ab71b147b50..a02d87a8392 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -61,6 +61,9 @@ if ($user->socid > 0) $socid = $user->socid; if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat'); if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); +// Hook +$hookmanager->initHooks(array('casoclist')); + // Date range $year = GETPOST("year", 'int'); $month = GETPOST("month", 'int'); diff --git a/htdocs/compta/stats/supplier_turnover_by_prodserv.php b/htdocs/compta/stats/supplier_turnover_by_prodserv.php index 5911daaba45..83a3cb70a00 100644 --- a/htdocs/compta/stats/supplier_turnover_by_prodserv.php +++ b/htdocs/compta/stats/supplier_turnover_by_prodserv.php @@ -57,6 +57,9 @@ if (GETPOST('subcat', 'alpha') === 'yes') { $selected_type = GETPOST('search_type', 'int'); if ($selected_type == '') $selected_type = -1; +// Hook +$hookmanager->initHooks(array('supplierturnoverbyprodservlist')); + // Date range $year = GETPOST("year"); $month = GETPOST("month"); diff --git a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php index 60d65049800..7a624284cdf 100644 --- a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php +++ b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php @@ -50,6 +50,9 @@ if (GETPOST('subcat', 'alpha') === 'yes') { $subcat = true; } +// Hook +$hookmanager->initHooks(array('supplierturnoverbythirdpartylist')); + // Security check if ($user->socid > 0) $socid = $user->socid; if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat'); diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index 6fa22885dee..010fd112646 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -98,18 +98,18 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) } $object->amount = $amount; $object->label = GETPOST("label", 'alpha'); - $object->note = GETPOST("note", 'none'); + $object->note = GETPOST("note", 'restricthtml'); - if (empty($object->datev)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateValue")), null, 'errors'); - $error++; - } if (empty($object->datep)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment")), null, 'errors'); $error++; } + if (empty($object->datev)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PeriodEndDate")), null, 'errors'); + $error++; + } if (empty($object->type_payment) || $object->type_payment < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentMode")), null, 'errors'); @@ -379,7 +379,7 @@ if ($id) { if (!empty($user->rights->tax->charges->supprimer)) { - print ''; + print ''; } else { print ''; } diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index 3274a3eaebd..5f661609e52 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -384,7 +384,7 @@ class Tva extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; if ($year) { - $sql .= " AND f.datef >= '".$year."-01-01' AND f.datef <= '".$year."-12-31' "; + $sql .= " AND f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; } $result = $this->db->query($sql); @@ -421,7 +421,7 @@ class Tva extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; if ($year) { - $sql .= " WHERE f.datef >= '".$year."-01-01' AND f.datef <= '".$year."-12-31' "; + $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; } $result = $this->db->query($sql); @@ -460,7 +460,7 @@ class Tva extends CommonObject if ($year) { - $sql .= " WHERE f.datev >= '".$year."-01-01' AND f.datev <= '".$year."-12-31' "; + $sql .= " WHERE f.datev >= '".$this->db->escape($year)."-01-01' AND f.datev <= '".$this->db->escape($year)."-12-31' "; } $result = $this->db->query($sql); @@ -499,6 +499,7 @@ class Tva extends CommonObject $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; @@ -583,9 +584,9 @@ class Tva extends CommonObject 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), '', '', $user); + $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, -abs($this->amount), $this->num_payment, '', $user); } else { - $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, abs($this->amount), '', '', $user); + $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 diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index 52466e33d84..a91d637c39d 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -124,6 +124,7 @@ $product_static = new Product($db); $payment_static = new Paiement($db); $paymentfourn_static = new PaiementFourn($db); $paymentexpensereport_static = new PaymentExpenseReport($db); +$user_static = new User($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); @@ -151,7 +152,7 @@ $calcmode = ''; 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').')'; +$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; @@ -216,7 +217,7 @@ $vatsup = $langs->trans("VATPaid"); // VAT Received - +print '
'; print ""; $y = $year_current; @@ -743,14 +744,12 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; } - print '
'; - // Total to pay - print '

'; - print ''; + print ''; + $diff = $x_coll_sum - $x_paye_sum; print ''; - print ''; + print ''; print '\n"; print "\n"; @@ -758,7 +757,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) } print '
'.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').''.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').''.price(price2num($diff, 'MT'))."
'; - +print '
'; llxFooter(); diff --git a/htdocs/compta/tva/document.php b/htdocs/compta/tva/document.php index cb26304cde5..830dfb78d3a 100644 --- a/htdocs/compta/tva/document.php +++ b/htdocs/compta/tva/document.php @@ -106,7 +106,7 @@ if ($object->id) $head = vat_prepare_head($object); - dol_fiche_head($head, 'documents', $langs->trans("VATPayment"), -1, 'bill'); + dol_fiche_head($head, 'documents', $langs->trans("VATPayment"), -1, 'payment'); $morehtmlref = '
'; // Label of social contribution diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index 43db8353c4c..a4fd1293b4d 100644 --- a/htdocs/compta/tva/index.php +++ b/htdocs/compta/tva/index.php @@ -220,12 +220,12 @@ $fsearch .= ''; $description = $fsearch; // Show report header -$name = $langs->trans("ReportByMonth"); +$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'); -$calcmode .= '
('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; +$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"); diff --git a/htdocs/compta/tva/list.php b/htdocs/compta/tva/list.php index 5b09da5305c..82829fca12e 100644 --- a/htdocs/compta/tva/list.php +++ b/htdocs/compta/tva/list.php @@ -146,11 +146,9 @@ if ($result) if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; if ($typeid) $param .= '&typeid='.$typeid; - $newcardbutton = ''; - if ($user->rights->tax->charges->creer) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewVATPayment', ($ltt + 1)), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/tva/card.php?action=create'); - } + $url = DOL_URL_ROOT.'/compta/tva/card.php?action=create'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('NewVATPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); print ''; if ($optioncss != '') print ''; @@ -172,22 +170,18 @@ if ($result) // Date end period print ''; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_dateend_start ? $search_dateend_start : -1, 'search_dateend_start', 0, 0, 1); + print $form->selectDate($search_dateend_start ? $search_dateend_start : -1, 'search_dateend_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_dateend_end ? $search_dateend_end : -1, 'search_dateend_end', 0, 0, 1); + print $form->selectDate($search_dateend_end ? $search_dateend_end : -1, 'search_dateend_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '
'; // Date payment print ''; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_datepayment_start ? $search_datepayment_start : -1, 'search_datepayment_start', 0, 0, 1); + print $form->selectDate($search_datepayment_start ? $search_datepayment_start : -1, 'search_datepayment_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_datepayment_end ? $search_datepayment_end : -1, 'search_datepayment_end', 0, 0, 1); + print $form->selectDate($search_datepayment_end ? $search_datepayment_end : -1, 'search_datepayment_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); print '
'; // Type print ''; diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index abd5fb6841c..8fb4c32bf72 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -152,7 +152,7 @@ $calcmode = ''; 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').')'; +$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; @@ -213,6 +213,7 @@ $vatexpensereport = $langs->trans("VATPaid"); // VAT Received and paid +print '
'; print ''; $y = $year_current; @@ -719,6 +720,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) } print '
'; + print '
'; // Total to pay print '

'; diff --git a/htdocs/conf/conf.php.example b/htdocs/conf/conf.php.example index 32c37301a0e..02cc5bae399 100644 --- a/htdocs/conf/conf.php.example +++ b/htdocs/conf/conf.php.example @@ -219,10 +219,10 @@ $dolibarr_main_authentication='dolibarr'; // 1 = Force redirect to https, until SCRIPT_URI start with https into response // 2 = Force redirect to https, until SERVER["HTTPS"] is 'on' into response // 'https://my.domain.com' = Force redirect to https using this domain name. -// Warning: If you enable this parameter, your web server must be configured to -// respond URL with https protocol. -// According to your web server setup, some values may works and other not. Try -// different values (1,2 or 'https://my.domain.com') if you experience problems. +// Warning: If you enable this parameter, your web server must be configured to respond URL with https protocol. +// According to your web server setup, some values may works and other not. Try different values (1,2 or 'https://my.domain.com') if you experience problems. +// Even if a redirect to HTTPS is forced by the webserver, it is recommanded to set this value to another value than 0, so your session cookies will be +// flagged as secured. // Default value: 0 // Possible values: 0, 1, 2 or 'https://my.domain.com' // Examples: @@ -233,12 +233,12 @@ $dolibarr_main_force_https='0'; // dolibarr_main_prod // When this parameter is defined, all errors messages are not reported. // This feature exists for production usage to avoid to give any information to hackers. -// Default value: 0 +// Default value: 1 // Possible values: 0 or 1 // Examples: -// $dolibarr_main_prod='0'; +// $dolibarr_main_prod='1'; // -$dolibarr_main_prod='0'; +$dolibarr_main_prod='1'; // $dolibarr_main_restrict_os_commands // To restrict commands you can execute by the backup feature, enter allowed command here. @@ -260,8 +260,8 @@ $dolibarr_main_restrict_ip=''; // dolibarr_nocsrfcheck // This parameter can be used to disable CSRF protection. -// This might be required if you access Dolibarr behind a proxy that make -// URL rewriting, to avoid false alarms. +// This might be required if you access Dolibarr behind a proxy that make bad URL rewriting, to avoid false alarms. +// In most cases, you should always keep this to 0. // Default value: 0 // Possible values: 0 or 1 // Examples: @@ -269,6 +269,12 @@ $dolibarr_main_restrict_ip=''; // $dolibarr_nocsrfcheck='0'; +// dolibarr_cron_allow_cli +// If set to 1, you will be able to define some command line in the internale Job scheduler module. +// Default value: '0' +// Examples: '1' +$dolibarr_cron_allow_cli='0'; + // dolibarr_mailing_limit_sendbyweb // Can set a limit for mailing send by web. This overwrite database value. Can be used to restrict on OS level. // Default value: '25' @@ -281,6 +287,18 @@ $dolibarr_nocsrfcheck='0'; // Examples: '-1' (sending by cli is forbidden) // $dolibarr_mailing_limit_sendbycli='0'; +// MAIN_ANTIVIRUS_COMMAND (as a constant) +// Force a value for the antivirus command line tool so setup for admin user interface has no effect. +// Default value: '' +// Example: '/usr/bin/clamdscan'; +// define('MAIN_ANTIVIRUS_COMMAND', '/usr/bin/clamdscan'); + +// MAIN_ANTIVIRUS_PARAM (as a constant) +// Force a value for the antivirus parameters on command line so setup for admin user interface has no effect. +// Default value: '' +// Example: '--fdpass'; +// define('MAIN_ANTIVIRUS_PARAM', '--fdpass'); + //################## // Other diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index 0ea0018632b..23a6042fbf9 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -83,7 +83,7 @@ $search_agenda_label = GETPOST('search_agenda_label'); // Security check if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission +$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'); @@ -240,18 +240,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $permok = $user->rights->agenda->myactions->create; if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { - //$out.='trans("AddAnAction"),'filenew'); - //$out.=""; + 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')); } - - //print '
'; - //print '
'; - $newcardbutton = ''; if (!empty($conf->agenda->enabled)) { diff --git a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php index bd0808aa8b5..43fd48e3ef0 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php @@ -144,7 +144,7 @@ if (empty($user->socid)) { } if ($user->rights->societe->contact->supprimer) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } print '

'; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index eeb51e65442..e4e7ecaf5fb 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -71,14 +71,14 @@ $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); if (!empty($canvas)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; - $objcanvas = new Canvas($db, $action); - $objcanvas->getCanvas('contact', 'contactcard', $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; -$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission +$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')); @@ -102,45 +102,45 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } + // Cancel + 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) - { - // Recuperation contact actuel - $result = $object->fetch($id); + if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) + { + // Recuperation contact actuel + $result = $object->fetch($id); - if ($result > 0) - { - $db->begin(); + if ($result > 0) + { + $db->begin(); - // Creation user - $nuser = new User($db); - $result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha) + // Creation user + $nuser = new User($db); + $result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha) - if ($result > 0) - { - $result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha) - if ($result2) - { - $db->commit(); - } else { - $error = $nuser->error; $errors = $nuser->errors; - $db->rollback(); - } - } else { - $error = $nuser->error; $errors = $nuser->errors; - $db->rollback(); - } - } else { - $error = $object->error; $errors = $object->errors; - } - } + if ($result > 0) + { + $result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha) + if ($result2) + { + $db->commit(); + } else { + $error = $nuser->error; $errors = $nuser->errors; + $db->rollback(); + } + } else { + $error = $nuser->error; $errors = $nuser->errors; + $db->rollback(); + } + } else { + $error = $object->error; $errors = $object->errors; + } + } // Confirmation desactivation @@ -174,50 +174,50 @@ if (empty($reshook)) { $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'); - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->civility_code = GETPOST("civility_code", 'alpha'); - $object->poste = GETPOST("poste", 'alpha'); - $object->address = GETPOST("address", 'alpha'); - $object->zip = GETPOST("zipcode", 'alpha'); - $object->town = GETPOST("town", 'alpha'); - $object->country_id = GETPOST("country_id", 'int'); - $object->state_id = GETPOST("state_id", 'int'); - //$object->jabberid = GETPOST("jabberid", 'alpha'); - //$object->skype = GETPOST("skype", 'alpha'); - //$object->twitter = GETPOST("twitter", 'alpha'); - //$object->facebook = GETPOST("facebook", 'alpha'); - //$object->linkedin = GETPOST("linkedin", 'alpha'); - $object->socialnetworks = array(); - if (!empty($conf->socialnetworks->enabled)) { - foreach ($socialnetworks as $key => $value) { - if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { - $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); - } - } - } - $object->email = GETPOST("email", 'alpha'); - $object->no_email = GETPOST("no_email", "int"); - $object->phone_pro = GETPOST("phone_pro", 'alpha'); - $object->phone_perso = GETPOST("phone_perso", 'alpha'); - $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); - $object->fax = GETPOST("fax", 'alpha'); - $object->priv = GETPOST("priv", 'int'); - $object->note_public = GETPOST("note_public", 'none'); - $object->note_private = GETPOST("note_private", 'none'); - $object->roles = GETPOST("roles", 'array'); + $object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity); + $object->socid = GETPOST("socid", 'int'); + $object->lastname = GETPOST("lastname", 'alpha'); + $object->firstname = GETPOST("firstname", 'alpha'); + $object->civility_code = GETPOST("civility_code", 'alpha'); + $object->poste = GETPOST("poste", 'alpha'); + $object->address = GETPOST("address", 'alpha'); + $object->zip = GETPOST("zipcode", 'alpha'); + $object->town = GETPOST("town", 'alpha'); + $object->country_id = GETPOST("country_id", 'int'); + $object->state_id = GETPOST("state_id", 'int'); + //$object->jabberid = GETPOST("jabberid", 'alpha'); + //$object->skype = GETPOST("skype", 'alpha'); + //$object->twitter = GETPOST("twitter", 'alpha'); + //$object->facebook = GETPOST("facebook", 'alpha'); + //$object->linkedin = GETPOST("linkedin", 'alpha'); + $object->socialnetworks = array(); + if (!empty($conf->socialnetworks->enabled)) { + foreach ($socialnetworks as $key => $value) { + if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { + $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); + } + } + } + $object->email = GETPOST("email", 'alpha'); + $object->no_email = GETPOST("no_email", "int"); + $object->phone_pro = GETPOST("phone_pro", 'alpha'); + $object->phone_perso = GETPOST("phone_perso", 'alpha'); + $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); + $object->fax = GETPOST("fax", 'alpha'); + $object->priv = GETPOST("priv", 'int'); + $object->note_public = GETPOST("note_public", 'restricthtml'); + $object->note_private = GETPOST("note_private", 'restricthtml'); + $object->roles = GETPOST("roles", 'array'); - $object->statut = 1; //Defult status to Actif + $object->statut = 1; //Defult status to Actif - // Note: Correct date should be completed with location to have exact GM time of birth. - $object->birthday = dol_mktime(0, 0, 0, GETPOST("birthdaymonth", 'int'), GETPOST("birthdayday", 'int'), GETPOST("birthdayyear", 'int')); - $object->birthday_alert = GETPOST("birthday_alert", 'alpha'); + // Note: Correct date should be completed with location to have exact GM time of birth. + $object->birthday = dol_mktime(0, 0, 0, GETPOST("birthdaymonth", 'int'), GETPOST("birthdayday", 'int'), GETPOST("birthdayyear", 'int')); + $object->birthday_alert = GETPOST("birthday_alert", 'alpha'); - // Fill array 'array_options' with data from add form + // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { @@ -225,19 +225,19 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST("lastname")) - { - $error++; $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label")); - $action = 'create'; - } + if (!GETPOST("lastname")) + { + $error++; $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label")); + $action = 'create'; + } - if (!$error) - { - $id = $object->create($user); - if ($id <= 0) - { - $error++; $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); - $action = 'create'; + if (!$error) + { + $id = $object->create($user); + if ($id <= 0) + { + $error++; $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); + $action = 'create'; } else { // Categories association $contcats = GETPOST('contcats', 'array'); @@ -259,51 +259,51 @@ if (empty($reshook)) } } } - } + } - if (!$error && $id > 0) - { - $db->commit(); - if (!empty($backtopage)) $url = $backtopage; - else $url = 'card.php?id='.$id; - header("Location: ".$url); - exit; - } else { - $db->rollback(); - } - } + if (!$error && $id > 0) + { + $db->commit(); + if (!empty($backtopage)) $url = $backtopage; + else $url = 'card.php?id='.$id; + header("Location: ".$url); + exit; + } else { + $db->rollback(); + } + } - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) - { - $result = $object->fetch($id); + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) + { + $result = $object->fetch($id); $object->oldcopy = clone $object; - $object->old_lastname = GETPOST("old_lastname"); - $object->old_firstname = GETPOST("old_firstname"); + $object->old_lastname = GETPOST("old_lastname"); + $object->old_firstname = GETPOST("old_firstname"); - $result = $object->delete(); - if ($result > 0) - { - if ($backtopage) - { - header("Location: ".$backtopage); - exit; - } else { - header("Location: ".DOL_URL_ROOT.'/contact/list.php'); - exit; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->delete(); + if ($result > 0) + { + if ($backtopage) + { + header("Location: ".$backtopage); + exit; + } else { + header("Location: ".DOL_URL_ROOT.'/contact/list.php'); + exit; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) - { - if (empty($_POST["lastname"])) - { - $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); - $action = 'edit'; - } + if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) + { + if (empty($_POST["lastname"])) + { + $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); + $action = 'edit'; + } if (!$error) { @@ -312,155 +312,155 @@ 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) - { - $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) - { - dol_mkdir($dir); + $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); + 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) + { + dol_mkdir($dir); - if (@is_dir($dir)) - { - $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); - $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); + 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) - { - $errors[] = "ErrorFailedToSaveFile"; - } else { - $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + if (!$result > 0) + { + $errors[] = "ErrorFailedToSaveFile"; + } else { + $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); - // Create thumbs - $object->addThumbs($newfile); - } - } - } else { - $errors[] = "ErrorBadImageFormat"; - } - } else { - 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 - $errors[] = "ErrorFilePartiallyUploaded"; - break; - } - } + // Create thumbs + $object->addThumbs($newfile); + } + } + } else { + $errors[] = "ErrorBadImageFormat"; + } + } else { + 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 + $errors[] = "ErrorFilePartiallyUploaded"; + break; + } + } $object->oldcopy = clone $object; $object->old_lastname = GETPOST("old_lastname", 'alpha'); $object->old_firstname = GETPOST("old_firstname", 'alpha'); - $object->socid = GETPOST("socid", 'int'); - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->civility_code = GETPOST("civility_code", 'alpha'); - $object->poste = GETPOST("poste", 'alpha'); + $object->socid = GETPOST("socid", 'int'); + $object->lastname = GETPOST("lastname", 'alpha'); + $object->firstname = GETPOST("firstname", 'alpha'); + $object->civility_code = GETPOST("civility_code", 'alpha'); + $object->poste = GETPOST("poste", 'alpha'); - $object->address = GETPOST("address", 'alpha'); - $object->zip = GETPOST("zipcode", 'alpha'); - $object->town = GETPOST("town", 'alpha'); - $object->state_id = GETPOST("state_id", 'int'); - $object->country_id = GETPOST("country_id", 'int'); + $object->address = GETPOST("address", 'alpha'); + $object->zip = GETPOST("zipcode", 'alpha'); + $object->town = GETPOST("town", 'alpha'); + $object->state_id = GETPOST("state_id", 'int'); + $object->country_id = GETPOST("country_id", 'int'); - $object->email = GETPOST("email", 'alpha'); - $object->no_email = GETPOST("no_email", "int"); - //$object->jabberid = GETPOST("jabberid", 'alpha'); - //$object->skype = GETPOST("skype", 'alpha'); - //$object->twitter = GETPOST("twitter", 'alpha'); - //$object->facebook = GETPOST("facebook", 'alpha'); - //$object->linkedin = GETPOST("linkedin", 'alpha'); + $object->email = GETPOST("email", 'alpha'); + $object->no_email = GETPOST("no_email", "int"); + //$object->jabberid = GETPOST("jabberid", 'alpha'); + //$object->skype = GETPOST("skype", 'alpha'); + //$object->twitter = GETPOST("twitter", 'alpha'); + //$object->facebook = GETPOST("facebook", 'alpha'); + //$object->linkedin = GETPOST("linkedin", 'alpha'); $object->socialnetworks = array(); - if (!empty($conf->socialnetworks->enabled)) { - foreach ($socialnetworks as $key => $value) { - if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { - $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); - } - } - } - $object->phone_pro = GETPOST("phone_pro", 'alpha'); - $object->phone_perso = GETPOST("phone_perso", 'alpha'); - $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); - $object->fax = GETPOST("fax", 'alpha'); - $object->priv = GETPOST("priv", 'int'); - $object->note_public = GETPOST("note_public", 'none'); - $object->note_private = GETPOST("note_private", 'none'); - $object->roles = GETPOST("roles", 'array'); + if (!empty($conf->socialnetworks->enabled)) { + foreach ($socialnetworks as $key => $value) { + if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { + $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); + } + } + } + $object->phone_pro = GETPOST("phone_pro", 'alpha'); + $object->phone_perso = GETPOST("phone_perso", 'alpha'); + $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); + $object->fax = GETPOST("fax", 'alpha'); + $object->priv = GETPOST("priv", 'int'); + $object->note_public = GETPOST("note_public", 'restricthtml'); + $object->note_private = GETPOST("note_private", 'restricthtml'); + $object->roles = GETPOST("roles", 'array'); - // Fill array 'array_options' with data from add form + // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; if (!$error) { - $result = $object->update($contactid, $user); + $result = $object->update($contactid, $user); - if ($result > 0) { - // Categories association - $categories = GETPOST('contcats', 'array'); - $object->setCategories($categories); + if ($result > 0) { + // Categories association + $categories = GETPOST('contcats', 'array'); + $object->setCategories($categories); - $no_email = GETPOST('no_email', 'int'); + $no_email = GETPOST('no_email', 'int'); - // Update mass emailing flag into table mailing_unsubscribe - if (GETPOSTISSET('no_email') && $object->email) - { - if ($no_email) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$db->escape($object->email)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - if (empty($noemail)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$db->escape($object->email)."', ".$db->escape(getEntity('mailing', 0)).", '".$db->idate(dol_now())."')"; - $resql = $db->query($sql); - } - } - } else { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$db->escape($object->email)."' AND entity = ".$db->escape(getEntity('mailing', 0)); - $resql = $db->query($sql); - } + // Update mass emailing flag into table mailing_unsubscribe + if (GETPOSTISSET('no_email') && $object->email) + { + if ($no_email) + { + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$db->escape($object->email)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $noemail = $obj->nb; + if (empty($noemail)) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$db->escape($object->email)."', ".$db->escape(getEntity('mailing', 0)).", '".$db->idate(dol_now())."')"; + $resql = $db->query($sql); + } + } + } else { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$db->escape($object->email)."' AND entity = ".$db->escape(getEntity('mailing', 0)); + $resql = $db->query($sql); + } - $object->no_email = $no_email; - } + $object->no_email = $no_email; + } - $object->old_lastname = ''; - $object->old_firstname = ''; - $action = 'view'; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'edit'; - } + $object->old_lastname = ''; + $object->old_firstname = ''; + $action = 'view'; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'edit'; + } } - } + } - 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); @@ -476,7 +476,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - // Actions to send emails + // Actions to send emails $triggersendname = 'CONTACT_SENTBYMAIL'; $paramname = 'id'; $mode = 'emailfromcontact'; @@ -501,87 +501,87 @@ $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans(" if ($socid > 0) { - $objsoc = new Societe($db); - $objsoc->fetch($socid); + $objsoc = new Societe($db); + $objsoc->fetch($socid); } if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { - // ----------------------------------------- - // When used with CANVAS - // ----------------------------------------- - if (empty($object->error) && $id) + // ----------------------------------------- + // 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 - $objcanvas->display_canvas($action); // Show template + $objcanvas->display_canvas($action); // Show template } else { - // ----------------------------------------- - // When used in standard mode - // ----------------------------------------- + // ----------------------------------------- + // When used in standard mode + // ----------------------------------------- - // Confirm deleting contact - 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); - } - } + // Confirm deleting contact + 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 */ - $head = array(); - if ($id > 0) - { - // Si edition contact deja existant - $object = new Contact($db); - $res = $object->fetch($id, $user); - if ($res < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $head = array(); + if ($id > 0) + { + // Si edition contact deja existant + $object = new Contact($db); + $res = $object->fetch($id, $user); + if ($res < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - $object->fetchRoles(); + $object->fetchRoles(); - // Show tabs - $head = contact_prepare_head($object); + // Show tabs + $head = contact_prepare_head($object); - $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); - } + $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 */ - $object->canvas = $canvas; + $object->canvas = $canvas; - $object->state_id = GETPOST("state_id"); + $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) - { - $tmparray = getCountry($object->country_id, 'all'); - $object->country_code = $tmparray['code']; - $object->country = $tmparray['label']; - } + // 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) + { + $tmparray = getCountry($object->country_id, 'all'); + $object->country_code = $tmparray['code']; + $object->country = $tmparray['label']; + } - $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - $linkback = ''; - print load_fiche_titre($title, $linkback, 'address'); + $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + $linkback = ''; + print load_fiche_titre($title, $linkback, 'address'); - // Show errors - dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); + // Show errors + dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) + { print "\n".''."\n"; - } + } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; if (!empty($objsoc)) { print ''; - } + } - dol_fiche_head($head, 'card', '', 0, ''); + dol_fiche_head($head, 'card', '', 0, ''); - print ''; + print '
'; - // Name - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; - print ''; - - // Company - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($socid > 0) - { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - } - } - - // Civility - print ''; - - print ''; - print ''; - - $colspan = 3; - if ($conf->use_javascript_ajax && $socid > 0) $colspan = 2; - - // Address - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->address)) == 0) $object->address = $objsoc->address; // Predefined with third party - print ''; - print ''; - - if ($conf->use_javascript_ajax && $socid > 0) - { - $rowspan = 3; - if (empty($conf->global->SOCIETE_DISABLE_STATE)) $rowspan++; - - print ''; - } - print ''; - - // Zip / Town - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->zip)) == 0) $object->zip = $objsoc->zip; // Predefined with third party - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->town)) == 0) $object->town = $objsoc->town; // Predefined with third party - print ''; - - // Country - print ''; - - // 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)) - { - print ''; - } - - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->phone_pro)) == 0) $object->phone_pro = $objsoc->phone; // Predefined with third party - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->fax)) == 0) $object->fax = $objsoc->fax; // Predefined with third party - - // Phone / Fax - print ''; - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; - print ''; - - print ''; - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; - print ''; - print ''; - - if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->email)) == 0) $object->email = $objsoc->email; // Predefined with third party - - // Email - print ''; - print ''; + // Name + print ''; + print ''; print ''; - if (!empty($conf->mailing->enabled)) - { - $noemail = ''; - if (empty($noemail) && !empty($object->email)) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - } - } + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; - } - print ''; + // Company + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + if ($socid > 0) + { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + } + } - if (!empty($conf->socialnetworks->enabled)) { - foreach ($socialnetworks as $key => $value) { - if ($value['active']) { - print ''; - print ''; - print ''; - print ''; - } elseif (!empty($object->socialnetworks[$key])) { - print ''; - } - } - } - // if (! empty($conf->socialnetworks->enabled)) - // { - // // Jabber - // if (! empty($conf->global->SOCIALNETWORKS_JABBER)) - // { - // print ''; - // print ''; - // } - // // Skype - // if (! empty($conf->global->SOCIALNETWORKS_SKYPE)) - // { - // print ''; - // print ''; - // } - // // Twitter - // if (! empty($conf->global->SOCIALNETWORKS_TWITTER)) - // { - // print ''; - // print ''; - // } - // // Facebook - // if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK)) - // { - // print ''; - // print ''; - // } - // // LinkedIn - // if (! empty($conf->global->SOCIALNETWORKS_LINKEDIN)) - // { - // print ''; - // print ''; - // } - // } + // Civility + print ''; - // Visibility - print ''; + print ''; + print ''; + + $colspan = 3; + if ($conf->use_javascript_ajax && $socid > 0) $colspan = 2; + + // Address + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->address)) == 0) $object->address = $objsoc->address; // Predefined with third party + print ''; + print ''; + + if ($conf->use_javascript_ajax && $socid > 0) + { + $rowspan = 3; + if (empty($conf->global->SOCIETE_DISABLE_STATE)) $rowspan++; + + print ''; + } + print ''; + + // Zip / Town + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->zip)) == 0) $object->zip = $objsoc->zip; // Predefined with third party + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->town)) == 0) $object->town = $objsoc->town; // Predefined with third party + print ''; + + // Country + print ''; + + // 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)) + { + print ''; + } + + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->phone_pro)) == 0) $object->phone_pro = $objsoc->phone; // Predefined with third party + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->fax)) == 0) $object->fax = $objsoc->fax; // Predefined with third party + + // Phone / Fax + print ''; + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; + print ''; + + print ''; + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; + print ''; + print ''; + + if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->email)) == 0) $object->email = $objsoc->email; // Predefined with third party + + // Email + print ''; + print ''; + print ''; + + if (!empty($conf->mailing->enabled)) + { + $noemail = ''; + if (empty($noemail) && !empty($object->email)) + { + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $noemail = $obj->nb; + } + } + + print ''; + print ''; + print ''; + print ''; + } + print ''; + + if (!empty($conf->socialnetworks->enabled)) { + foreach ($socialnetworks as $key => $value) { + if ($value['active']) { + print ''; + print ''; + print ''; + print ''; + } elseif (!empty($object->socialnetworks[$key])) { + print ''; + } + } + } + // if (! empty($conf->socialnetworks->enabled)) + // { + // // Jabber + // if (! empty($conf->global->SOCIALNETWORKS_JABBER)) + // { + // print ''; + // print ''; + // } + // // Skype + // if (! empty($conf->global->SOCIALNETWORKS_SKYPE)) + // { + // print ''; + // print ''; + // } + // // Twitter + // if (! empty($conf->global->SOCIALNETWORKS_TWITTER)) + // { + // print ''; + // print ''; + // } + // // Facebook + // if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK)) + // { + // print ''; + // print ''; + // } + // // LinkedIn + // if (! empty($conf->global->SOCIALNETWORKS_LINKEDIN)) + // { + // print ''; + // print ''; + // } + // } + + // Visibility + print ''; // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { @@ -823,84 +823,84 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ""; } - // Contact by default - if (!empty($socid)) { - print ''; - print ''; - } + // Contact by default + if (!empty($socid)) { + print ''; + print ''; + } - // Other attributes - $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)) - { - print $object->showOptionals($extrafields, 'edit', $parameters); - } + // Other attributes + $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)) + { + print $object->showOptionals($extrafields, 'edit', $parameters); + } - print "
lastname).'" autofocus="autofocus">
firstname).'">
'; - print $objsoc->getNomUrl(1, 'contact'); - print '
'; - print $form->select_company($socid, 'socid', '', 'SelectThirdParty'); - print '
'; - print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", 'alpha') : $object->civility_code, 'civility_code'); - print '
poste).'">
'; - print ''.$langs->trans('CopyAddressFromSoc').''; - print '
/ '; - print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha') ? GETPOST("zipcode", 'alpha') : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; - print $formcompany->select_ziptown((GETPOST("town", 'alpha') ? GETPOST("town", 'alpha') : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); - print '
'; - print img_picto('', 'globe-americas', 'class="paddingrightonly"'); - print $form->select_country((GETPOST("country_id", 'alpha') ? GETPOST("country_id", 'alpha') : $object->country_id), 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
'; - } else { - print '
'; - } - - if ($object->country_id) - { - print $formcompany->select_state(GETPOST("state_id", 'alpha') ? GETPOST("state_id", 'alpha') : $object->state_id, $object->country_code, 'state_id'); - } else { - print $countrynotdefined; - } - print '
'.$form->editfieldkey('PhonePro', 'phone_pro', '', $object, 0).''; - print img_picto('', 'object_phoning'); - print '
'.$form->editfieldkey('PhonePerso', 'phone_perso', '', $object, 0).''; - print img_picto('', 'object_phoning'); - print '
'.$form->editfieldkey('PhoneMobile', 'phone_mobile', '', $object, 0).''; - print img_picto('', 'object_phoning_mobile'); - print '
'.$form->editfieldkey('Fax', 'fax', '', $object, 0).''; - print img_picto('', 'object_phoning_fax'); - print '
'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '').''; - print img_picto('', 'object_email'); - print '
lastname).'" autofocus="autofocus">
firstname).'">
'.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'alpha') : $noemail), 1).'
'; + print $objsoc->getNomUrl(1, 'contact'); + print '
'; + print $form->select_company($socid, 'socid', '', 'SelectThirdParty'); + print '
'; - print ''; - print '
jabberid).'">
skype).'">
twitter).'">
facebook).'">
linkedin).'">
'; + print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", 'alpha') : $object->civility_code, 'civility_code'); + print '
'; - $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); - print $form->selectarray('priv', $selectarray, (GETPOST("priv", 'alpha') ?GETPOST("priv", 'alpha') : $object->priv), 0); - print '
poste).'">
'; + print ''.$langs->trans('CopyAddressFromSoc').''; + print '
/ '; + print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha') ? GETPOST("zipcode", 'alpha') : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; + print $formcompany->select_ziptown((GETPOST("town", 'alpha') ? GETPOST("town", 'alpha') : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); + print '
'; + print img_picto('', 'globe-americas', 'class="paddingrightonly"'); + print $form->select_country((GETPOST("country_id", 'alpha') ? GETPOST("country_id", 'alpha') : $object->country_id), 'country_id'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print '
'; + } else { + print '
'; + } + + if ($object->country_id) + { + print $formcompany->select_state(GETPOST("state_id", 'alpha') ? GETPOST("state_id", 'alpha') : $object->state_id, $object->country_code, 'state_id'); + } else { + print $countrynotdefined; + } + print '
'.$form->editfieldkey('PhonePro', 'phone_pro', '', $object, 0).''; + print img_picto('', 'object_phoning'); + print '
'.$form->editfieldkey('PhonePerso', 'phone_perso', '', $object, 0).''; + print img_picto('', 'object_phoning'); + print '
'.$form->editfieldkey('PhoneMobile', 'phone_mobile', '', $object, 0).''; + print img_picto('', 'object_phoning_mobile'); + print '
'.$form->editfieldkey('Fax', 'fax', '', $object, 0).''; + print img_picto('', 'object_phoning_fax'); + print '
'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '').''; + print img_picto('', 'object_email'); + print '
'.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'alpha') : $noemail), 1).'
'; + print ''; + print '
jabberid).'">
skype).'">
twitter).'">
facebook).'">
linkedin).'">
'; + $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); + print $form->selectarray('priv', $selectarray, (GETPOST("priv", 'alpha') ?GETPOST("priv", 'alpha') : $object->priv), 0); + print '
'.$langs->trans("ContactByDefaultFor").''; - $contactType = $object->listeTypeContacts('external', '', 1); - print $form->multiselectarray('roles', $contactType); - print '
'.$langs->trans("ContactByDefaultFor").''; + $contactType = $object->listeTypeContacts('external', '', 1); + print $form->multiselectarray('roles', $contactType); + print '

"; + print "
"; print '
'; - // Add personnal information - print load_fiche_titre('
'.$langs->trans("PersonalInformations").'
', '', ''); + // Add personnal information + print load_fiche_titre('
'.$langs->trans("PersonalInformations").'
', '', ''); - print ''; + print '
'; - // Date To Birth - print ''; + // Date To Birth + print ''; - print ''; - print ''; + print ''; + print ''; - print "
'; - $form = new Form($db); - 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); - } - print '
'; + $form = new Form($db); + 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); + } + print ': '; - if ($object->birthday_alert) - { - print ''; - } else { - print ''; - } - print '
: '; + if ($object->birthday_alert) + { + print ''; + } else { + print ''; + } + print '
"; + print ""; - dol_fiche_end(); + dol_fiche_end(); - print '
'; - print ''; - if (!empty($backtopage)) - { - print '     '; - print ''; - } else { - print '     '; - print ''; - } - print '
'; + print '
'; + print ''; + if (!empty($backtopage)) + { + print '     '; + print ''; + } else { + print '     '; + print ''; + } + print '
'; - print ""; - } elseif ($action == 'edit' && !empty($id)) - { - /* + print ""; + } elseif ($action == 'edit' && !empty($id)) + { + /* * Fiche en mode edition */ - // We set country_id, and country_code label of the chosen country - if (isset($_POST["country_id"]) || $object->country_id) - { - $tmparray = getCountry($object->country_id, 'all'); - $object->country_code = $tmparray['code']; - $object->country = $tmparray['label']; - } + // We set country_id, and country_code label of the chosen country + if (isset($_POST["country_id"]) || $object->country_id) + { + $tmparray = getCountry($object->country_id, 'all'); + $object->country_code = $tmparray['code']; + $object->country = $tmparray['label']; + } $objsoc = new Societe($db); $objsoc->fetch($object->socid); @@ -908,8 +908,8 @@ 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"; - } + } - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($backtopage)) print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (!empty($backtopage)) print ''; - dol_fiche_head($head, 'card', $title, 0, 'contact'); + dol_fiche_head($head, 'card', $title, 0, 'contact'); - print ''; + print '
'; - // Ref/ID - if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) - { - print ''; - } + // Ref/ID + if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) + { + print ''; + } - // Lastname - print ''; - print ''; - print ''; - print ''; - // Firstname - print ''; - print ''; - print ''; + // Lastname + print ''; + print ''; + print ''; + print ''; + // Firstname + print ''; + print ''; + print ''; - // Company - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - print ''; - print ''; - print ''; - } + // Company + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + print ''; + print ''; + print ''; + } - // Civility - print ''; + // Civility + print ''; - print ''; - print ''; + print ''; + print ''; - // Address - print ''; - print ''; + // Address + print ''; + print ''; - // Zip / Town - print ''; + // Zip / Town + print ''; - // Country - print ''; + // Country + print ''; - // 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)) - { - print ''; - } + print $formcompany->select_state(GETPOSTISSET('state_id') ? GETPOST('state_id', 'alpha') : $object->state_id, $object->country_code, 'state_id'); + print ''; + } - // Phone - print ''; - print ''; - print ''; - print ''; + // Phone + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - // EMail - print ''; - print ''; - if (!empty($conf->mailing->enabled)) - { - $langs->load("mails"); - print ''; - print ''; - } else { - print ''; - } - print ''; - - // Unsubscribe - print ''; - if (!empty($conf->mailing->enabled)) - { - $noemail = ''; - if (empty($noemail) && !empty($object->email)) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - } - } - - print ''; - print ''; - } else { + // EMail + print ''; + print ''; + if (!empty($conf->mailing->enabled)) + { + $langs->load("mails"); + print ''; + print ''; + } else { print ''; } - print ''; + print ''; - if (!empty($conf->socialnetworks->enabled)) { - foreach ($socialnetworks as $key => $value) { - if ($value['active']) { - print ''; - print ''; - print ''; - print ''; - } elseif (!empty($object->socialnetworks[$key])) { - print ''; - } - } - } - // if (! empty($conf->socialnetworks->enabled)) - // { - // // Jabber ID - // if (! empty($conf->global->SOCIALNETWORKS_JABBER)) - // { - // print ''; - // print ''; - // } - // // Skype - // if (! empty($conf->global->SOCIALNETWORKS_SKYPE)) - // { - // print ''; - // print ''; - // } - // // Twitter - // if (! empty($conf->global->SOCIALNETWORKS_TWITTER)) - // { - // print ''; - // print ''; - // } - // // Facebook - // if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK)) - // { - // print ''; - // print ''; - // } - // // LinkedIn - // if (! empty($conf->global->SOCIALNETWORKS_LINKEDIN)) - // { - // print ''; - // print ''; - // } - // } + // Unsubscribe + print ''; + if (!empty($conf->mailing->enabled)) + { + $noemail = ''; + if (empty($noemail) && !empty($object->email)) + { + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $noemail = $obj->nb; + } + } - // Visibility - print ''; + print ''; + print ''; + } else { + print ''; + } + print ''; - // Note Public - print ''; + if (!empty($conf->socialnetworks->enabled)) { + foreach ($socialnetworks as $key => $value) { + if ($value['active']) { + print ''; + print ''; + print ''; + print ''; + } elseif (!empty($object->socialnetworks[$key])) { + print ''; + } + } + } + // if (! empty($conf->socialnetworks->enabled)) + // { + // // Jabber ID + // if (! empty($conf->global->SOCIALNETWORKS_JABBER)) + // { + // print ''; + // print ''; + // } + // // Skype + // if (! empty($conf->global->SOCIALNETWORKS_SKYPE)) + // { + // print ''; + // print ''; + // } + // // Twitter + // if (! empty($conf->global->SOCIALNETWORKS_TWITTER)) + // { + // print ''; + // print ''; + // } + // // Facebook + // if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK)) + // { + // print ''; + // print ''; + // } + // // LinkedIn + // if (! empty($conf->global->SOCIALNETWORKS_LINKEDIN)) + // { + // print ''; + // print ''; + // } + // } - // Note Private - print ''; + // Visibility + print ''; - // Status - print ''; - print ''; + // Note Public + print ''; + + // Note Private + print ''; + + // Status + print ''; + print ''; // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { @@ -1162,200 +1162,205 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } // Contact by default - if (!empty($object->socid)) { - print ''; - print ''; - } + if (!empty($object->socid)) { + print ''; + print ''; + } - // Other attributes - $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)) - { - print $object->showOptionals($extrafields, 'edit', $parameters); - } + // Other attributes + $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)) + { + print $object->showOptionals($extrafields, 'edit', $parameters); + } - $object->load_ref_elements(); + $object->load_ref_elements(); - if (!empty($conf->commande->enabled)) - { - print ''; - } + if (!empty($conf->commande->enabled)) + { + print ''; + } - if (!empty($conf->propal->enabled)) - { - print ''; - } + if (!empty($conf->propal->enabled)) + { + print ''; + } - if (!empty($conf->contrat->enabled)) - { - print ''; - } + if (!empty($conf->contrat->enabled)) + { + print ''; + } - if (!empty($conf->facture->enabled)) - { - print ''; - } + if (!empty($conf->facture->enabled)) + { + print ''; + } - // Login Dolibarr - print ''; + // Login Dolibarr + print ''; - // Photo - print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print ''; + print ''; - print '
'.$langs->trans("ID").''; - print $object->ref; - print '
'.$langs->trans("ID").''; + print $object->ref; + print '
lastname).'" autofocus="autofocus">
firstname).'">
lastname).'" autofocus="autofocus">
firstname).'">
'; - print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : ($object->socid ? $object->socid : -1), 'socid', '', $langs->trans("SelectThirdParty")); - print '
'; + print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : ($object->socid ? $object->socid : -1), 'socid', '', $langs->trans("SelectThirdParty")); + print '
'; - print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", "aZ09") : $object->civility_code, 'civility_code'); - print '
'; + print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", "aZ09") : $object->civility_code, 'civility_code'); + print '
poste).'">
poste).'">
'; - print '
'; - print ''; - print '
'; - if ($conf->use_javascript_ajax) print ''.$langs->trans('CopyAddressFromSoc').'
'; - print '
'; - print '
'; + print '
'; + print ''; + print '
'; + if ($conf->use_javascript_ajax) print ''.$langs->trans('CopyAddressFromSoc').'
'; + print '
'; + print '
/ '; - print $formcompany->select_ziptown((GETPOSTISSET("zipcode") ? GETPOST("zipcode") : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; - print $formcompany->select_ziptown((GETPOSTISSET("town") ? GETPOST("town") : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); - print '
/ '; + print $formcompany->select_ziptown((GETPOSTISSET("zipcode") ? GETPOST("zipcode") : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; + print $formcompany->select_ziptown((GETPOSTISSET("town") ? GETPOST("town") : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); + print '
'; - print img_picto('', 'globe-americas', 'class="paddingrightonly"'); - print $form->select_country(GETPOSTISSET("country_id") ? GETPOST("country_id") : $object->country_id, 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
'; + print img_picto('', 'globe-americas', 'class="paddingrightonly"'); + print $form->select_country(GETPOSTISSET("country_id") ? GETPOST("country_id") : $object->country_id, 'country_id'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print '
'; - } else { - print '
'; - } + // 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)) + { + print '
'; + } else { + print '
'; + } - print $formcompany->select_state(GETPOSTISSET('state_id') ? GETPOST('state_id', 'alpha') : $object->state_id, $object->country_code, 'state_id'); - print '
'.$form->editfieldkey('PhonePro', 'phone_pro', GETPOST('phone_pro', 'alpha'), $object, 0).''; - print img_picto('', 'object_phoning'); - print ''.$form->editfieldkey('PhonePerso', 'fax', GETPOST('phone_perso', 'alpha'), $object, 0).''; - print img_picto('', 'object_phoning'); - print '
'.$form->editfieldkey('PhonePro', 'phone_pro', GETPOST('phone_pro', 'alpha'), $object, 0).''; + print img_picto('', 'object_phoning'); + print ''.$form->editfieldkey('PhonePerso', 'fax', GETPOST('phone_perso', 'alpha'), $object, 0).''; + print img_picto('', 'object_phoning'); + print '
'.$form->editfieldkey('PhoneMobile', 'phone_mobile', GETPOST('phone_mobile', 'alpha'), $object, 0, 'string', '').''; - print img_picto('', 'object_phoning_mobile'); - print ''.$form->editfieldkey('Fax', 'fax', GETPOST('fax', 'alpha'), $object, 0).''; - print img_picto('', 'object_phoning_fax'); - print '
'.$form->editfieldkey('PhoneMobile', 'phone_mobile', GETPOST('phone_mobile', 'alpha'), $object, 0, 'string', '').''; + print img_picto('', 'object_phoning_mobile'); + print ''.$form->editfieldkey('Fax', 'fax', GETPOST('fax', 'alpha'), $object, 0).''; + print img_picto('', 'object_phoning_fax'); + print '
'.$form->editfieldkey('EMail', 'email', GETPOST('email', 'alpha'), $object, 0, 'string', '', (!empty($conf->global->SOCIETE_EMAIL_MANDATORY))).''; - print img_picto('', 'object_email'); - print ''.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().'
'.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ?GETPOST("no_email", 'alpha') : $noemail), 1).'
'.$form->editfieldkey('EMail', 'email', GETPOST('email', 'alpha'), $object, 0, 'string', '', (!empty($conf->global->SOCIETE_EMAIL_MANDATORY))).''; + print img_picto('', 'object_email'); + print ''.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().'
'; - print ''; - print '
jabberid).'">
skype).'">
twitter).'">
facebook).'">
linkedin).'">
'; - $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); - print $form->selectarray('priv', $selectarray, $object->priv, 0); - print '
'.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ?GETPOST("no_email", 'alpha') : $noemail), 1).'
'; - $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
'; + print ''; + print '
jabberid).'">
skype).'">
twitter).'">
facebook).'">
linkedin).'">
'; - $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
'; + $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); + print $form->selectarray('priv', $selectarray, $object->priv, 0); + print '
'.$langs->trans("Status").''; - print $object->getLibStatut(4); - print '
'; + $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
'; + $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
'.$langs->trans("Status").''; + print $object->getLibStatut(4); + print '
'.$langs->trans("ContactByDefaultFor").''; - print $formcompany->showRoles("roles", $object, 'edit', $object->roles); - print '
'.$langs->trans("ContactByDefaultFor").''; + print $formcompany->showRoles("roles", $object, 'edit', $object->roles); + print '
'.$langs->trans("ContactForOrders").''; - print $object->ref_commande ? $object->ref_commande : $langs->trans("NoContactForAnyOrder"); - 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("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("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("ContactForInvoices").''; + print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); + print '
'.$langs->trans("DolibarrLogin").''; - 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"); - print '
'.$langs->trans("DolibarrLogin").''; + 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"); + print '
'.$langs->trans("PhotoFile").''; - if ($object->photo) { - print $form->showphoto('contact', $object); - print "
\n"; - } - print ''; - if ($object->photo) print ''; - //print ''; - print ''; - print '
'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; + // Photo + print '
'.$langs->trans("PhotoFile").''; + if ($object->photo) { + print $form->showphoto('contact', $object); + print "
\n"; + } + print ''; + if ($object->photo) print ''; + //print ''; + print ''; + print '
'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; - print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; - print ''; - print '     '; - print ''; - print '
'; + print '
'; + print ''; + print '     '; + print ''; + print '
'; - print "
"; - } + print ""; + } + } + + // Select mail models is same action as presend + if (GETPOST('modelselected', 'alpha')) { + $action = 'presend'; } if (!empty($id) && $action != 'edit' && $action != 'create') { $objsoc = new Societe($db); - // View mode + // View mode - // Show errors - dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); + // Show errors + dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - dol_fiche_head($head, 'card', $title, -1, 'contact'); + dol_fiche_head($head, 'card', $title, -1, 'contact'); - 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); + 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 ? - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $generated_password = getRandomPassword(false); - } - $password = $generated_password; + $generated_password = ''; + if (!$ldap_sid) // TODO ldap_sid ? + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $generated_password = getRandomPassword(false); + } + $password = $generated_password; - // Create a form array - $formquestion = array( - array('label' => $langs->trans("LoginToCreate"), 'type' => 'text', 'name' => 'login', 'value' => $login), - array('label' => $langs->trans("Password"), 'type' => 'text', 'name' => 'password', 'value' => $password), - //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"); - } - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes'); - } + // Create a form array + $formquestion = array( + array('label' => $langs->trans("LoginToCreate"), 'type' => 'text', 'name' => 'login', 'value' => $login), + array('label' => $langs->trans("Password"), 'type' => 'text', 'name' => 'password', 'value' => $password), + //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"); + } + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes'); + } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
'; - 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"); - } - $morehtmlref .= '
'; + $morehtmlref = '
'; + 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"); + } + $morehtmlref .= '
'; - dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - print '
'; - print '
'; + print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; - // Civility - print ''; + // Civility + print ''; - // Job / position - print ''; + // Job / position + print ''; - // Email - if (!empty($conf->mailing->enabled)) - { - $langs->load("mails"); - print ''; - print ''; - } + // Email + if (!empty($conf->mailing->enabled)) + { + $langs->load("mails"); + print ''; + print ''; + } - // Unsubscribe opt-out - if (!empty($conf->mailing->enabled)) - { - //print 'eee'.$object->email; - $noemail = $object->no_email; - if (empty($noemail) && !empty($object->email)) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - } - } - print ''; - } + // Unsubscribe opt-out + if (!empty($conf->mailing->enabled)) + { + //print 'eee'.$object->email; + $noemail = $object->no_email; + if (empty($noemail) && !empty($object->email)) + { + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $noemail = $obj->nb; + } + } + print ''; + } - print ''; + print ''; - print '
'.$langs->trans("UserTitle").''; - print $object->getCivilityLabel(); - print '
'.$langs->trans("UserTitle").''; + print $object->getCivilityLabel(); + print '
'.$langs->trans("PostOrFunction").''.$object->poste.'
'.$langs->trans("PostOrFunction").''.$object->poste.'
'.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().'
'.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().'
'.$langs->trans("No_Email").''.yn($noemail).'
'.$langs->trans("No_Email").''.yn($noemail).'
'.$langs->trans("ContactVisibility").''; - print $object->LibPubPriv($object->priv); - print '
'.$langs->trans("ContactVisibility").''; + print $object->LibPubPriv($object->priv); + print '
'; - print '
'; + print ''; + print '
'; $object->fetch_thirdparty(); - if (! empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { + if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) { print '
'; @@ -1368,11 +1373,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; + 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') { - $formcompany->formProspectContactLevel($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_prospectlevel, 'prospect_contact_level_id', 1); + $formcompany->formProspectContactLevel($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_prospectlevel, 'prospect_contact_level_id', 1); } else { print $object->getLibProspLevel(); } @@ -1381,13 +1386,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Status of prospection $object->loadCacheOfProspStatus(); - print '' . $langs->trans("StatusProsp") . '' . $object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); + print ''.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); print '     '; 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 ($object->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; } print '
'; @@ -1396,10 +1401,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } - print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { @@ -1409,78 +1414,78 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; } - if (!empty($object->socid)) { - print ''; - print ''; - } + if (!empty($object->socid)) { + print ''; + print ''; + } - // Other attributes - $cols = 3; - $parameters = array('socid'=>$socid); - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 3; + $parameters = array('socid'=>$socid); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - $object->load_ref_elements(); + $object->load_ref_elements(); - if (!empty($conf->propal->enabled)) - { - print ''; - } + if (!empty($conf->propal->enabled)) + { + print ''; + } - if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) - { - print ''; - } + if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) + { + print ''; + } - if (!empty($conf->contrat->enabled)) - { - print ''; - } + if (!empty($conf->contrat->enabled)) + { + print ''; + } - if (!empty($conf->facture->enabled)) - { - print ''; - } + if (!empty($conf->facture->enabled)) + { + print ''; + } - print ''; + print ''; - print ''; + print ''; - print "
'.$langs->trans("ContactByDefaultFor").''; - print $formcompany->showRoles("roles", $object, 'view'); - print '
'.$langs->trans("ContactByDefaultFor").''; + print $formcompany->showRoles("roles", $object, 'view'); + print '
'.$langs->trans("ContactForProposals").''; - print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal"); - 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"); - print ''; - $none = $langs->trans("NoContactForAnyOrder"); - if (!empty($conf->expedition->enabled)) { $none = $langs->trans("NoContactForAnyOrderOrShipments"); } - print $object->ref_commande ? $object->ref_commande : $none; - print '
'; + 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"); } + 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("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("ContactForInvoices").''; + print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); + print '
'.$langs->trans("DolibarrLogin").''; - 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"); - print '
'.$langs->trans("DolibarrLogin").''; + 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"); + print '
'; - print $langs->trans("VCard").''; + print '
'; + print $langs->trans("VCard").''; print ''; print img_picto($langs->trans("Download"), 'vcard.png', 'class="paddingrightonly"'); print $langs->trans("Download"); print ''; - print '
"; + print ""; - print '
'; - print '
'; + print '
'; + print '
'; - dol_fiche_end(); + dol_fiche_end(); - // Barre d'actions - print '
'; + // Barre d'actions + print '
'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook @@ -1498,43 +1503,66 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } if ($user->rights->societe->contact->creer) - { - print ''.$langs->trans('Modify').''; - } + { + print ''.$langs->trans('Modify').''; + } - if (!$object->user_id && $user->rights->user->user->creer) - { - print ''.$langs->trans("CreateDolibarrLogin").''; - } + if (!$object->user_id && $user->rights->user->user->creer) + { + print ''.$langs->trans("CreateDolibarrLogin").''; + } - // Activer - if ($object->statut == 0 && $user->rights->societe->contact->creer) - { - print ''.$langs->trans("Reactivate").''; - } - // Desactiver - if ($object->statut == 1 && $user->rights->societe->contact->creer) - { - print ''.$langs->trans("DisableUser").''; - } + // Activer + if ($object->statut == 0 && $user->rights->societe->contact->creer) + { + print ''.$langs->trans("Reactivate").''; + } + // Desactiver + if ($object->statut == 1 && $user->rights->societe->contact->creer) + { + print ''.$langs->trans("DisableUser").''; + } - // Delete - if ($user->rights->societe->contact->supprimer) - { - print ''.$langs->trans('Delete').''; - } - } + // Delete + if ($user->rights->societe->contact->supprimer) + { + print ''.$langs->trans('Delete').''; + } + } - print "
"; + print "
"; - // Presend form - $modelmail = 'contact'; - $defaulttopic = 'Information'; - $diroutput = $conf->contact->dir_output; - $trackid = 'con'.$object->id; + //Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - } + if ($action != 'presend') + { + print '
'; + + print '
'; + + $MAXEVENT = 10; + + $morehtmlright = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-list-alt imgforviewmode', DOL_URL_ROOT.'/contact/agenda.php?id='.$object->id); + + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'contact', $object->socid, 1, '', $MAXEVENT, '', $morehtmlright); // Show all action for thirdparty + + print '
'; + } + + // Presend form + $modelmail = 'contact'; + $defaulttopic = 'Information'; + $diroutput = $conf->contact->dir_output; + $trackid = 'con'.$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 c475c1b439d..8ea6ebea0d4 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -60,6 +60,29 @@ class Contact extends CommonObject */ public $picto = 'contact'; + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * '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' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * '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") + * '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 /** @@ -69,38 +92,38 @@ class Contact extends CommonObject 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>15), 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), - 'fk_soc' =>array('type'=>'integer', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>25), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>30, 'index'=>1), - 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>35), - 'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>-1, 'position'=>40), - 'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>-1, 'position'=>45, 'showoncombobox'=>1), - 'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'showoncombobox'=>1), + 'fk_soc' =>array('type'=>'integer', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>1, 'position'=>25, 'searchall'=>1), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>30, 'index'=>1), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>3, 'position'=>35), + 'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>3, 'position'=>40), + 'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'showoncombobox'=>1, 'searchall'=>1), + 'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>1, 'position'=>50, 'showoncombobox'=>1, 'searchall'=>1), 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>55), - 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>60), - 'town' =>array('type'=>'text', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>65), - 'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>-1, 'position'=>70), - 'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>-1, 'position'=>75), - 'birthday' =>array('type'=>'date', 'label'=>'Birthday', 'enabled'=>1, 'visible'=>-1, 'position'=>80), + 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>1, 'position'=>60), + 'town' =>array('type'=>'text', 'label'=>'Town', 'enabled'=>1, 'visible'=>1, 'position'=>65), + 'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>3, 'position'=>70), + 'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>3, 'position'=>75), + 'birthday' =>array('type'=>'date', 'label'=>'Birthday', 'enabled'=>1, 'visible'=>3, 'position'=>80), 'poste' =>array('type'=>'varchar(80)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>-1, 'position'=>85), - 'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>90), - 'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'Phone perso', 'enabled'=>1, 'visible'=>-1, 'position'=>95), - 'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'Phone mobile', 'enabled'=>1, 'visible'=>-1, 'position'=>100), - 'fax' =>array('type'=>'varchar(30)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105), - 'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>110), - 'socialnetworks' =>array('type'=>'text', 'label'=>'SocialNetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>115), - 'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>-1, 'position'=>170), - 'priv' =>array('type'=>'smallint(6)', 'label'=>'Private', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>175), - 'fk_stcomm' =>array('type'=>'integer', 'label'=>'Fk stcommcontact', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220), + 'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>1, 'position'=>90, 'searchall'=>1), + 'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'PhonePerso', 'enabled'=>1, 'visible'=>1, 'position'=>95, 'searchall'=>1), + 'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'PhoneMobile', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'searchall'=>1), + 'fax' =>array('type'=>'varchar(30)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>1, 'position'=>105, 'searchall'=>1), + 'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>1, 'position'=>110, 'searchall'=>1), + 'socialnetworks' =>array('type'=>'text', 'label'=>'SocialNetworks', 'enabled'=>1, 'visible'=>3, 'position'=>115), + 'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>3, 'position'=>170), + 'priv' =>array('type'=>'smallint(6)', 'label'=>'ContactVisibility', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>175), + 'fk_stcommcontact' =>array('type'=>'integer', 'label'=>'Fk stcommcontact', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220), 'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255), - 'no_email' =>array('type'=>'smallint(6)', 'label'=>'No email', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>180), - 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>185), - 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'position'=>190), - 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>195), - 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>200), - 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>205), - 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>210), - 'statut' =>array('type'=>'tinyint(4)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000), + 'no_email' =>array('type'=>'smallint(6)', 'label'=>'No_Email', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>180), + 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>3, 'position'=>185), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>3, 'position'=>190), + 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>3, 'position'=>195, 'searchall'=>1), + 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>3, 'position'=>200, 'searchall'=>1), + 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>3, 'position'=>205), + 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>3, 'position'=>210), + 'statut' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000), ); public $civility_id; // In fact we store civility_code @@ -228,16 +251,22 @@ class Contact extends CommonObject 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->mailing->enabled)) $this->fields['no_email']['enabled'] = 0; - if (!empty($conf->global->SOCIETE_DISABLE_CONTACTS)) $this->fields['thirdparty']['enabled'] = 0; - if (empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { // Default behaviour - $this->field['fk_stcomm']['enabled'] = 0; - $this->field['fk_prospectlevel']['enabled'] = 0; - } $this->statut = 1; // By default, status is enabled + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; + if (empty($conf->mailing->enabled)) $this->fields['no_email']['enabled'] = 0; + + // typical ['s.nom'] is used for third-parties + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { + $this->fields['fk_soc']['enabled'] = 0; + $this->fields['fk_soc']['searchall'] = 0; + } + + if (empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { // Default behaviour + $this->field['fk_stcommcontact']['enabled'] = 0; + $this->field['fk_prospectcontactlevel']['enabled'] = 0; + } + // Unset fields that are disabled foreach ($this->fields as $key => $val) { @@ -1284,7 +1313,7 @@ class Contact extends CommonObject $label .= '
'; } - $label .= ''.$langs->trans("Contact").''; + $label .= img_picto('', $this->picto).' '.$langs->trans("Contact").''; $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; @@ -1649,7 +1678,7 @@ class Contact extends CommonObject $sql .= ", ".MAIN_DB_PREFIX."societe_contacts sc"; $sql .= " WHERE sc.fk_soc =".$this->socid; $sql .= " AND sc.fk_c_type_contact=tc.rowid"; - $sql .= " AND tc.element='".$element."'"; + $sql .= " AND tc.element='".$this->db->escape($element)."'"; $sql .= " AND tc.active=1"; dol_syslog(__METHOD__, LOG_DEBUG); diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index e21ee3e492b..f8498ddae9a 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -52,7 +52,7 @@ if (!empty($canvas)) // Security check if ($user->socid) $socid = $user->socid; -$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission +$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 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 9eeae17280f..4d30977bf6a 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -44,7 +44,7 @@ $langs->loadLangs(array("companies", "suppliers", "categories")); $socialnetworks = getArrayOfSocialNetworks(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -62,7 +62,7 @@ $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', $search_cti = preg_replace('/^0+/', '', preg_replace('/[^0-9]/', '', GETPOST('search_cti', 'alphanohtml'))); // Phone number without any special chars $search_phone = GETPOST("search_phone", 'alpha'); -$search_id = trim(GETPOST("search_id", "int")); +$search_id = GETPOST("search_id", "int"); $search_firstlast_only = GETPOST("search_firstlast_only", 'alpha'); $search_lastname = GETPOST("search_lastname", 'alpha'); $search_firstname = GETPOST("search_firstname", 'alpha'); @@ -77,7 +77,7 @@ $search_no_email = GETPOST("search_no_email", 'int'); if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { - $search_{$key} = GETPOST("search_".$key, 'alpha'); + $search_[$key] = GETPOST("search_".$key, 'alpha'); } } } @@ -104,8 +104,8 @@ $type = GETPOST("type", 'aZ'); $view = GETPOST("view", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $userid = GETPOST('userid', 'int'); $begin = GETPOST('begin'); @@ -149,44 +149,45 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" -$fieldstosearchall = array( - 'p.lastname'=>'Lastname', - 'p.firstname'=>'Firstname', - 'p.email'=>'EMail', - 's.nom'=>"ThirdParty", - 'p.phone'=>"Phone", - 'p.phone_perso'=>"PhonePerso", - 'p.phone_mobile'=>"PhoneMobile", - 'p.fax'=>"Fax", - 'p.note_public'=>"NotePublic", - 'p.note_private'=>"NotePrivate", -); +$fieldstosearchall = array(); +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; + } + + if (empty($val['searchall'])) { + continue; + } + + $fieldstosearchall['p.'.$key] = $val['label']; +} + +// Add none object fields for "search in all" +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { + $fieldstosearchall['s.nom'] = "ThirdParty"; +} // Definition of fields for list -$arrayfields = array( - 'p.rowid'=>array('label'=>"TechnicalID", 'position'=>1, 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID ? 1 : 0)), - 'p.lastname'=>array('label'=>"Lastname", 'position'=>2, 'checked'=>1), - 'p.firstname'=>array('label'=>"Firstname", 'position'=>3, 'checked'=>1), - 'p.poste'=>array('label'=>"PostOrFunction", 'position'=>10, 'checked'=>1), - 'p.town'=>array('label'=>"Town", 'position'=>20, 'checked'=>0), - 'p.zip'=>array('label'=>"Zip", 'position'=>21, 'checked'=>0), - 'country.code_iso'=>array('label'=>"Country", 'position'=>22, 'checked'=>0), - 'p.phone'=>array('label'=>"Phone", 'position'=>30, 'checked'=>1), - 'p.phone_perso'=>array('label'=>"PhonePerso", 'position'=>31, 'checked'=>0), - 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'position'=>32, 'checked'=>1), - 'p.fax'=>array('label'=>"Fax", 'position'=>33, 'checked'=>0), - 'p.email'=>array('label'=>"EMail", 'position'=>40, 'checked'=>1), - 'p.no_email'=>array('label'=>"No_Email", 'position'=>41, 'checked'=>0, 'enabled'=>(!empty($conf->mailing->enabled))), - 'p.thirdparty'=>array('label'=>"ThirdParty", 'position'=>50, 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), - 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), - 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), - 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), - 'p.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), -); -if (! empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { - $arrayfields['p.fk_prospectcontactlevel'] = array('label'=>"ProspectLevelShort", 'checked'=>1, 'position'=>210); - $arrayfields['p.fk_stcommcontact'] = array('label'=>"StatusProsp", 'checked'=>1, 'position'=>215); +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (empty($val['visible'])) { + continue; + } + + $arrayfields['p.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($val['visible'] < 0) ? 0 : 1), + 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), + 'position'=>$val['position']); +} + +// Add none object fields to fields for list +$arrayfields['country.code_iso'] = array('label'=>"Country", 'position'=>22, 'checked'=>0); +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { + $arrayfields['s.nom'] = array('label'=>"ThirdParty", 'position'=>25, 'checked'=>1); } if (!empty($conf->socialnetworks->enabled)) { @@ -200,6 +201,7 @@ if (!empty($conf->socialnetworks->enabled)) { } } } + // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { @@ -265,13 +267,13 @@ if (empty($reshook)) if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { - $search_{$key} = ""; + $search_[$key] = ""; } } } $search_priv = ""; - $search_stcomm=''; - $search_level=''; + $search_stcomm = ''; + $search_level = ''; $search_status = -1; $search_categ = ''; $search_categ_thirdparty = ''; @@ -314,7 +316,7 @@ $formother = new FormOther($db); $formcompany = new FormCompany($db); $contactstatic = new Contact($db); -if (! empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { +if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { $contactstatic->loadCacheOfProspStatus(); } @@ -323,17 +325,17 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C // Select every potentiels, and note each potentiels which fit in search parameters $tab_level = array(); $sql = "SELECT code, label, sortorder"; -$sql.= " FROM ".MAIN_DB_PREFIX."c_prospectcontactlevel"; -$sql.= " WHERE active > 0"; -$sql.= " ORDER BY sortorder"; +$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)) { // Compute level text - $level=$langs->trans($obj->code); - if ($level == $obj->code) $level=$langs->trans($obj->label); + $level = $langs->trans($obj->code); + if ($level == $obj->code) $level = $langs->trans($obj->label); $tab_level[$obj->code] = $level; } } @@ -343,7 +345,7 @@ $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,"; $sql .= " p.socialnetworks, p.photo,"; $sql .= " p.phone as phone_pro, p.phone_mobile, p.phone_perso, p.fax, p.fk_pays, p.priv, p.datec as date_creation, p.tms as date_update,"; -$sql.= " st.libelle as stcomm, st.picto as stcomm_picto, p.fk_stcommcontact as stcomm_id, p.fk_prospectcontactlevel,"; +$sql .= " st.libelle as stcomm, st.picto as stcomm_picto, p.fk_stcommcontact as stcomm_id, p.fk_prospectcontactlevel,"; $sql .= " co.label as country, co.code as country_code"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { @@ -357,7 +359,7 @@ $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)"; $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"; +$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 @@ -395,10 +397,10 @@ if (strlen($search_phone)) $sql .= natural_search(array('p.phone', 'p.p 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_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('s.nom', $search_societe); +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); @@ -407,8 +409,8 @@ if (strlen($search_phone_mobile)) $sql .= natural_search('p.phone_mobile', $se 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})) { - $sql .= ' AND p.socialnetworks LIKE \'%"'.$key.'":"'.$search_{$key}.'%\''; + if ($value['active'] && strlen($search_[$key])) { + $sql .= ' AND p.socialnetworks LIKE \'%"'.$key.'":"'.$search_[$key].'%\''; } } } @@ -469,7 +471,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; @@ -515,10 +517,10 @@ 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 ($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); + $param .= '&search_level[]='.urlencode($slevel); } } if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key); @@ -538,11 +540,7 @@ if ($user->rights->societe->supprimer) $arrayofmassactions['predelete'] = 'selectMassAction('', $arrayofmassactions); -$newcardbutton = ''; -if ($user->rights->societe->contact->creer) -{ - $newcardbutton .= dolGetButtonTitle($langs->trans('NewContactAddress'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?action=create'); -} +$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 ''; @@ -573,7 +571,7 @@ if ($search_firstlast_only) } $moreforfilter = ''; -if (!empty($conf->categorie->enabled)) +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
'; @@ -596,21 +594,20 @@ if (!empty($conf->categorie->enabled)) $moreforfilter .= $formother->select_categories(Categorie::TYPE_SUPPLIER, $search_categ_supplier, 'search_categ_supplier', 1); $moreforfilter .= '
'; } - $moreforfilter .= '
'; - $moreforfilter .= $langs->trans('Roles').': '; - $moreforfilter .= $formcompany->showRoles("search_roles", $objecttmp, 'edit', $search_roles); - $moreforfilter .= '
'; -} -if ($moreforfilter) -{ - print '
'; - 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 '
'; } +$moreforfilter .= '
'; +$moreforfilter .= $langs->trans('Roles').': '; +$moreforfilter .= $formcompany->showRoles("search_roles", $objecttmp, 'edit', $search_roles); +$moreforfilter .= '
'; + +print '
'; +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 '
'; + $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); @@ -719,13 +716,13 @@ if (!empty($conf->socialnetworks->enabled)) { if (!empty($arrayfields['p.'.$key]['checked'])) { print ''; - print ''; + print ''; print ''; } } } } -if (!empty($arrayfields['p.thirdparty']['checked'])) +if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; print ''; @@ -734,25 +731,25 @@ if (!empty($arrayfields['p.thirdparty']['checked'])) if (!empty($arrayfields['p.priv']['checked'])) { print ''; - $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); - print $form->selectarray('search_priv', $selectarray, $search_priv, 1); - print ''; + $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); + print $form->selectarray('search_priv', $selectarray, $search_priv, 1); + print ''; } // Prospect level -if (! empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) +if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { print ''; print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2); print ''; } // Prospect status -if (! empty($arrayfields['p.fk_stcommcontact']['checked'])) +if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { print ''; - $arraystcomm=array(); + $arraystcomm = array(); foreach ($contactstatic->cacheprospectstatus as $key => $val) { - $arraystcomm[$val['id']]=($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); + $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 '); print ''; @@ -808,7 +805,7 @@ if (!empty($arrayfields['p.town']['checked'])) print_liste_field_ //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 '); + 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); @@ -823,32 +820,33 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (!empty($arrayfields['p.thirdparty']['checked'])) print_liste_field_titre($arrayfields['p.thirdparty']['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 $parameters = array( - 'arrayfields'=>$arrayfields, - 'param'=>$param, - 'sortfield'=>$sortfield, - 'sortorder'=>$sortorder, + '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 '); + 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 '); + print_liste_field_titre($arrayfields['p.tms']['label'], $_SERVER["PHP_SELF"], "p.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } if (!empty($arrayfields['p.statut']['checked'])) { - print_liste_field_titre($arrayfields['p.statut']['label'], $_SERVER["PHP_SELF"], "p.statut", "", $param, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre($arrayfields['p.statut']['label'], $_SERVER["PHP_SELF"], "p.statut", "", $param, '', $sortfield, $sortorder, 'center '); } if (!empty($arrayfields['p.import_key']['checked'])) { - print_liste_field_titre($arrayfields['p.import_key']['label'], $_SERVER["PHP_SELF"], "p.import_key", "", $param, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre($arrayfields['p.import_key']['label'], $_SERVER["PHP_SELF"], "p.import_key", "", $param, '', $sortfield, $sortorder, 'center '); } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; @@ -877,7 +875,7 @@ while ($i < min($num, $limit)) $contactstatic->country_code = $obj->country_code; $contactstatic->photo = $obj->photo; - $contactstatic->fk_prospectlevel=$obj->fk_prospectcontactlevel; + $contactstatic->fk_prospectlevel = $obj->fk_prospectcontactlevel; print ''; @@ -986,15 +984,15 @@ while ($i < min($num, $limit)) } } } - // Company - if (!empty($arrayfields['p.thirdparty']['checked'])) + // Company + if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; if ($obj->socid) { - $objsoc = new Societe($db); - $objsoc->fetch($obj->socid); - print $objsoc->getNomUrl(1); + $objsoc = new Societe($db); + $objsoc->fetch($obj->socid); + print $objsoc->getNomUrl(1); } else print ' '; print ''; if (!$i) $totalarray['nbfield']++; @@ -1007,7 +1005,7 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) + if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { // Prospect level print ''; @@ -1016,16 +1014,16 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } - if (! empty($arrayfields['p.fk_stcommcontact']['checked'])) + if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { // Prospect status print '
'; - print '
' . $contactstatic->libProspCommStatut($obj->stcomm_id, 2, $contactstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); + 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 ($obj->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; } print '
'; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index a5a1714b6e5..1710b4dda6a 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php'; $langs->loadLangs(array('companies', 'other')); $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; @@ -188,7 +188,7 @@ if ($action == 'edit') print ''; // Date To Birth - print ''.$langs->trans("DateToBirth").''; + print ''.$langs->trans("DateOfBirth").''; $form = new Form($db); print $form->selectDate($object->birthday, 'birthday', 0, 0, 1, "perso", 1, 0); print ''; @@ -272,7 +272,7 @@ if ($action == 'edit') { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - print ''.$langs->trans("DateToBirth").''.dol_print_date($object->birthday, "day"); + print ''.$langs->trans("DateOfBirth").''.dol_print_date($object->birthday, "day"); print '   '; //var_dump($birthdatearray); @@ -288,7 +288,7 @@ if ($action == 'edit') else print $langs->trans("BirthdayAlertOff"); print ''; } else { - print ''.$langs->trans("DateToBirth").''; + print ''.$langs->trans("DateOfBirth").''; } print ""; diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 031a1b7498d..5343ab8f349 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -42,7 +42,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'contrat'; //Must be the $element of the class that manage extrafield diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index 3e068f5650b..bd0c7b132d0 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_extrafields.php @@ -42,7 +42,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'contratdet'; //Must be the $element of the class that manage extrafield diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 7904bd321ae..b6e77e69dca 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -9,7 +9,7 @@ * Copyright (C) 2014-2018 Ferran Marcet * Copyright (C) 2014-2016 Marcos García * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2020 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 @@ -50,7 +50,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->loadLangs(array("contracts", "orders", "companies", "bills", "products", 'compta')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $socid = GETPOST('socid', 'int'); $id = GETPOST('id', 'int'); @@ -568,7 +568,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } unset($_POST['prod_entry_mode']); @@ -665,7 +665,8 @@ if (empty($reshook)) $fk_unit = GETPOST('unit', 'alpha'); - $objectline->description = GETPOST('product_desc', 'none'); + $objectline->fk_product = GETPOST('idprod', 'int'); + $objectline->description = GETPOST('product_desc', 'restricthtml'); $objectline->price_ht = GETPOST('elprice'); $objectline->subprice = GETPOST('elprice'); $objectline->qty = GETPOST('elqty'); @@ -743,7 +744,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -811,7 +812,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) { @@ -1191,7 +1192,7 @@ if ($action == 'create') // Other attributes if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit', $parameters); + print $object->showOptionals($extrafields, 'create', $parameters); } print "\n"; @@ -1436,8 +1437,6 @@ if ($action == 'create') $usemargins = 0; if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) $usemargins = 1; - $var = false; - // Title line for service $cursorline = 1; print '
'; @@ -1448,7 +1447,6 @@ if ($action == 'create') print ''; print ''; print ''; - print ''; print ''; // Area with common detail of line @@ -1569,7 +1567,7 @@ if ($action == 'create') } if ($user->rights->contrat->creer && ($object->statut >= 0)) { - print ''; + print ''; print img_delete(); print ''; } @@ -1632,17 +1630,29 @@ if ($action == 'create') // Ligne carac print ''; print ''; - if ($objp->fk_product) + if ($objp->fk_product > 0) { - $productstatic->id = $objp->fk_product; - $productstatic->type = $objp->ptype; - $productstatic->ref = $objp->pref; - $productstatic->entity = $objp->pentity; - print $productstatic->getNomUrl(1, '', 32); - print $objp->label ? ' - '.dol_trunc($objp->label, 32) : ''; + $canchangeproduct = 1; + if (empty($canchangeproduct)) { + $productstatic->id = $objp->fk_product; + $productstatic->type = $objp->ptype; + $productstatic->ref = $objp->pref; + $productstatic->entity = $objp->pentity; + print $productstatic->getNomUrl(1, '', 32); + print $objp->label ? ' - '.dol_trunc($objp->label, 32) : ''; + print ''; + } else { + $senderissupplier = 0; + if (empty($senderissupplier)) { + print $form->select_produits((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod'); + } else { + print $form->select_produits_fournisseurs((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod'); + } + } print '
'; } else { print $objp->label ? $objp->label.'
' : ''; + print ''; } // editeur wysiwyg @@ -1897,7 +1907,7 @@ if ($action == 'create') print ''; print ''; - print ''.$langs->trans("Comment").''; + print ''.$langs->trans("Comment").''; print ''; print '   '; print ''; @@ -2098,7 +2108,7 @@ if ($action == 'create') // - Droit de supprimer if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) { - print ''; + print ''; } else { print ''; } @@ -2126,7 +2136,7 @@ if ($action == 'create') $delallowed = $user->rights->contrat->creer; - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); // Show links to link elements diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php index ffe66208afe..671ac1177f6 100644 --- a/htdocs/contrat/class/api_contracts.class.php +++ b/htdocs/contrat/class/api_contracts.class.php @@ -141,7 +141,7 @@ class Contracts extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -149,28 +149,28 @@ class Contracts extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; while ($i < $min) { - $obj = $db->fetch_object($result); - $contrat_static = new Contrat($db); + $obj = $this->db->fetch_object($result); + $contrat_static = new Contrat($this->db); if ($contrat_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($contrat_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve contrat list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No contract found'); diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index ab94e73b58c..e179bd50797 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -510,7 +510,7 @@ class Contrat extends CommonObject if ($num) { - $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$num."', statut = 1"; + $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"; @@ -726,6 +726,7 @@ class Contrat extends CommonObject $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; + $this->model_pdf = $obj->model_pdf; $this->modelpdf = $obj->model_pdf; $this->fk_projet = $obj->fk_project; // deprecated @@ -1092,7 +1093,7 @@ class Contrat extends CommonObject } $sqlcontact = "SELECT ctc.code, ctc.source, ec.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 = '".$originforcontact."'"; + $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) @@ -1540,15 +1541,15 @@ class Contrat extends CommonObject $sql .= ($fk_product > 0 ? $fk_product : "null").","; $sql .= " ".$qty.","; $sql .= " ".$txtva.","; - $sql .= " ".($vat_src_code ? "'".$vat_src_code."'" : "null").","; + $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").","; $sql .= " ".$txlocaltax1.","; $sql .= " ".$txlocaltax2.","; - $sql .= " '".$localtax1_type."',"; - $sql .= " '".$localtax2_type."',"; + $sql .= " '".$this->db->escape($localtax1_type)."',"; + $sql .= " '".$this->db->escape($localtax2_type)."',"; $sql .= " ".price2num($remise_percent).","; $sql .= " ".price2num($pu_ht).","; $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).","; - $sql .= " '".$info_bits."',"; + $sql .= " '".$this->db->escape($info_bits)."',"; $sql .= " ".price2num($price).",".price2num($remise).","; if (isset($fk_fournprice)) $sql .= ' '.$fk_fournprice.','; else $sql .= ' null,'; @@ -1716,8 +1717,8 @@ class Contrat extends CommonObject $sql .= ",tva_tx='".price2num($tvatx)."'"; $sql .= ",localtax1_tx='".price2num($localtax1tx)."'"; $sql .= ",localtax2_tx='".price2num($localtax2tx)."'"; - $sql .= ",localtax1_type='".$localtax1_type."'"; - $sql .= ",localtax2_type='".$localtax2_type."'"; + $sql .= ",localtax1_type='".$this->db->escape($localtax1_type)."'"; + $sql .= ",localtax2_type='".$this->db->escape($localtax2_type)."'"; $sql .= ", total_ht='".price2num($total_ht)."'"; $sql .= ", total_tva='".price2num($total_tva)."'"; $sql .= ", total_localtax1='".price2num($total_localtax1)."'"; @@ -1910,7 +1911,6 @@ class Contrat extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) $statusType = 'status6'; if ($mode == 4 || $mode == 6 || $mode == 7) @@ -1967,7 +1967,7 @@ class Contrat extends CommonObject $label = ''; if ($user->rights->contrat->lire) { - $label = ''.$langs->trans("ShowContract").''; + $label = img_picto('', $this->picto).' '.$langs->trans("Contract").''; $label .= '
'.$langs->trans('Ref').': '.($this->ref ? $this->ref : $this->id); $label .= '
'.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); $label .= '
'.$langs->trans('RefSupplier').': '.$this->ref_supplier; @@ -2256,7 +2256,7 @@ class Contrat extends CommonObject { while ($obj = $this->db->fetch_object($resql)) { - $this->nb["Contracts"] = $obj->nb; + $this->nb["contracts"] = $obj->nb; } $this->db->free($resql); return 1; @@ -2309,6 +2309,8 @@ class Contrat extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."product"; $sql .= " WHERE entity IN (".getEntity('product').")"; $sql .= " AND tosell = 1"; + $sql .= $this->db->plimit(100); + $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index 02d9c71776d..38a97d0aaa8 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -36,7 +36,7 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('contracts', 'companies')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $socid = GETPOST('socid', 'int'); $id = GETPOST('id', 'int'); diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 40a9a4100da..7fe88d03c3d 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -37,8 +37,8 @@ $hookmanager->initHooks(array('contractindex')); // Load translation files required by the page $langs->loadLangs(array('products', 'companies', 'contracts')); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $statut = GETPOST('statut') ?GETPOST('statut') : 1; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 8afc2f0e335..04329a63145 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // Load translation files required by the page $langs->loadLangs(array('contracts', 'products', 'companies', 'compta')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -50,13 +50,13 @@ $search_name = GETPOST('search_name', 'alpha'); $search_email = GETPOST('search_email', 'alpha'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); -$search_state = trim(GETPOST("search_state", 'alpha')); +$search_state = GETPOST("search_state", 'alpha'); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_contract = GETPOST('search_contract', 'alpha'); $search_ref_customer = GETPOST('search_ref_customer', 'alpha'); $search_ref_supplier = GETPOST('search_ref_supplier', 'alpha'); -$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$sall = (GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search_status = GETPOST('search_status', 'alpha'); $socid = GETPOST('socid', 'int'); $search_user = GETPOST('search_user', 'int'); @@ -369,11 +369,9 @@ if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete'] = 'selectMassAction('', $arrayofmassactions); -$newcardbutton = ''; -if ($user->rights->contrat->creer) -{ - $newcardbutton .= dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contrat/card.php?action=create'); -} +$url = DOL_URL_ROOT.'/contrat/card.php?action=create'; +if (!empty($socid)) $url .= '&socid='.$socid; +$newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer); print ''; if ($optioncss != '') print ''; @@ -418,7 +416,7 @@ if ($user->rights->user->user->lire) $moreforfilter .= '
'; } // If the user can view categories of products -if ($conf->categorie->enabled && ($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 .= '
'; diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index d782ad5b3f5..d9eb8e3ccdc 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -34,7 +34,7 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array('companies', 'contracts')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $socid = GETPOST('socid', 'int'); $id = GETPOST('id', 'int'); diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 38aae136b39..7279ab98781 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -199,7 +199,7 @@ $now = dol_now(); $form = new Form($db); -$sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut,"; +$sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut, c.ref_customer, c.ref_supplier,"; $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,"; @@ -564,6 +564,8 @@ while ($i < min($num, $limit)) $contractstatic->id = $obj->cid; $contractstatic->ref = $obj->ref ? $obj->ref : $obj->cid; + $contractstatic->ref_customer = $obj->ref_customer; + $contractstatic->ref_supplier = $obj->ref_supplier; $companystatic->id = $obj->socid; $companystatic->name = $obj->name; diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 1114e33f6f6..cee75415eee 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -64,7 +64,7 @@ if ($action == 'add' && !empty($permissiontoadd)) // Set value to insert if (in_array($object->fields[$key]['type'], array('text', 'html'))) { - $value = GETPOST($key, 'none'); + $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')); } elseif ($object->fields[$key]['type'] == 'datetime') { @@ -72,7 +72,7 @@ if ($action == 'add' && !empty($permissiontoadd)) } 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'])) { - $value = price2num(GETPOST($key, 'none')); // To fix decimal separator according to lang setup + $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup } elseif ($object->fields[$key]['type'] == 'boolean') { $value = (GETPOST($key) == 'on' ? 1 : 0); } else { @@ -85,7 +85,7 @@ if ($action == 'add' && !empty($permissiontoadd)) $object->$key = $value; if ($val['notnull'] > 0 && $object->$key == '' && !is_null($val['default']) && $val['default'] == '(PROV)') { - $object->$key = '(PROV)'; + $object->$key = '(PROV)'; } if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) { @@ -105,7 +105,7 @@ if ($action == 'add' && !empty($permissiontoadd)) $result = $object->create($user); if ($result > 0) { - // Creation OK + // 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 header("Location: ".$urltogo); @@ -141,8 +141,13 @@ if ($action == 'update' && !empty($permissiontoadd)) if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Set value to update - if (in_array($object->fields[$key]['type'], array('text', 'html'))) { - $value = GETPOST($key, 'none'); + if (preg_match('/^(text|html)/', $object->fields[$key]['type'])) { + $tmparray = explode(':', $object->fields[$key]['type']); + if (!empty($tmparray[1])) { + $value = GETPOST($key, $tmparray[1]); + } else { + $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')); } elseif ($object->fields[$key]['type'] == 'datetime') { @@ -154,7 +159,7 @@ if ($action == 'update' && !empty($permissiontoadd)) $value = ''; } } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) { - $value = price2num(GETPOST($key, 'none')); // To fix decimal separator according to lang setup + $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup } elseif ($object->fields[$key]['type'] == 'boolean') { $value = ((GETPOST($key, 'aZ09') == 'on' || GETPOST($key, 'aZ09') == '1') ? 1 : 0); } else { @@ -223,11 +228,11 @@ if ($action == "update_extras" && !empty($permissiontoadd)) // Action to delete if ($action == 'confirm_delete' && !empty($permissiontodelete)) { - if (!($object->id > 0)) - { - dol_print_error('', 'Error, object must be fetched before being deleted'); - exit; - } + if (!($object->id > 0)) + { + dol_print_error('', 'Error, object must be fetched before being deleted'); + exit; + } $result = $object->delete($user); if ($result > 0) @@ -245,7 +250,11 @@ if ($action == 'confirm_delete' && !empty($permissiontodelete)) // Remove a line if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) { - $result = $object->deleteline($user, $lineid); + if (method_exists('deleteline', $object)) { + $result = $object->deleteline($user, $lineid); // For backward compatibility + } else { + $result = $object->deleteLine($user, $lineid); + } if ($result > 0) { // Define output language @@ -264,8 +273,10 @@ if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissionto $outputlangs->setDefaultLang($newlang); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (method_exists($object, 'generateDocument')) { + $ret = $object->fetch($object->id); // Reload to get new records + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs'); @@ -283,8 +294,7 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $outputlangs = $langs; $newlang = ''; @@ -294,7 +304,7 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -312,20 +322,21 @@ if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) if ($result >= 0) { // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + 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 (!empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model = $object->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -351,20 +362,21 @@ if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) if ($result >= 0) { // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + 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 (!empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model = $object->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -378,11 +390,11 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) { 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 = 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) + // ... + $result = $objectutil->createFromClone($user, (($object->id > 0) ? $object->id : $id)); + if (is_object($result) || $result > 0) { $newid = 0; if (is_object($result)) $newid = $result->id; @@ -390,7 +402,7 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) header("Location: ".$_SERVER['PHP_SELF'].'?id='.$newid); // Open record of new object exit; } else { - setEventMessages($objectutil->error, $objectutil->errors, 'errors'); + setEventMessages($objectutil->error, $objectutil->errors, 'errors'); $action = ''; } } diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index eb51796eccd..20bd19625cc 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -82,7 +82,7 @@ if ($action == 'builddoc' && $permissiontoadd) if (empty($hideref)) $hideref = 0; if (empty($moreparams)) $moreparams = null; - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); diff --git a/htdocs/core/actions_changeselectedfields.inc.php b/htdocs/core/actions_changeselectedfields.inc.php index 9a03ba0d29e..f4e7f01d234 100644 --- a/htdocs/core/actions_changeselectedfields.inc.php +++ b/htdocs/core/actions_changeselectedfields.inc.php @@ -28,7 +28,7 @@ // $object must be defined (object is loaded in this file with fetch) // Save selection -if (GETPOST('formfilteraction', 'none') == 'listafterchangingselectedfields') +if (GETPOST('formfilteraction', 'alphanohtml') == 'listafterchangingselectedfields') { $tabparam = array(); diff --git a/htdocs/core/actions_comments.inc.php b/htdocs/core/actions_comments.inc.php index c352f07f9f7..079f207b4a4 100644 --- a/htdocs/core/actions_comments.inc.php +++ b/htdocs/core/actions_comments.inc.php @@ -35,7 +35,7 @@ $comment = new Comment($db); if ($action == 'addcomment') { - $description = GETPOST('comment_description', 'none'); + $description = GETPOST('comment_description', 'restricthtml'); if (!empty($description)) { $comment->description = $description; @@ -59,7 +59,7 @@ if ($action === 'updatecomment') { if ($comment->fetch($idcomment) >= 0) { - $comment->description = GETPOST('comment_description', 'none'); + $comment->description = GETPOST('comment_description', 'restricthtml'); if ($comment->update($user) > 0) { setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); diff --git a/htdocs/core/actions_lineupdown.inc.php b/htdocs/core/actions_lineupdown.inc.php index b0556d6399f..e5507eeafc0 100644 --- a/htdocs/core/actions_lineupdown.inc.php +++ b/htdocs/core/actions_lineupdown.inc.php @@ -43,7 +43,7 @@ if ($action == 'up' && $permissiontoedit) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid')); @@ -64,7 +64,7 @@ if ($action == 'down' && $permissiontoedit) $outputlangs->setDefaultLang($newlang); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid')); diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index 7884fc09e67..3caeeed6678 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -63,7 +63,7 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) } } } -} elseif (GETPOST('linkit', 'none') && !empty($conf->global->MAIN_UPLOAD_DOC)) +} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) { $link = GETPOST('link', 'alpha'); if ($link) diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 612f988305f..c2f0a314445 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 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 @@ -141,7 +141,7 @@ if (!$error && $massaction == 'confirm_presend') $massaction = 'presend'; } - if (!GETPOST('subject', 'none')) + if (!GETPOST('subject', 'restricthtml')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); @@ -376,8 +376,8 @@ if (!$error && $massaction == 'confirm_presend') } $replyto = $from; - $subject = GETPOST('subject', 'none'); - $message = GETPOST('message', 'none'); + $subject = GETPOST('subject', 'restricthtml'); + $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)); @@ -615,7 +615,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders $cmd->fetch_optionals(); $objecttmp->socid = $cmd->socid; - $objecttmp->type = Facture::TYPE_STANDARD; + $objecttmp->type = $objecttmp::TYPE_STANDARD; $objecttmp->cond_reglement_id = $cmd->cond_reglement_id; $objecttmp->mode_reglement_id = $cmd->mode_reglement_id; $objecttmp->fk_project = $cmd->fk_project; @@ -648,9 +648,9 @@ if ($massaction == 'confirm_createbills') // Create bills from orders $sql .= ", targettype"; $sql .= ") VALUES ("; $sql .= $id_order; - $sql .= ", '".$objecttmp->origin."'"; + $sql .= ", '".$db->escape($objecttmp->origin)."'"; $sql .= ", ".$objecttmp->id; - $sql .= ", '".$objecttmp->element."'"; + $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; if (!$db->query($sql)) @@ -742,7 +742,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders 'HT', 0, $product_type, - $ii, + $lines[$i]->rang, $lines[$i]->special_code, $objecttmp->origin, $lines[$i]->rowid, diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index bc38d9839af..5be25002079 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -114,12 +114,11 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST $result = $object->fetch($id); $sendtosocid = 0; // Id of related thirdparty - if (method_exists($object, "fetch_thirdparty") && !in_array($object->element, array('societe', 'member', 'user', 'expensereport', 'contact'))) + if (method_exists($object, "fetch_thirdparty") && !in_array($object->element, array('member', 'user', 'expensereport', 'societe', 'contact'))) { - $result = $object->fetch_thirdparty(); - if ($object->element == 'user' && $result == 0) $result = 1; // Even if not found, we consider ok + $resultthirdparty = $object->fetch_thirdparty(); $thirdparty = $object->thirdparty; - $sendtosocid = $thirdparty->id; + if (is_object($thirdparty)) $sendtosocid = $thirdparty->id; } elseif ($object->element == 'member' || $object->element == 'user') { $thirdparty = $object; @@ -133,11 +132,15 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST } elseif ($object->element == 'societe') { $thirdparty = $object; - if ($thirdparty->id > 0) $sendtosocid = $thirdparty->id; + if (is_object($thirdparty) && $thirdparty->id > 0) $sendtosocid = $thirdparty->id; } elseif ($object->element == 'contact') { $contact = $object; - if ($contact->id > 0) $sendtosocid = $contact->fetch_thirdparty()->id; + if ($contact->id > 0) { + $contact->fetch_thirdparty(); + $thirdparty = $contact->thirdparty; + if (is_object($thirdparty) && $thirdparty->id > 0) $sendtosocid = $thirdparty->id; + } } else dol_print_error('', "Use actions_sendmails.in.php for an element/object '".$object->element."' that is not supported"); if (is_object($hookmanager)) @@ -145,7 +148,9 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST $parameters = array(); $reshook = $hookmanager->executeHooks('initSendToSocid', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks } - } else $thirdparty = $mysoc; + } else { + $thirdparty = $mysoc; + } if ($result > 0) { @@ -170,23 +175,24 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST // Recipients are provided into free text $tmparray[] = trim($_POST['sendto']); } + if (count($receiver) > 0) { + // Recipient was provided from combo list foreach ($receiver as $key=>$val) { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Key selected means currentthird party (may be usd for current member or current user too) + if ($val == 'thirdparty') // Key selected means current third party ('thirdparty' may be used for current member or current user too) { $tmparray[] = dol_string_nospecial($thirdparty->getFullName($langs), ' ', array(",")).' <'.$thirdparty->email.'>'; } - // Recipient was provided from combo list elseif ($val == 'contact') // Key selected means current contact { $tmparray[] = dol_string_nospecial($contact->getFullName($langs), ' ', array(",")).' <'.$contact->email.'>'; + $sendtoid[] = $contact->id; } elseif ($val) // $val is the Id of a contact { $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); - $sendtoid[] = $val; + $sendtoid[] = ((int) $val); } } } @@ -232,10 +238,11 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST elseif ($val == 'contact') // Key selected means current contact { $tmparray[] = dol_string_nospecial($contact->name, ' ', array(",")).' <'.$contact->email.'>'; + //$sendtoid[] = $contact->id; TODO Add also id of contact in CC ? } elseif ($val) // $val is the Id of a contact { $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); - //$sendtoid[] = $val; TODO Add also id of contact in CC ? + //$sendtoid[] = ((int) $val); TODO Add also id of contact in CC ? } } } @@ -256,12 +263,12 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST if (dol_strlen($sendto)) { - // 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 + // 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 - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $langs->load("commercial"); @@ -293,8 +300,8 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST } $replyto = dol_string_nospecial($_POST['replytoname'], ' ', array(",")).' <'.$_POST['replytomail'].'>'; - $message = GETPOST('message', 'none'); - $subject = GETPOST('subject', 'none'); + $message = GETPOST('message', 'restricthtml'); + $subject = GETPOST('subject', 'restricthtml'); // Make a change into HTML code to allow to include images from medias directory with an external reabable URL. // @@ -412,10 +419,10 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST // Initialisation of datas of object to call trigger if (is_object($object)) { - if (empty($actiontypecode)) $actiontypecode = 'AC_OTH_AUTO'; // Event insert into agenda automatically + if (empty($actiontypecode)) $actiontypecode = 'AC_OTH_AUTO'; // Event insert into agenda automatically $object->socid = $sendtosocid; // To link to a company - $object->sendtoid = $sendtoid; // To link to contact addresses. This is an array. + $object->sendtoid = $sendtoid; // To link to contact-addresses. This is an array. $object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) $object->actionmsg = $actionmsg; // Long text (@todo Replace this with $message, we already have details of email in dedicated properties) $object->actionmsg2 = $actionmsg2; // Short text ($langs->transnoentities('MailSentBy')...); @@ -449,7 +456,7 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST if ($error) { setEventMessages($object->error, $object->errors, 'errors'); - } + } } // End call of triggers } @@ -486,7 +493,7 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST $action = 'presend'; } } else { - $langs->load("other"); + $langs->load("errors"); setEventMessages($langs->trans('ErrorFailedToReadObject', $object->element), null, 'errors'); dol_syslog('Failed to read data of object id='.$object->id.' element='.$object->element); $action = 'presend'; diff --git a/htdocs/core/actions_setnotes.inc.php b/htdocs/core/actions_setnotes.inc.php index 3bbba0204f5..61db9b9fc55 100644 --- a/htdocs/core/actions_setnotes.inc.php +++ b/htdocs/core/actions_setnotes.inc.php @@ -33,7 +33,7 @@ if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', 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', 'none'), ENT_QUOTES, 'UTF-8', 1), '_public'); + $result_update = $object->update_note(dol_html_entity_decode(GETPOST('note_public', 'restricthtml'), ENT_QUOTES, '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'))) @@ -49,7 +49,7 @@ if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_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)); @@ -63,6 +63,6 @@ if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', // 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 - $result = $object->update_note(dol_html_entity_decode(GETPOST('note_private', 'none'), ENT_QUOTES), '_private'); + $result = $object->update_note(dol_html_entity_decode(GETPOST('note_private', 'restricthtml'), ENT_QUOTES), '_private'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index e2a7ae83326..41e23819266 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -34,28 +34,28 @@ if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); 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'; - require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; + 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'; + require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; - $action = GETPOST('action', 'aZ09'); - $file = urldecode(GETPOST('file', 'alpha')); - $section = GETPOST("section", 'alpha'); - $module = GETPOST("module", 'alpha'); - $urlsource = GETPOST("urlsource", 'alpha'); - $search_doc_ref = GETPOST('search_doc_ref', 'alpha'); + $action = GETPOST('action', 'aZ09'); + $file = urldecode(GETPOST('file', 'alpha')); + $section = GETPOST("section", 'alpha'); + $module = GETPOST("module", 'alpha'); + $urlsource = GETPOST("urlsource", 'alpha'); + $search_doc_ref = GETPOST('search_doc_ref', '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) { $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"; + $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 = $limit * $page; + $pageprev = $page - 1; + $pagenext = $page + 1; + if (!$sortorder) $sortorder = "ASC"; + if (!$sortfield) $sortfield = "name"; $rootdirfordoc = $conf->ecm->dir_output; @@ -63,30 +63,30 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $ecmdir = new EcmDirectory($db); if ($section > 0) { - $result = $ecmdir->fetch($section); - if (!$result > 0) - { - //dol_print_error($db,$ecmdir->error); - //exit; - } + $result = $ecmdir->fetch($section); + if (!$result > 0) + { + //dol_print_error($db,$ecmdir->error); + //exit; + } } } else // For no ajax call { $rootdirfordoc = $conf->ecm->dir_output; $ecmdir = new EcmDirectory($db); - $relativepath = ''; - if ($section > 0) - { - $result = $ecmdir->fetch($section); - if (!$result > 0) - { - dol_print_error($db, $ecmdir->error); - exit; - } + $relativepath = ''; + if ($section > 0) + { + $result = $ecmdir->fetch($section); + if (!$result > 0) + { + dol_print_error($db, $ecmdir->error); + exit; + } - $relativepath = $ecmdir->getRelativePath(); // Example 'mydir/' - } elseif (GETPOST('section_dir')) + $relativepath = $ecmdir->getRelativePath(); // Example 'mydir/' + } elseif (GETPOST('section_dir')) { $relativepath = GETPOST('section_dir'); } @@ -113,10 +113,10 @@ if ($user->socid > 0) $socid = $user->socid; // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. 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)); - exit; + 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)); + exit; } // Check permissions @@ -145,10 +145,10 @@ if ($modulepart == 'medias') if (!isset($mode) || $mode != 'noajax') { // Ajout directives pour resoudre bug IE - header('Cache-Control: Public, must-revalidate'); - header('Pragma: public'); + header('Cache-Control: Public, must-revalidate'); + header('Pragma: public'); - top_httphead(); + top_httphead(); } $type = 'directory'; @@ -156,8 +156,8 @@ $type = 'directory'; // This test if file exists should be useless. We keep it to find bug more easily if (!dol_is_dir($upload_dir)) { - //dol_mkdir($upload_dir); - /*$langs->load("install"); + //dol_mkdir($upload_dir); + /*$langs->load("install"); dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir)); exit;*/ } @@ -173,71 +173,76 @@ if (!empty($pageid)) $param .= '&pageid='.urlencode($pageid); // Dir scan if ($type == 'directory') { - $formfile = new FormFile($db); + $formfile = new FormFile($db); - $maxlengthname = 40; - $excludefiles = array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$'); - $sorting = (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC); + $maxlengthname = 40; + $excludefiles = array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$'); + $sorting = (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC); - // Right area. If module is defined here, we are in automatic ecm. - $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'supplier_proposal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user', 'expensereport', 'holiday', 'banque'); + // Right area. If module is defined here, we are in automatic ecm. + $automodules = array( + 'company', + 'invoice', + 'invoice_supplier', + 'propal', + 'supplier_proposal', + 'order', + 'order_supplier', + 'contract', + 'product', + 'tax', + 'project', + 'fichinter', + 'user', + 'expensereport', + 'holiday', + 'recruitment-recruitmentcandidature', + 'banque', + 'mrp-mo' + ); - // TODO change for multicompany sharing - // Auto area for suppliers invoices - if ($module == 'company') $upload_dir = $conf->societe->dir_output; - // Auto area for suppliers invoices - elseif ($module == 'invoice') $upload_dir = $conf->facture->dir_output; - // Auto area for suppliers invoices - elseif ($module == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output; - // Auto area for customers proposal - elseif ($module == 'propal') $upload_dir = $conf->propal->dir_output; - // Auto area for suppliers proposal - elseif ($module == 'supplier_proposal') $upload_dir = $conf->supplier_proposal->dir_output; - // Auto area for customers orders - elseif ($module == 'order') $upload_dir = $conf->commande->dir_output; - // Auto area for suppliers orders - elseif ($module == 'order_supplier') $upload_dir = $conf->fournisseur->commande->dir_output; - // Auto area for suppliers invoices - elseif ($module == 'contract') $upload_dir = $conf->contrat->dir_output; - // Auto area for products - elseif ($module == 'product') $upload_dir = $conf->product->dir_output; - // Auto area for suppliers invoices - elseif ($module == 'tax') $upload_dir = $conf->tax->dir_output; - // Auto area for projects - elseif ($module == 'project') $upload_dir = $conf->projet->dir_output; - // Auto area for interventions - elseif ($module == 'fichinter') $upload_dir = $conf->ficheinter->dir_output; - // Auto area for users - elseif ($module == 'user') $upload_dir = $conf->user->dir_output; - // Auto area for expense report - elseif ($module == 'expensereport') $upload_dir = $conf->expensereport->dir_output; - // Auto area for holiday - elseif ($module == 'holiday') $upload_dir = $conf->holiday->dir_output; - // Auto area for holiday - elseif ($module == 'banque') $upload_dir = $conf->bank->dir_output; + // 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'; - // Automatic list - if (in_array($module, $automodules)) - { - $param .= '&module='.$module; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.urlencode($search_doc_ref); + // Automatic list + if (in_array($module, $automodules)) + { + $param .= '&module='.$module; + 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"))); + $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); + $filter = preg_quote($search_doc_ref, '/'); + $filearray = dol_dir_list($upload_dir, "files", 1, $filter, $excludefiles, $sortfield, $sorting, 1); - $perm = $user->rights->ecm->upload; + $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') - { - /* + $formfile->list_of_autoecmfiles($upload_dir, $filearray, $module, $param, 1, '', $perm, 1, $textifempty, $maxlengthname, $url, 1); + } + // Manual list + else { + if ($module == 'medias') + { + /* $_POST is array like 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32) 'action' => string 'file_manager' (length=12) @@ -248,82 +253,82 @@ if ($type == 'directory') '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 .= '/'; - $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath; - 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('/backtopage=/',$param)) $param.='&backtopage='.urlencode($_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid); - } - } else { - $relativepath = $ecmdir->getRelativePath(); - $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; - } + $relativepath = GETPOST('file', 'alpha') ?GETPOST('file', 'alpha') : GETPOST('section_dir', 'alpha'); + if ($relativepath && $relativepath != '/') $relativepath .= '/'; + $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath; + 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('/backtopage=/',$param)) $param.='&backtopage='.urlencode($_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid); + } + } else { + $relativepath = $ecmdir->getRelativePath(); + $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; + } - // If $section defined with value 0 + // If $section defined with value 0 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); - } + { + $filearray = array(); + } else { + $filearray = dol_dir_list($upload_dir, "files", 0, '', array('^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^CVS$'), $sortfield, $sorting, 1); + } - if ($section) - { - $param .= '§ion='.$section; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.$search_doc_ref; + if ($section) + { + $param .= '§ion='.$section; + 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")); + $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")); - 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) - { - // Buttons: Preview - $useinecm = 2; - } + 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) + { + // Buttons: Preview + $useinecm = 2; + } - if ($user->rights->ecm->upload) - { - // Buttons: Preview + Delete - $useinecm = 4; - } + if ($user->rights->ecm->upload) + { + // Buttons: Preview + Delete + $useinecm = 4; + } - if ($user->rights->ecm->setup) - { - // Buttons: Preview + Delete + Edit - $useinecm = 5; - } + if ($user->rights->ecm->setup) + { + // Buttons: Preview + Delete + Edit + $useinecm = 5; + } - $perm = $user->rights->ecm->upload; - $modulepart = 'ecm'; - $title = ''; // Use default - } else { - $useinecm = 5; - $modulepart = 'ecm'; - $perm = $user->rights->ecm->upload; - $title = ''; // Use default - } + $perm = $user->rights->ecm->upload; + $modulepart = 'ecm'; + $title = ''; // Use default + } else { + $useinecm = 5; + $modulepart = 'ecm'; + $perm = $user->rights->ecm->upload; + $title = ''; // Use default + } - // When we show list of files for ECM files, $filearray contains file list, and directory is defined with modulepart + section into $param - // When we show list of files for a directory, $filearray ciontains file list, and directory is defined with modulepart + $relativepath - //var_dump("section=".$section." title=".$title." modulepart=".$modulepart." useinecm=".$useinecm." perm=".$perm." relativepath=".$relativepath." param=".$param." url=".$url); - $formfile->list_of_documents($filearray, '', $modulepart, $param, 1, $relativepath, $perm, $useinecm, $textifempty, $maxlengthname, $title, $url, 0, $perm); - } + // When we show list of files for ECM files, $filearray contains file list, and directory is defined with modulepart + section into $param + // When we show list of files for a directory, $filearray ciontains file list, and directory is defined with modulepart + $relativepath + //var_dump("section=".$section." title=".$title." modulepart=".$modulepart." useinecm=".$useinecm." perm=".$perm." relativepath=".$relativepath." param=".$param." url=".$url); + $formfile->list_of_documents($filearray, '', $modulepart, $param, 1, $relativepath, $perm, $useinecm, $textifempty, $maxlengthname, $title, $url, 0, $perm); + } } diff --git a/htdocs/core/ajax/check_notifications.php b/htdocs/core/ajax/check_notifications.php index 98d7d00a8dc..01cb85008bd 100644 --- a/htdocs/core/ajax/check_notifications.php +++ b/htdocs/core/ajax/check_notifications.php @@ -1,7 +1,7 @@ * Copyright (C) 2017 Juanjo Menent - * Copyright (C) 2019 Frédéric France + * 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 @@ -18,27 +18,83 @@ */ if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) 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('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('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//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("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("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL', '1'); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL' + require '../../main.inc.php'; +//$time = (int) GETPOST('time', 'int'); // Use the time parameter that is always increased by time_update, even if call is late +$time=dol_now(); +$action = GETPOST('action', 'aZ09'); +$listofreminderids = GETPOST('listofreminderids', 'aZ09'); + + +/* + * Actions + */ + +if ($action == 'stopreminder') { + dol_syslog("Clear notification for listofreminderids=".$listofreminderids); + $listofreminderid = GETPOST('listofreminderids', 'intcomma'); + + // Set the reminder as done + //foreach ($listofreminderidsarray as $listofreminderid) { + // if (empty($listofreminderid)) continue; + //$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'action_reminder WHERE rowid = '.$listofreminderid.' AND fk_user = '.$user->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'actioncomm_reminder SET status = 1'; + $sql .= ' WHERE status = 0 AND rowid IN ('.$db->sanitize($db->escape($listofreminderid)).')'; + $sql .= ' AND fk_user = '.$user->id.' AND entity = '.$conf->entity; + $resql = $db->query($sql); + if (!$resql) { + dol_print_error($db); + } + //} + + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + + // Clean database + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'actioncomm_reminder'; + $sql .= " WHERE dateremind < '".$db->idate(dol_time_plus_duree(dol_now(), -1, 'm'))."'"; + $resql = $db->query($sql); + if (!$resql) { + dol_print_error($db); + } + + exit; +} + /* * View */ -top_httphead('text/html'); // TODO Use a json mime type +top_httphead('application/json'); global $user, $db, $langs, $conf; -$time = (int) GETPOST('time', 'int'); // Use the time parameter that is always increased by time_update, even if call is late -//$time=dol_now(); - - $eventfound = array(); //Uncomment this to force a test //$eventfound[]=array('type'=>'agenda', 'id'=>1, 'tipo'=>'eee', 'location'=>'aaa'); @@ -46,9 +102,10 @@ $eventfound = array(); //dol_syslog('time='.$time.' $_SESSION[auto_ck_events_not_before]='.$_SESSION['auto_check_events_not_before']); // TODO Try to make a solution with only a javascript timer that is easier. Difficulty is to avoid notification twice when several tabs are opened. -if ($time >= $_SESSION['auto_check_events_not_before']) +// This need to extend period to be sure to not miss and save in session what we notified to avoid duplicate. +if (empty($_SESSION['auto_check_events_not_before']) || $time >= $_SESSION['auto_check_events_not_before'] || GETPOST('forcechecknow', 'int')) { - $time_update = (int) $conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY; // Always defined + /*$time_update = (int) $conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY; // Always defined if (!empty($_SESSION['auto_check_events_not_before'])) { // We start scan from the not before so if two tabs were opend at differents seconds and we close one (so the js timer), @@ -65,8 +122,9 @@ if ($time >= $_SESSION['auto_check_events_not_before']) } $_SESSION['auto_check_events_not_before'] = $time + $time_update; + */ - // Force save of session change we did. + // Force save of the session change we did. // WARNING: Any change in sessions after that will not be saved ! session_write_close(); @@ -75,41 +133,42 @@ if ($time >= $_SESSION['auto_check_events_not_before']) dol_syslog('NEW $_SESSION[auto_check_events_not_before]='.$_SESSION['auto_check_events_not_before']); - $sql = 'SELECT id'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm a, '.MAIN_DB_PREFIX.'actioncomm_resources ar'; - $sql .= ' WHERE a.id = ar.fk_actioncomm'; - // TODO Try to make a solution with only a javascript timer that is easier. Difficulty is to avoid notification twice when several tabs are opened. - // This need to extend period to be sure to not miss and save in session what we notified to avoid duplicate (save is not done yet). - $sql .= " AND datep BETWEEN '".$db->idate($starttime)."' AND '".$db->idate($time + $time_update - 1)."'"; - $sql .= ' AND a.code <> "AC_OTH_AUTO"'; - $sql .= ' AND ar.element_type = "user"'; - $sql .= ' AND ar.fk_element = '.$user->id; + $sql = 'SELECT a.id as id_agenda, a.code, a.datep, a.label, a.location, ar.rowid as id_reminder, ar.dateremind, ar.fk_user as id_user_reminder'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; + if (!empty($user->conf->MAIN_USER_WANT_ALL_EVENTS_NOTIFICATIONS)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_reminder as ar ON a.id = ar.fk_actioncomm AND ar.fk_user = '.$user->id; + $sql .= ' WHERE a.code <> "AC_OTH_AUTO"'; + $sql .= ' AND ('; + $sql .= " (ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."' AND ar.status = 0 AND ar.entity = ".$conf->entity; + $sql .= ' )'; + } else { + $sql .= ' JOIN '.MAIN_DB_PREFIX.'actioncomm_reminder as ar ON a.id = ar.fk_actioncomm AND ar.fk_user = '.$user->id; + $sql .= " AND ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."' AND ar.status = 0 AND ar.entity = ".$conf->entity; + } + $sql .= $db->order('datep', 'ASC'); $sql .= ' LIMIT 10'; // Avoid too many notification at once $resql = $db->query($sql); if ($resql) { - $actionmod = new ActionComm($db); - while ($obj = $db->fetch_object($resql)) { - // Load translation files required by the page - $langs->loadLangs(array('agenda', 'commercial')); - - $actionmod->fetch($obj->id); - // Message must be formated and translated to be used with javascript directly $event = array(); $event['type'] = 'agenda'; - $event['id'] = $actionmod->id; - $event['tipo'] = $langs->transnoentities('Action'.$actionmod->code); - $event['titulo'] = $actionmod->label; - $event['location'] = $langs->transnoentities('Location').': '.$actionmod->location; + $event['id_reminder'] = $obj->id_reminder; + $event['id_agenda'] = $obj->id_agenda; + $event['id_user'] = $obj->id_user_reminder; + $event['code'] = $obj->code; + $event['label'] = $obj->label; + $event['location'] = $obj->location; + $event['reminder_date_formated'] = dol_print_date($db->jdate($obj->dateremind), 'standard'); + $event['event_date_start_formated'] = dol_print_date($db->jdate($obj->datep), 'standard'); - $eventfound[] = $event; + $eventfound[$obj->id_agenda] = $event; } } else { dol_syslog("Error sql = ".$db->lasterror(), LOG_ERR); } } -print json_encode($eventfound); +print json_encode(array('pastreminders'=>$eventfound, 'nextreminder'=>'')); diff --git a/htdocs/core/ajax/constantonoff.php b/htdocs/core/ajax/constantonoff.php index 1ed8ca34076..710759e10bb 100644 --- a/htdocs/core/ajax/constantonoff.php +++ b/htdocs/core/ajax/constantonoff.php @@ -26,13 +26,15 @@ 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('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Token is required even in GET mode require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // set or del $name = GETPOST('name', 'alpha'); + /* * View */ @@ -46,7 +48,7 @@ top_httphead(); //print ''."\n"; -// Registering the location of boxes +// Registering the new value of constant if (!empty($action) && !empty($name)) { $entity = GETPOST('entity', 'int'); @@ -62,4 +64,6 @@ if (!empty($action) && !empty($name)) dolibarr_del_const($db, $name, $entity); } } +} else { + http_response_code(403); } diff --git a/htdocs/core/ajax/contacts.php b/htdocs/core/ajax/contacts.php index 67e769ab17f..6b476a8f59a 100644 --- a/htdocs/core/ajax/contacts.php +++ b/htdocs/core/ajax/contacts.php @@ -1,6 +1,6 @@ - * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2020 Laurent Destailleur * * 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,11 +27,15 @@ if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); require '../../main.inc.php'; -$id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$id = GETPOST('id', 'int'); // id of thirdparty +$action = GETPOST('action', 'aZ09'); $htmlname = GETPOST('htmlname', 'alpha'); $showempty = GETPOST('showempty', 'int'); +// Security check +$result = restrictedArea($user, 'societe', $id, '&societe', '', 'fk_soc', 'rowid', 0); + + /* * View */ diff --git a/htdocs/core/ajax/objectonoff.php b/htdocs/core/ajax/objectonoff.php index 6c9f97bfbb0..ceb221b4870 100644 --- a/htdocs/core/ajax/objectonoff.php +++ b/htdocs/core/ajax/objectonoff.php @@ -30,7 +30,7 @@ if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); $value = GETPOST('value', 'int'); $field = GETPOST('field', 'alpha'); diff --git a/htdocs/core/ajax/pingresult.php b/htdocs/core/ajax/pingresult.php index e08b2c5efcf..e58895a967f 100644 --- a/htdocs/core/ajax/pingresult.php +++ b/htdocs/core/ajax/pingresult.php @@ -30,7 +30,7 @@ if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $hash_unique_id = GETPOST('hash_unique_id', 'alpha'); $hash_algo = GETPOST('hash_algo', 'alpha'); diff --git a/htdocs/core/ajax/selectobject.php b/htdocs/core/ajax/selectobject.php index eed6c21c126..9d9b7bbfc42 100644 --- a/htdocs/core/ajax/selectobject.php +++ b/htdocs/core/ajax/selectobject.php @@ -33,7 +33,7 @@ $objectdesc = GETPOST('objectdesc', 'alpha'); $htmlname = GETPOST('htmlname', 'aZ09'); $sqlfilter = GETPOST('sqlfilter', 'alpha'); $outjson = (GETPOST('outjson', 'int') ? GETPOST('outjson', 'int') : 0); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); @@ -75,9 +75,10 @@ if (!is_object($objecttmp)) } // 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') : '')); +$searchkey = (($id && GETPOST($id, 'alpha')) ? GETPOST($id, 'alpha') : (($htmlname && GETPOST($htmlname, 'alpha')) ? GETPOST($htmlname, 'alpha') : '')); -// TODO Add a security test to avoid to get content of all tables +// Add a security test to avoid to get content of all tables +restrictedArea($user, $objecttmp->element, $id); $arrayresult = $form->selectForFormsList($objecttmp, $htmlname, '', 0, $searchkey, '', '', '', 0, 1); diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index bdd4eacc976..29aeb9cc7eb 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -48,7 +48,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; //global $hookmanager; $hookmanager->initHooks(array('searchform')); -$search_boxvalue = GETPOST('q', 'none'); +$search_boxvalue = GETPOST('q', 'restricthtml'); $arrayresult = array(); @@ -119,6 +119,17 @@ if ((! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFOR $arrayresult['searchintosupplierinvoice'] = array('position'=>120, 'img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('', 'object_supplier_invoice').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php'.($search_boxvalue ? '?sall='.urlencode($search_boxvalue) : '')); } +// Miscellaneous payments +if (!empty($conf->banque->enabled) && empty($conf->global->MAIN_SEARCHFORM_MISC_PAYMENTS_DISABLED) && $user->rights->banque->lire) +{ + $arrayresult['searchintomiscpayments'] = array( + 'position'=>180, + 'img'=>'object_payment', + 'label'=>$langs->trans("SearchIntoMiscPayments", $search_boxvalue), + 'text'=>img_picto('', 'object_payment').' '.$langs->trans("SearchIntoMiscPayments", $search_boxvalue), + 'url'=>DOL_URL_ROOT.'/compta/bank/various_payment/list.php?leftmenu=tax_various'.($search_boxvalue ? '&sall='.urlencode($search_boxvalue) : '')); +} + if (!empty($conf->contrat->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTRACT_DISABLED) && $user->rights->contrat->lire) { $arrayresult['searchintocontract'] = array('position'=>130, 'img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('', 'object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php'.($search_boxvalue ? '?sall='.urlencode($search_boxvalue) : '')); diff --git a/htdocs/core/ajax/vatrates.php b/htdocs/core/ajax/vatrates.php index b0ab6ed2a7e..0bd16eb6449 100644 --- a/htdocs/core/ajax/vatrates.php +++ b/htdocs/core/ajax/vatrates.php @@ -27,7 +27,7 @@ if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); require '../../main.inc.php'; $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $htmlname = GETPOST('htmlname', 'alpha'); $selected = (GETPOST('selected') ?GETPOST('selected') : '-1'); $productid = (GETPOST('productid', 'int') ?GETPOST('productid', 'int') : 0); diff --git a/htdocs/core/boxes/box_activity.php b/htdocs/core/boxes/box_activity.php index a59edbbf337..1585241b843 100644 --- a/htdocs/core/boxes/box_activity.php +++ b/htdocs/core/boxes/box_activity.php @@ -30,413 +30,413 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; */ class box_activity extends ModeleBoxes { - public $boxcode = "activity"; - public $boximg = "object_bill"; - public $boxlabel = 'BoxGlobalActivity'; - public $depends = array("facture"); + public $boxcode = "activity"; + public $boximg = "object_bill"; + public $boxlabel = 'BoxGlobalActivity'; + public $depends = array("facture"); - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - public $param; - public $enabled = 1; + public $param; + public $enabled = 1; - public $info_box_head = array(); - public $info_box_contents = array(); + public $info_box_head = array(); + public $info_box_contents = array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param string $param More parameters - */ - public function __construct($db, $param) - { - global $conf, $user; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param) + { + global $conf, $user; - $this->db = $db; + $this->db = $db; - // FIXME: Pb into some status - $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments) + // FIXME: Pb into some status + $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments) - $this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire) - || (!empty($conf->commande->enabled) && $user->rights->commande->lire) - || (!empty($conf->propal->enabled) && $user->rights->propale->lire) - ); - } + $this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire) + || (!empty($conf->commande->enabled) && $user->rights->commande->lire) + || (!empty($conf->propal->enabled) && $user->rights->propale->lire) + ); + } - /** - * Charge les donnees en memoire pour affichage ulterieur - * - * @param int $max Maximum number of records to load - * @return void - */ - public function loadBox($max = 5) - { - global $conf, $user, $langs; + /** + * Charge les donnees en memoire pour affichage ulterieur + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $totalnb = 0; - $line = 0; - $cachetime = 3600; - $fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache'; - $now = dol_now(); - $nbofperiod = 3; + $totalnb = 0; + $line = 0; + $cachetime = 3600; + $fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache'; + $now = dol_now(); + $nbofperiod = 3; - if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION; - $textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod); - $this->info_box_head = array( - 'text' => $textHead, - 'limit'=> dol_strlen($textHead), - ); + if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION; + $textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod); + $this->info_box_head = array( + 'text' => $textHead, + 'limit'=> dol_strlen($textHead), + ); - // compute the year limit to show - $tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m"); + // compute the year limit to show + $tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m"); - // list the summary of the propals - if (!empty($conf->propal->enabled) && $user->rights->propale->lire) - { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $propalstatic = new Propal($this->db); + // list the summary of the propals + if (!empty($conf->propal->enabled) && $user->rights->propale->lire) + { + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $propalstatic = new Propal($this->db); - $cachedir = DOL_DATA_ROOT.'/propale/temp'; - $filename = '/boxactivity-propal'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) - { - $sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE p.entity IN (".getEntity('propal').")"; - $sql .= " AND p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND p.datep >= '".$this->db->idate($tmpdate)."'"; - $sql .= " AND p.date_cloture IS NULL"; // just unclosed - $sql .= " GROUP BY p.fk_statut"; - $sql .= " ORDER BY p.fk_statut DESC"; + $cachedir = DOL_DATA_ROOT.'/propale/temp'; + $filename = '/boxactivity-propal'.$fileid; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); + if ($refresh) + { + $sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND p.datep >= '".$this->db->idate($tmpdate)."'"; + $sql .= " AND p.date_cloture IS NULL"; // just unclosed + $sql .= " GROUP BY p.fk_statut"; + $sql .= " ORDER BY p.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) - { - $j = 0; - while ($j < count($data)) - { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, - 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - 'logo' => 'object_propal' - ); + if (!empty($data)) + { + $j = 0; + while ($j < count($data)) + { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, + 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + 'logo' => 'object_propal' + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, - ); - $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, + ); + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3), - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3), + ); - $line++; - $j++; - } - } - } + $line++; + $j++; + } + } + } - // list the summary of the orders - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $commandestatic = new Commande($this->db); + // list the summary of the orders + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $commandestatic = new Commande($this->db); - $langs->load("orders"); + $langs->load("orders"); - $cachedir = DOL_DATA_ROOT.'/commande/temp'; - $filename = '/boxactivity-order'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); + $cachedir = DOL_DATA_ROOT.'/commande/temp'; + $filename = '/boxactivity-order'.$fileid; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); - if ($refresh) { - $sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE c.entity = ".$conf->entity; - $sql .= " AND c.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'"; - $sql .= " GROUP BY c.fk_statut"; - $sql .= " ORDER BY c.fk_statut DESC"; + if ($refresh) { + $sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE c.entity IN (".getEntity('commande').")"; + $sql .= " AND c.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'"; + $sql .= " GROUP BY c.fk_statut"; + $sql .= " ORDER BY c.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $j = 0; - while ($j < count($data)) { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, - 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - 'logo' => 'object_order', - ); + if (!empty($data)) { + $j = 0; + while ($j < count($data)) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, + 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + 'logo' => 'object_order', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' =>$langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' =>$langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, - ); - $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, + ); + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3), - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3), + ); - $line++; - $j++; - } - } - } + $line++; + $j++; + } + } + } - // list the summary of the bills - if (!empty($conf->facture->enabled) && $user->rights->facture->lire) - { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $facturestatic = new Facture($this->db); + // list the summary of the bills + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) + { + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $facturestatic = new Facture($this->db); - // part 1 - $cachedir = DOL_DATA_ROOT.'/facture/temp'; - $filename = '/boxactivity-invoice'.$fileid; + // part 1 + $cachedir = DOL_DATA_ROOT.'/facture/temp'; + $filename = '/boxactivity-invoice'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) - { - $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND f.fk_soc = s.rowid"; - $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1"; - $sql .= " GROUP BY f.fk_statut"; - $sql .= " ORDER BY f.fk_statut DESC"; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); + if ($refresh) + { + $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1"; + $sql .= " GROUP BY f.fk_statut"; + $sql .= " ORDER BY f.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $j = 0; - while ($j < count($data)) { - $billurl = "search_status=2&paye=1&year=".$data[$j]->annee; - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - 'logo' => 'bill', - ); + if (!empty($data)) { + $j = 0; + while ($j < count($data)) { + $billurl = "search_status=2&paye=1&year=".$data[$j]->annee; + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + 'logo' => 'bill', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee, - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee, + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), - 'text' => $data[$j]->nb, - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - ); + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), + 'text' => $data[$j]->nb, + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + ); - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency) - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency) + ); - // We add only for the current year - $totalnb += $data[$j]->nb; + // We add only for the current year + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3), - ); - $line++; - $j++; - } - if (count($data) == 0) - $this->info_box_contents[$line][0] = array( - 'td' => 'class="center"', - 'text'=>$langs->trans("NoRecordedInvoices"), - ); - } + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3), + ); + $line++; + $j++; + } + if (count($data) == 0) + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedInvoices"), + ); + } - // part 2 - $cachedir = DOL_DATA_ROOT.'/facture/temp'; - $filename = '/boxactivity-invoice2'.$fileid; + // part 2 + $cachedir = DOL_DATA_ROOT.'/facture/temp'; + $filename = '/boxactivity-invoice2'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) { - $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; - $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; - $sql .= " AND f.fk_soc = s.rowid"; - $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0"; - $sql .= " GROUP BY f.fk_statut"; - $sql .= " ORDER BY f.fk_statut DESC"; + $data = array(); + if ($refresh) { + $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0"; + $sql .= " GROUP BY f.fk_statut"; + $sql .= " ORDER BY f.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $alreadypaid = -1; + if (!empty($data)) { + $alreadypaid = -1; - $j = 0; - while ($j < count($data)) { - $billurl = "search_status=".$data[$j]->fk_statut."&paye=0"; - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - 'logo' => 'bill', - ); + $j = 0; + while ($j < count($data)) { + $billurl = "search_status=".$data[$j]->fk_statut."&paye=0"; + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + 'logo' => 'bill', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - ); - $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid), - ); - $line++; - $j++; - } - if (count($data) == 0) { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="center"', - 'text'=>$langs->trans("NoRecordedInvoices"), - ); - } - } - } + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + ); + $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid), + ); + $line++; + $j++; + } + if (count($data) == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedInvoices"), + ); + } + } + } // Add the sum in the bottom of the boxes $this->info_box_contents[$line][0] = array('tr' => 'class="liste_total_wrap"'); @@ -444,19 +444,19 @@ class box_activity extends ModeleBoxes $this->info_box_contents[$line][2] = array('td' => 'class="liste_total right" ', 'text' => $totalnb); $this->info_box_contents[$line][3] = array('td' => 'class="liste_total right" ', 'text' => ''); $this->info_box_contents[$line][4] = array('td' => 'class="liste_total right" ', 'text' => ""); - } + } - /** - * 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); - } + /** + * 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_commandes.php b/htdocs/core/boxes/box_commandes.php index 7ec5071b6e3..90729b96017 100644 --- a/htdocs/core/boxes/box_commandes.php +++ b/htdocs/core/boxes/box_commandes.php @@ -105,7 +105,7 @@ class box_commandes extends ModeleBoxes $sql .= ", ".MAIN_DB_PREFIX."commande as c"; if (!$user->rights->societe->client->voir && !$user->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.entity IN (".getEntity('commande').")"; if (!empty($conf->global->ORDER_BOX_LAST_ORDERS_VALIDATED_ONLY)) $sql .= " AND c.fk_statut = 1"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index caea252c571..7141728c23d 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -94,7 +94,7 @@ class box_contacts extends ModeleBoxes $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON sp.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND sp.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; if ($user->socid) $sql .= " AND sp.fk_soc = ".$user->socid; $sql .= " ORDER BY sp.tms DESC"; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index fbf1874a132..957277005e7 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -133,66 +133,6 @@ class box_graph_product_distribution extends ModeleBoxes $WIDTH = ($nbofgraph >= 2 || !empty($conf->dol_optimize_smallscreen)) ? '160' : '320'; $HEIGHT = '192'; - if (!empty($conf->facture->enabled) && !empty($user->rights->facture->lire)) - { - // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) - if ($showinvoicenb) - { - $langs->load("bills"); - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facturestats.class.php'; - - $showpointvalue = 1; $nocolor = 0; - $mode = 'customer'; - $stats_invoice = new FactureStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); - $data1 = $stats_invoice->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); - - if (empty($data1)) - { - $showpointvalue = 0; - $nocolor = 1; - $data1 = array(array(0=>$langs->trans("None"), 1=>1)); - } - $filenamenb = $dir."/prodserforinvoice-".$year.".png"; - $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=productstats&file=prodserforinvoice-'.$year.'.png'; - - $px1 = new DolGraph(); - $mesg = $px1->isGraphKo(); - if (!$mesg) - { - $i = 0; $legend = array(); - - foreach ($data1 as $key => $val) - { - $data1[$key][0] = dol_trunc($data1[$key][0], 32); - $legend[] = $data1[$key][0]; - $i++; - } - - $px1->SetData($data1); - unset($data1); - - if ($nocolor) $px1->SetDataColor(array(array(220, 220, 220))); - $px1->SetLegend($legend); - $px1->setShowLegend(2); - $px1->setShowPointValue($showpointvalue); - $px1->setShowPercent(0); - $px1->SetMaxValue($px1->GetCeilMaxValue()); - //$px1->SetWidth($WIDTH); - $px1->SetHeight($HEIGHT); - //$px1->SetYLabel($langs->trans("NumberOfBills")); - $px1->SetShading(3); - $px1->SetHorizTickIncrement(1); - $px1->SetCssPrefix("cssboxes"); - //$px1->mode='depth'; - $px1->SetType(array('pie')); - $px1->SetTitle($langs->trans("ForObject", $langs->transnoentitiesnoconv("Invoices"))); - $px1->combine = 0.05; - - $px1->draw($filenamenb, $fileurlnb); - } - } - } - if (!empty($conf->propal->enabled) && !empty($user->rights->propale->lire)) { // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) @@ -312,6 +252,67 @@ class box_graph_product_distribution extends ModeleBoxes } } + + if (!empty($conf->facture->enabled) && !empty($user->rights->facture->lire)) + { + // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) + if ($showinvoicenb) + { + $langs->load("bills"); + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facturestats.class.php'; + + $showpointvalue = 1; $nocolor = 0; + $mode = 'customer'; + $stats_invoice = new FactureStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); + $data1 = $stats_invoice->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); + + if (empty($data1)) + { + $showpointvalue = 0; + $nocolor = 1; + $data1 = array(array(0=>$langs->trans("None"), 1=>1)); + } + $filenamenb = $dir."/prodserforinvoice-".$year.".png"; + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=productstats&file=prodserforinvoice-'.$year.'.png'; + + $px1 = new DolGraph(); + $mesg = $px1->isGraphKo(); + if (!$mesg) + { + $i = 0; $legend = array(); + + foreach ($data1 as $key => $val) + { + $data1[$key][0] = dol_trunc($data1[$key][0], 32); + $legend[] = $data1[$key][0]; + $i++; + } + + $px1->SetData($data1); + unset($data1); + + if ($nocolor) $px1->SetDataColor(array(array(220, 220, 220))); + $px1->SetLegend($legend); + $px1->setShowLegend(2); + $px1->setShowPointValue($showpointvalue); + $px1->setShowPercent(0); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + //$px1->SetWidth($WIDTH); + $px1->SetHeight($HEIGHT); + //$px1->SetYLabel($langs->trans("NumberOfBills")); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + //$px1->mode='depth'; + $px1->SetType(array('pie')); + $px1->SetTitle($langs->trans("ForObject", $langs->transnoentitiesnoconv("Invoices"))); + $px1->combine = 0.05; + + $px1->draw($filenamenb, $fileurlnb); + } + } + } + if (empty($nbofgraph)) { $langs->load("errors"); @@ -339,11 +340,6 @@ class box_graph_product_distribution extends ModeleBoxes $stringtoshow .= ''; $stringtoshow .= ''; $stringtoshow .= ''; - if (!empty($conf->facture->enabled) || !empty($user->rights->facture->lire)) - { - $stringtoshow .= ' '.$langs->trans("ForCustomersInvoices"); - $stringtoshow .= '   '; - } if (!empty($conf->propal->enabled) || !empty($user->rights->propale->lire)) { $stringtoshow .= ' '.$langs->trans("ForProposals"); @@ -353,6 +349,11 @@ class box_graph_product_distribution extends ModeleBoxes { $stringtoshow .= ' '.$langs->trans("ForCustomersOrders"); } + if (!empty($conf->facture->enabled) || !empty($user->rights->facture->lire)) + { + $stringtoshow .= ' '.$langs->trans("ForCustomersInvoices"); + $stringtoshow .= '   '; + } $stringtoshow .= '
'; $stringtoshow .= $langs->trans("Year").' '; $stringtoshow .= ''; @@ -361,29 +362,29 @@ class box_graph_product_distribution extends ModeleBoxes if ($nbofgraph == 1) { - if ($showinvoicenb) $stringtoshow .= $px1->show(); - elseif ($showpropalnb) $stringtoshow .= $px2->show(); - else $stringtoshow .= $px3->show(); + if ($showpropalnb) $stringtoshow .= $px2->show(); + elseif ($showordernb) $stringtoshow .= $px3->show(); + else $stringtoshow .= $px1->show(); } if ($nbofgraph == 2) { $stringtoshow .= '
'; - if ($showinvoicenb) $stringtoshow .= $px1->show(); - elseif ($showpropalnb) $stringtoshow .= $px2->show(); + if ($showpropalnb) $stringtoshow .= $px2->show(); + elseif ($showordernb) $stringtoshow .= $px3->show(); $stringtoshow .= '
'; - if ($showordernb) $stringtoshow .= $px3->show(); - elseif ($showpropalnb) $stringtoshow .= $px2->show(); + if ($showinvoicenb) $stringtoshow .= $px1->show(); + elseif ($showordernb) $stringtoshow .= $px3->show(); $stringtoshow .= '
'; } if ($nbofgraph == 3) { $stringtoshow .= '
'; - $stringtoshow .= $px1->show(); - $stringtoshow .= '
'; $stringtoshow .= $px2->show(); + $stringtoshow .= '
'; + $stringtoshow .= $px3->show(); $stringtoshow .= '
'; $stringtoshow .= '
'; - $stringtoshow .= $px3->show(); + $stringtoshow .= $px1->show(); $stringtoshow .= '
'; } $this->info_box_contents[0][0] = array( diff --git a/htdocs/core/boxes/box_produits.php b/htdocs/core/boxes/box_produits.php index 8dffe4adf20..52591fa5292 100644 --- a/htdocs/core/boxes/box_produits.php +++ b/htdocs/core/boxes/box_produits.php @@ -117,7 +117,7 @@ class box_produits extends ModeleBoxes $sqld = "SELECT label"; $sqld .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sqld .= " WHERE fk_product=".$objp->rowid; - $sqld .= " AND lang='".$langs->getDefaultLang()."'"; + $sqld .= " AND lang='".$this->db->escape($langs->getDefaultLang())."'"; $sqld .= " LIMIT 1"; $resultd = $this->db->query($sqld); diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php index 5b17ef22ddf..6845cb2db5f 100644 --- a/htdocs/core/boxes/box_produits_alerte_stock.php +++ b/htdocs/core/boxes/box_produits_alerte_stock.php @@ -130,7 +130,7 @@ class box_produits_alerte_stock extends ModeleBoxes $sqld = "SELECT label"; $sqld .= " FROM ".MAIN_DB_PREFIX."product_lang"; $sqld .= " WHERE fk_product=".$objp->rowid; - $sqld .= " AND lang='".$langs->getDefaultLang()."'"; + $sqld .= " AND lang='".$this->db->escape($langs->getDefaultLang())."'"; $sqld .= " LIMIT 1"; $resultd = $this->db->query($sqld); diff --git a/htdocs/core/boxes/box_propales.php b/htdocs/core/boxes/box_propales.php index 979723753a0..331ff54cb8d 100644 --- a/htdocs/core/boxes/box_propales.php +++ b/htdocs/core/boxes/box_propales.php @@ -91,7 +91,7 @@ class box_propales extends ModeleBoxes $sql .= ", ".MAIN_DB_PREFIX."propal as p"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE p.fk_soc = s.rowid"; - $sql .= " AND p.entity = ".$conf->entity; + $sql .= " AND p.entity IN (".getEntity('propal').")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY p.datep DESC, p.ref DESC "; diff --git a/htdocs/core/boxes/box_services_contracts.php b/htdocs/core/boxes/box_services_contracts.php index aae8e0356d0..d528a4d68ca 100644 --- a/htdocs/core/boxes/box_services_contracts.php +++ b/htdocs/core/boxes/box_services_contracts.php @@ -90,7 +90,7 @@ class box_services_contracts extends ModeleBoxes $sql = "SELECT s.nom as name, s.rowid as socid, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,"; $sql .= " c.rowid, c.ref, c.statut as contract_status, c.ref_customer, c.ref_supplier,"; - $sql .= " cd.rowid as cdid, cd.label, cd.description, cd.tms as datem, cd.statut, cd.product_type as type, cd.date_fin_validite as date_line,"; + $sql .= " cd.rowid as cdid, cd.label, cd.description, cd.tms as datem, cd.statut as contractline_status, cd.product_type as type, cd.date_fin_validite as date_line,"; $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as plabel, p.fk_product_type as ptype, p.entity, p.tobuy, p.tosell"; $sql .= " FROM (".MAIN_DB_PREFIX."societe as s"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."contrat as c ON s.rowid = c.fk_soc"; @@ -125,6 +125,7 @@ class box_services_contracts extends ModeleBoxes $contractlinestatic->type = $objp->type; $contractlinestatic->product_id = $objp->product_id; $contractlinestatic->product_ref = $objp->product_ref; + $contractlinestatic->statut = $objp->contractline_status; $contractstatic->id = $objp->rowid; $contractstatic->ref = $objp->ref; @@ -143,24 +144,7 @@ class box_services_contracts extends ModeleBoxes $thirdpartytmp->code_compta_fournisseur = $objp->code_compta_fournisseur; $dateline = $this->db->jdate($objp->date_line); - if ($contractstatic->statut == Contrat::STATUS_VALIDATED && $objp->statut == ContratLigne::STATUS_OPEN && !empty($dateline) && ($dateline + $conf->contrat->services->expires->warning_delay) < $now) $late = img_warning($langs->trans("Late")); - - // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS) && $objp->product_id > 0) // if option multilang is on - { - $sqld = "SELECT label"; - $sqld .= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sqld .= " WHERE fk_product=".$objp->product_id; - $sqld .= " AND lang='".$langs->getDefaultLang()."'"; - $sqld .= " LIMIT 1"; - - $resultd = $this->db->query($sqld); - if ($resultd) - { - $objtp = $this->db->fetch_object($resultd); - if ($objtp->label != '') $contractlinestatic->label = $objtp->label; - } - } + if ($contractstatic->statut == Contrat::STATUS_VALIDATED && $objp->contractline_status == ContratLigne::STATUS_OPEN && !empty($dateline) && ($dateline + $conf->contrat->services->expires->warning_delay) < $now) $late = img_warning($langs->trans("Late")); // Label if ($objp->product_id > 0) @@ -190,7 +174,7 @@ class box_services_contracts extends ModeleBoxes $description = ''; // Already added into main visible desc } - $s = $form->textwithtooltip($text, $description, 3, '', '', $cursorline, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : '')); + $s = $form->textwithtooltip($text, $description, 3, '', '', '', 0, (!empty($objp->fk_parent_line) ?img_picto('', 'rightarrow') : '')); } else { $s = img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description); } @@ -222,7 +206,7 @@ class box_services_contracts extends ModeleBoxes $this->info_box_contents[$i][] = array( 'td' => 'class="right" width="18"', - 'text' => $contractlinestatic->LibStatut($objp->statut, 3) + 'text' => $contractlinestatic->getLibStatut(3) ); $i++; diff --git a/htdocs/core/boxes/box_shipments.php b/htdocs/core/boxes/box_shipments.php index 61942d03f45..8574b7ce01b 100644 --- a/htdocs/core/boxes/box_shipments.php +++ b/htdocs/core/boxes/box_shipments.php @@ -104,7 +104,7 @@ class box_shipments extends ModeleBoxes $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 && !$user->socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; - $sql .= " WHERE e.entity = ".$conf->entity; + $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; if (!empty($conf->global->ORDER_BOX_LAST_SHIPMENTS_VALIDATED_ONLY)) $sql .= " AND e.fk_statut = 1"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND sc.fk_user = ".$user->id; else $sql .= " ORDER BY e.date_delivery, e.ref DESC "; diff --git a/htdocs/core/boxes/box_supplier_orders.php b/htdocs/core/boxes/box_supplier_orders.php index 5ba940f2af2..cdc1dd51440 100644 --- a/htdocs/core/boxes/box_supplier_orders.php +++ b/htdocs/core/boxes/box_supplier_orders.php @@ -95,7 +95,7 @@ class box_supplier_orders extends ModeleBoxes $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; if (!$user->rights->societe->client->voir && !$user->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.entity IN (".getEntity('supplier_order').")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY c.date_commande DESC, c.ref DESC "; diff --git a/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php b/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php index 952e0b78d92..54b8955d519 100644 --- a/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php +++ b/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php @@ -95,8 +95,7 @@ class box_supplier_orders_awaiting_reception extends ModeleBoxes $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; if (!$user->rights->societe->client->voir && !$user->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.entity IN (".getEntity('supplier_order').")"; $sql .= " AND c.fk_statut = ".CommandeFournisseur::STATUS_ORDERSENT; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; diff --git a/htdocs/core/boxes/box_task.php b/htdocs/core/boxes/box_task.php index 55557cd355a..c1d728eb667 100644 --- a/htdocs/core/boxes/box_task.php +++ b/htdocs/core/boxes/box_task.php @@ -94,7 +94,7 @@ class box_task extends ModeleBoxes if (in_array(GETPOST($cookie_name), array('all', 'im_project_contact', 'im_task_contact'))) { $filterValue = GETPOST($cookie_name); } elseif (!empty($_COOKIE[$cookie_name])) { - $filterValue = $_COOKIE[$cookie_name]; + $filterValue = preg_replace('/[^a-z_]/', '', $_COOKIE[$cookie_name]); // Clean cookie from evil data } if ($filterValue == 'im_task_contact') { @@ -154,10 +154,10 @@ class box_task extends ModeleBoxes $sql .= " JOIN ".MAIN_DB_PREFIX."projet as p ON (pt.fk_projet = p.rowid)"; if ($filterValue === 'im_task_contact') { - $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = '".$user->id."' )"; + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )"; } elseif ($filterValue === 'im_project_contact') { - $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = '".$user->id."' )"; + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )"; } @@ -189,7 +189,7 @@ class box_task extends ModeleBoxes $projectstatic->ref = $objp->project_ref; $projectstatic->title = $objp->project_title; - $label = $projectstatic->getNomUrl(1).' '.$taskstatic->getNomUrl(1).' '.dol_htmlentities($taskstatic->label); + $label = $projectstatic->getNomUrl(1).'   '.$taskstatic->getNomUrl(1).' '.dol_htmlentities($taskstatic->label); $boxcontent = getTaskProgressView($taskstatic, $label, true, false, false); diff --git a/htdocs/core/boxes/box_validated_projects.php b/htdocs/core/boxes/box_validated_projects.php new file mode 100644 index 00000000000..378aea61df5 --- /dev/null +++ b/htdocs/core/boxes/box_validated_projects.php @@ -0,0 +1,195 @@ + + * Copyright (C) 2014 Marcos García + * Copyright (C) 2015 Frederic France + * Copyright (C) 2016 Juan José Menent + * Copyright (C) 2020 Pierre Ardoin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_validated_projects.php + * \ingroup projet + * \brief Module to show validated projects whose tasks are assigned to the connected person, without any time entered by the connected person + */ +include_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box to show last projet + */ +class box_validated_projects extends ModeleBoxes +{ + public $boxcode="validated_project"; + public $boximg="object_projectpub"; + public $boxlabel; + //var $depends = array("projet"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + + public $info_box_head = array(); + public $info_box_contents = array(); + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $user, $langs; + + // Load translation files required by the page + $langs->loadLangs(array('boxes', 'projects')); + + $this->db = $db; + $this->boxlabel = "ValidatedProjects"; + + $this->hidden = ! ($user->rights->projet->lire); + } + + /** + * Load data for box to show them later + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; + + $this->max=$max; + + $totalMnt = 0; + $totalnb = 0; + $totalnbTask=0; + + $textHead = $langs->trans("ValidatedProjects"); + $this->info_box_head = array('text' => $textHead, 'limit'=> dol_strlen($textHead)); + + // list the summary of the orders + if ($user->rights->projet->lire) { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + $projectstatic = new Project($this->db); + + $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. + + // Get list of project id allowed to user (in a string list separated by coma) + $projectsListId=''; + if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); + + $sql = "SELECT p.rowid, p.ref as Ref, p.fk_soc as Client, p.dateo as startDate,"; + $sql.= " (SELECT COUNT(t.rowid) FROM ".MAIN_DB_PREFIX."projet_task AS t"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact AS c ON t.rowid = c.element_id"; + $sql.= " WHERE t.fk_projet = p.rowid AND c.fk_c_type_contact != 160 AND c.fk_socpeople = ".$user->id." AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")) AS 'taskNumber'"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet AS p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task AS t ON p.rowid = t.fk_projet"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact AS c ON t.rowid = c.element_id"; + $sql.= " WHERE p.fk_statut = 1"; // Only open projects + $sql.= " AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")"; + $sql.= " AND c.fk_socpeople = ".$user->id; + $sql.= " GROUP BY p.ref"; + $sql.= " ORDER BY p.dateo ASC"; + + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + $this->info_box_contents[$i][] = array( + 'td' => 'class="nowraponall"', + 'text' => "Reference projet", + ); + $this->info_box_contents[$i][] = array( + 'td' => 'class="center"', + 'text' => 'Client', + ); + $this->info_box_contents[$i][] = array( + 'td' => 'class="center"', + 'text' => 'Date debut de projet', + ); + $this->info_box_contents[$i][] = array( + 'td' => 'class="center"', + 'text' => 'Nombre de mes tâches sans temps saisi', + ); + $i++; + + while ($i < min($num+1, $max+1)) { + $objp = $this->db->fetch_object($result); + + $projectstatic->id = $objp->rowid; + $projectstatic->ref = $objp->Ref; + $projectstatic->customer = $objp->Client; + $projectstatic->startDate = $objp->startDate; + $projectstatic->taskNumber = $objp->taskNumber; + + $this->info_box_contents[$i][] = array( + 'td' => 'class="nowraponall"', + 'text' => $projectstatic->getNomUrl(1), + 'asis' => 1 + ); + + $sql = 'SELECT rowid, nom FROM '.MAIN_DB_PREFIX.'societe WHERE rowid ='.$objp->Client; + $resql = $this->db->query($sql); + if ($resql){ + $socstatic = new Societe($this->db); + $obj = $this->db->fetch_object($resql); + $this->info_box_contents[$i][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth200onsmartphone"', + 'text' => $obj->nom, + 'asis' => 1, + 'url' => DOL_URL_ROOT.'/societe/card.php?socid='.$obj->rowid + ); + } + else { + dol_print_error($this->db); + } + + $this->info_box_contents[$i][] = array( + 'td' => 'class="center"', + 'text' => $objp->startDate, + ); + + $this->info_box_contents[$i][] = array( + 'td' => 'class="center"', + 'text' => $objp->taskNumber." ".$langs->trans("Tasks"), + 'asis' => 1, + ); + $i++; + } + }else { + dol_print_error($this->db); + } + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index e5fa9d8fb0d..fd179dec7b6 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -143,10 +143,10 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box global $conf; // Recupere liste des boites d'un user si ce dernier a sa propre liste - $sql = "SELECT b.rowid, b.box_id, b.position, b.box_order, b.fk_user"; + $sql = "SELECT b.rowid as id, b.box_id, b.position, b.box_order, b.fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."boxes as b"; $sql .= " WHERE b.entity = ".$conf->entity; - $sql .= " AND b.rowid = ".$rowid; + $sql .= " AND b.rowid = ".((int) $rowid); dol_syslog(get_class($this)."::fetch rowid=".$rowid); $resql = $this->db->query($sql); @@ -155,7 +155,8 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box $obj = $this->db->fetch_object($resql); if ($obj) { - $this->rowid = $obj->rowid; + $this->id = $obj->id; + $this->rowid = $obj->id; // For backward compatibility $this->box_id = $obj->box_id; $this->position = $obj->position; $this->box_order = $obj->box_order; @@ -169,29 +170,6 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box } } - - /** - * Standard method to get content of a box - * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * - * @return string - */ - public function outputBox($head = null, $contents = null) - { - global $langs, $user, $conf; - - // Trick to get result into a var from a function that makes print instead of return - // TODO Replace ob_start with param nooutput=1 into showBox - ob_start(); - $result = $this->showBox($head, $contents); - $output = ob_get_contents(); - ob_end_clean(); - - return $output; - } - /** * Standard method to show a box (usage by boxes not mandatory, a box can still use its own showBox function) * @@ -422,6 +400,7 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box { while (($file = readdir($handle)) !== false) { + $reg = array(); if (is_readable($newdir.'/'.$file) && preg_match('/^(.+)\.php/', $file, $reg)) { if (preg_match('/\.back$/', $file)) continue; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index bca09cb967e..bb8086f9b90 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -32,7 +32,7 @@ /** * Class to send emails (with attachments or not) - * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext); + * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); * $mailfile->sendfile(); */ class CMailFile @@ -41,47 +41,47 @@ class CMailFile public $sendmode; public $sendsetup; - public $subject; // Topic: Subject of email - public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). + public $subject; // Topic: Subject of email + public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). // Sender: Who send the email ("Sender" has sent emails on behalf of "From"). // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain. // Return-Path: Email where to send bounds. - public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) - public $errors_to; // Errors-To: Email where to send errors. - public $addr_to; - public $addr_cc; - public $addr_bcc; - public $trackid; + public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined) + public $errors_to; // Errors-To: Email where to send errors. + public $addr_to; + public $addr_cc; + public $addr_bcc; + public $trackid; - public $mixed_boundary; - public $related_boundary; - public $alternative_boundary; - public $deliveryreceipt; + public $mixed_boundary; + public $related_boundary; + public $alternative_boundary; + public $deliveryreceipt; - public $eol; - public $eol2; + public $eol; + public $eol2; /** * @var string Error code (or message) */ public $error = ''; - public $smtps; // Contains SMTPs object (if this method is used) - public $phpmailer; // Contains PHPMailer object (if this method is used) + public $smtps; // Contains SMTPs object (if this method is used) + public $phpmailer; // Contains PHPMailer object (if this method is used) /** * @var string CSS */ public $css; //! Defined css style for body background - public $styleCSS; + public $styleCSS; //! Defined background directly in body tag - public $bodyCSS; + public $bodyCSS; - public $msgid; - public $headers; - public $message; - /** + public $msgid; + public $headers; + public $message; + /** * @var array fullfilenames list (full path of filename on file system) */ public $filename_list = array(); @@ -95,21 +95,21 @@ class CMailFile public $mimefilename_list = array(); // Image - public $html; - public $image_boundary; - public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). - public $html_images = array(); - public $images_encoded = array(); - public $image_types = array( - 'gif' => 'image/gif', + public $html; + public $image_boundary; + public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). + public $html_images = array(); + public $images_encoded = array(); + public $image_types = array( + 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'bmp' => 'image/bmp', 'png' => 'image/png', 'tif' => 'image/tiff', - 'tiff' => 'image/tiff', - ); + 'tiff' => 'image/tiff', + ); /** @@ -147,7 +147,7 @@ class CMailFile // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; - $this->subject = $subject; + $this->subject = $subject; $this->addr_to = $to; $this->addr_from = $from; $this->msg = $msg; @@ -168,9 +168,13 @@ class CMailFile // Define this->sendmode $this->sendmode = ''; - if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') - { - $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING; + if (!empty($this->sendcontext)) { + $smtpContextKey = strtoupper($this->sendcontext); + $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; + $smtpContextSendMode = $conf->global->{$keyForSMTPSendMode}; + if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { + $this->sendmode = $smtpContextSendMode; + } } if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE; if (empty($this->sendmode)) $this->sendmode = 'mail'; @@ -195,7 +199,7 @@ class CMailFile // On defini alternative_boundary $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) - dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); + dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); if (empty($subject)) @@ -206,8 +210,8 @@ class CMailFile } if (empty($msg)) { - dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); - $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure) + dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); + $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure) } // Detect if message is HTML (use fast method) @@ -287,7 +291,17 @@ class CMailFile // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) { - $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + } + + $keyforsslseflsigned ='MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; + if (!empty($this->sendcontext)) { + $smtpContextKey = strtoupper($this->sendcontext); + $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_' . $smtpContextKey; + $smtpContextSendMode = $conf->global->{$keyForSMTPSendMode}; + if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { + $keyforsslseflsigned ='MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_' . $smtpContextKey; + } } // We set all data according to choosed sending method. @@ -358,7 +372,7 @@ class CMailFile $smtps->setTO($this->getValidAddress($this->addr_to, 0, 1)); $smtps->setFrom($this->getValidAddress($this->addr_from, 0, 1)); $smtps->setTrackId($this->trackid); - $smtps->setReplyTo($this->getValidAddress($this->replyto, 0, 1)); + $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1)); if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); @@ -400,6 +414,7 @@ class CMailFile $smtps->setBCC($this->addr_bcc); $smtps->setErrorsTo($this->errors_to); $smtps->setDeliveryReceipt($this->deliveryreceipt); + if (!empty($conf->global->$keyforsslseflsigned)) $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true))); $host = dol_getprefix('email'); $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host; @@ -407,41 +422,41 @@ class CMailFile $this->smtps = $smtps; } elseif ($this->sendmode == 'swiftmailer') { // Use Swift Mailer library - $host = dol_getprefix('email'); + $host = dol_getprefix('email'); - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; - // egulias autoloader lib - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php'; + // egulias autoloader lib + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; - // Create the message - //$this->message = Swift_Message::newInstance(); - $this->message = new Swift_Message(); - //$this->message = new Swift_SignedMessage(); - // Adding a trackid header to a message - $headers = $this->message->getHeaders(); - $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host); - $this->msgid = time().'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host; - $headerID = $this->msgid; - $msgid = $headers->get('Message-ID'); - $msgid->setId($headerID); - $headers->addIdHeader('References', $headerID); - // TODO if (! empty($moreinheader)) ... + // Create the message + //$this->message = Swift_Message::newInstance(); + $this->message = new Swift_Message(); + //$this->message = new Swift_SignedMessage(); + // Adding a trackid header to a message + $headers = $this->message->getHeaders(); + $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host); + $this->msgid = time().'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host; + $headerID = $this->msgid; + $msgid = $headers->get('Message-ID'); + $msgid->setId($headerID); + $headers->addIdHeader('References', $headerID); + // TODO if (! empty($moreinheader)) ... - // Give the message a subject - try { - $result = $this->message->setSubject($this->subject); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } + // Give the message a subject + try { + $result = $this->message->setSubject($this->subject); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } - // Set the From address with an associative array - //$this->message->setFrom(array('john@doe.com' => 'John Doe')); - if (! empty($this->addr_from)) { - try { - if (! empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) { + // Set the From address with an associative array + //$this->message->setFrom(array('john@doe.com' => 'John Doe')); + if (!empty($this->addr_from)) { + try { + if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) { // Prevent email spoofing for smtp server with a strict configuration $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom); @@ -455,35 +470,35 @@ class CMailFile } else { $result = $this->message->setFrom($this->getArrayAddress($this->addr_from)); } - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - // Set the To addresses with an associative array - if (! empty($this->addr_to)) { - try { - $result = $this->message->setTo($this->getArrayAddress($this->addr_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } + // Set the To addresses with an associative array + if (!empty($this->addr_to)) { + try { + $result = $this->message->setTo($this->getArrayAddress($this->addr_to)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - if (! empty($this->reply_to)) { - try { - $result = $this->message->SetReplyTo($this->getArrayAddress($this->reply_to)); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } + if (!empty($this->reply_to)) { + try { + $result = $this->message->SetReplyTo($this->getArrayAddress($this->reply_to)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - try { - $result = $this->message->setCharSet($conf->file->character_set_client); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } + try { + $result = $this->message->setCharSet($conf->file->character_set_client); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } - if (!empty($this->html)) { + if (!empty($this->html)) { if (!empty($css)) { $this->css = $css; $this->buildCSS(); @@ -521,13 +536,16 @@ class CMailFile { //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i])); $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]); + if (!empty($mimefilename_list[$i])) { + $attachment->setFilename($mimefilename_list[$i]); + } $this->message->attach($attachment); } } - if (! empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); - if (! empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); - //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to); + if (!empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); + if (!empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); + //if (! empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to)); if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); } else { // Send mail method not correctly defined @@ -574,26 +592,26 @@ class CMailFile $sendingmode = $this->sendmode; if ($this->context == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') { - // List of sending methods - $listofmethods = array(); - $listofmethods['mail'] = 'PHP mail function'; - //$listofmethods['simplemail']='Simplemail class'; - $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; + // List of sending methods + $listofmethods = array(); + $listofmethods['mail'] = 'PHP mail function'; + //$listofmethods['simplemail']='Simplemail class'; + $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; - // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. - // You ensure that every user is using its own SMTP server when using the mass emailing module. - $linktoadminemailbefore = ''; - $linktoadminemailend = ''; - $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); - $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); - $this->error .= '
'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) - { - $this->error .= '
'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); - $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); - } - return false; + // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. + // You ensure that every user is using its own SMTP server when using the mass emailing module. + $linktoadminemailbefore = ''; + $linktoadminemailend = ''; + $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); + $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); + $this->error .= '
'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); + $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); + if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) + { + $this->error .= '
'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); + $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); + } + return false; } // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL @@ -635,14 +653,20 @@ class CMailFile $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW'; $keyfortls = 'MAIN_MAIL_EMAIL_TLS'; $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; - if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') - { - $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING'; - $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_EMAILING'; - $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_EMAILING'; - $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_EMAILING'; - $keyfortls = 'MAIN_MAIL_EMAIL_TLS_EMAILING'; - $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; + $keyforsslseflsigned ='MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED'; + if (!empty($this->sendcontext)) { + $smtpContextKey = strtoupper($this->sendcontext); + $keyForSMTPSendMode = 'MAIN_MAIL_SENDMODE_'.$smtpContextKey; + $smtpContextSendMode = $conf->global->{$keyForSMTPSendMode}; + if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') { + $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_' . $smtpContextKey; + $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_' . $smtpContextKey; + $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_' . $smtpContextKey; + $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_' . $smtpContextKey; + $keyfortls = 'MAIN_MAIL_EMAIL_TLS_' . $smtpContextKey; + $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_' . $smtpContextKey; + $keyforsslseflsigned ='MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_' . $smtpContextKey; + } } // Action according to choosed sending method @@ -820,9 +844,9 @@ class CMailFile } } elseif ($this->sendmode == 'swiftmailer') { - // Use Swift Mailer library - // ------------------------------------------ - require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; + // Use Swift Mailer library + // ------------------------------------------ + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Clean parameters if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); @@ -838,25 +862,26 @@ class CMailFile if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); + if (! empty($conf->global->$keyforsslseflsigned)) $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false)));; //$smtps->_msgReplyTo = 'reply@web.com'; // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable - $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); - $this->message->setEncoder($contentEncoderBase64); + $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + $this->message->setEncoder($contentEncoderBase64); // Create the Mailer using your created Transport $this->mailer = new Swift_Mailer($this->transport); - // DKIM SIGN - if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { - $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; - $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; - $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; - $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); - $this->message->attachSigner($signer->ignoreHeader('Return-Path')); - } + // DKIM SIGN + if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); + $this->message->attachSigner($signer->ignoreHeader('Return-Path')); + } - if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger @@ -916,7 +941,7 @@ class CMailFile return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?='; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Read a file on disk and return encoded content for emails (mode = 'mail') * @@ -925,7 +950,7 @@ class CMailFile */ private function _encode_file($sourcefile) { - // phpcs:enable + // phpcs:enable $newsourcefile = dol_osencode($sourcefile); if (is_readable($newsourcefile)) @@ -941,7 +966,7 @@ class CMailFile } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Write content of a SMTP request into a dump file (mode = all) * Used for debugging. @@ -951,7 +976,7 @@ class CMailFile */ public function dump_mail() { - // phpcs:enable + // phpcs:enable global $conf, $dolibarr_main_data_root; if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir @@ -1032,7 +1057,7 @@ class CMailFile } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Create SMTP headers (mode = 'mail') * @@ -1040,7 +1065,7 @@ class CMailFile */ public function write_smtpheaders() { - // phpcs:enable + // phpcs:enable global $conf; $out = ""; @@ -1096,7 +1121,7 @@ class CMailFile } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Create header MIME (mode = 'mail') * @@ -1106,7 +1131,7 @@ class CMailFile */ public function write_mimeheaders($filename_list, $mimefilename_list) { - // phpcs:enable + // phpcs:enable $mimedone = 0; $out = ""; @@ -1127,7 +1152,7 @@ class CMailFile return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return email content (mode = 'mail') * @@ -1136,7 +1161,7 @@ class CMailFile */ public function write_body($msgtext) { - // phpcs:enable + // phpcs:enable global $conf; $out = ''; @@ -1227,7 +1252,7 @@ class CMailFile return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Attach file to email (mode = 'mail') * @@ -1238,7 +1263,7 @@ class CMailFile */ public function write_files($filename_list, $mimetype_list, $mimefilename_list) { - // phpcs:enable + // phpcs:enable $out = ''; $filename_list_size = count($filename_list); @@ -1274,7 +1299,7 @@ class CMailFile } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Attach an image to email (mode = 'mail') * @@ -1283,7 +1308,7 @@ class CMailFile */ public function write_images($images_list) { - // phpcs:enable + // phpcs:enable $out = ''; if (is_array($images_list)) @@ -1307,7 +1332,7 @@ class CMailFile } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Try to create a socket connection * @@ -1317,7 +1342,7 @@ class CMailFile */ public function check_server_port($host, $port) { - // phpcs:enable + // phpcs:enable global $conf; $_retVal = 0; @@ -1348,7 +1373,7 @@ class CMailFile dol_syslog("Try socket connection to host=".$host." port=".$port); //See if we can connect to the SMTP server - if ($socket = @fsockopen( + if ($socket = @fsockopen( $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. $port, // which Port number to use $errno, // actual system level error @@ -1369,7 +1394,7 @@ class CMailFile return $_retVal; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * This function has been modified as provided by SirSir to allow multiline responses when * using SMTP Extensions. @@ -1380,7 +1405,7 @@ class CMailFile */ public function server_parse($socket, $response) { - // phpcs:enable + // phpcs:enable $_retVal = true; // Indicates if Object was created or not $server_response = ''; @@ -1504,8 +1529,8 @@ class CMailFile * If format 2: 'john@doe.com' * If format 3: '' or '"John Doe" ' or '"=?UTF-8?B?Sm9obiBEb2U=?=" ' * If format 4: 'John Doe' or 'john@doe.com' if no label exists - * If format 5: John Doe or john@doe.com if no label exists - * @see getArrayAddress() + * If format 5: John Doe or john@doe.com if no label exists + * @see getArrayAddress() */ public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0) { @@ -1519,6 +1544,7 @@ class CMailFile $i = 0; foreach ($arrayaddress as $val) { + $regs = array(); if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { $name = trim($regs[1]); @@ -1533,10 +1559,10 @@ class CMailFile $i++; $newemail = ''; - if ($format == 5) { - $newemail = $name ? $name : $email; - $newemail = ''.$newemail.''; - } + if ($format == 5) { + $newemail = $name ? $name : $email; + $newemail = ''.$newemail.''; + } if ($format == 4) { $newemail = $name ? $name : $email; diff --git a/htdocs/core/class/comment.class.php b/htdocs/core/class/comment.class.php index 91fba374181..a083576aacb 100644 --- a/htdocs/core/class/comment.class.php +++ b/htdocs/core/class/comment.class.php @@ -349,25 +349,25 @@ class Comment extends CommonObject $sql .= " c.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as c"; $sql .= " WHERE c.fk_element = ".$fk_element; - $sql .= " AND c.element_type = '".$db->escape($element_type)."'"; + $sql .= " AND c.element_type = '".$this->db->escape($element_type)."'"; $sql .= " AND c.entity = ".$conf->entity; $sql .= " ORDER BY c.tms DESC"; dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG); - $resql = $db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $num_rows = $db->num_rows($resql); + $num_rows = $this->db->num_rows($resql); if ($num_rows > 0) { - while ($obj = $db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { $comment = new self($db); $comment->fetch($obj->rowid); $this->comments[] = $comment; } } - $db->free($resql); + $this->db->free($resql); } else { $this->errors[] = "Error ".$this->db->lasterror(); return -1; diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index f610e6bb952..6015bbceece 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -40,199 +40,199 @@ abstract class CommonDocGenerator */ public $error = ''; - /** - * @var string[] Array of error strings - */ - public $errors = array(); + /** + * @var string[] Array of error strings + */ + public $errors = array(); /** - * @var DoliDB Database handler. - */ + * @var DoliDB Database handler. + */ protected $db; - /** - * @var Extrafields object - */ + /** + * @var Extrafields object + */ public $extrafieldsCache; /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param User $user User - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_user($user, $outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param User $user User + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_user($user, $outputlangs) + { + // phpcs:enable + global $conf; - $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; + $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; - return array( - 'myuser_lastname'=>$user->lastname, - 'myuser_firstname'=>$user->firstname, - 'myuser_fullname'=>$user->getFullName($outputlangs, 1), - 'myuser_login'=>$user->login, - 'myuser_phone'=>$user->office_phone, - 'myuser_address'=>$user->address, - 'myuser_zip'=>$user->zip, - 'myuser_town'=>$user->town, - 'myuser_country'=>$user->country, - 'myuser_country_code'=>$user->country_code, - 'myuser_state'=>$user->state, - 'myuser_state_code'=>$user->state_code, - 'myuser_fax'=>$user->office_fax, - 'myuser_mobile'=>$user->user_mobile, - 'myuser_email'=>$user->email, - 'myuser_logo'=>$logotouse, - 'myuser_job'=>$user->job, - 'myuser_web'=>'' // url not exist in $user object - ); - } + return array( + 'myuser_lastname'=>$user->lastname, + 'myuser_firstname'=>$user->firstname, + 'myuser_fullname'=>$user->getFullName($outputlangs, 1), + 'myuser_login'=>$user->login, + 'myuser_phone'=>$user->office_phone, + 'myuser_address'=>$user->address, + 'myuser_zip'=>$user->zip, + 'myuser_town'=>$user->town, + 'myuser_country'=>$user->country, + 'myuser_country_code'=>$user->country_code, + 'myuser_state'=>$user->state, + 'myuser_state_code'=>$user->state_code, + 'myuser_fax'=>$user->office_fax, + 'myuser_mobile'=>$user->user_mobile, + 'myuser_email'=>$user->email, + 'myuser_logo'=>$logotouse, + 'myuser_job'=>$user->job, + 'myuser_web'=>'' // url not exist in $user object + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $mysoc Object thirdparty - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_mysoc($mysoc, $outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $mysoc Object thirdparty + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_mysoc($mysoc, $outputlangs) + { + // phpcs:enable + global $conf; - if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) - { - $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); - } - if (empty($mysoc->country) && !empty($mysoc->country_code)) - { - $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); - } - if (empty($mysoc->state) && !empty($mysoc->state_code)) - { - $mysoc->state = getState($mysoc->state_code, 0); - } + if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) + { + $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); + } + if (empty($mysoc->country) && !empty($mysoc->country_code)) + { + $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); + } + if (empty($mysoc->state) && !empty($mysoc->state_code)) + { + $mysoc->state = getState($mysoc->state_code, 0); + } - $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; - return array( - 'mycompany_logo'=>$logotouse, - 'mycompany_name'=>$mysoc->name, - 'mycompany_email'=>$mysoc->email, - 'mycompany_phone'=>$mysoc->phone, - 'mycompany_fax'=>$mysoc->fax, - 'mycompany_address'=>$mysoc->address, - 'mycompany_zip'=>$mysoc->zip, - 'mycompany_town'=>$mysoc->town, - 'mycompany_country'=>$mysoc->country, - 'mycompany_country_code'=>$mysoc->country_code, - 'mycompany_state'=>$mysoc->state, - 'mycompany_state_code'=>$mysoc->state_code, - 'mycompany_web'=>$mysoc->url, - 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, - 'mycompany_managers'=>$mysoc->managers, - 'mycompany_capital'=>$mysoc->capital, - 'mycompany_barcode'=>$mysoc->barcode, - 'mycompany_idprof1'=>$mysoc->idprof1, - 'mycompany_idprof2'=>$mysoc->idprof2, - 'mycompany_idprof3'=>$mysoc->idprof3, - 'mycompany_idprof4'=>$mysoc->idprof4, - 'mycompany_idprof5'=>$mysoc->idprof5, - 'mycompany_idprof6'=>$mysoc->idprof6, - 'mycompany_vatnumber'=>$mysoc->tva_intra, + return array( + 'mycompany_logo'=>$logotouse, + 'mycompany_name'=>$mysoc->name, + 'mycompany_email'=>$mysoc->email, + 'mycompany_phone'=>$mysoc->phone, + 'mycompany_fax'=>$mysoc->fax, + 'mycompany_address'=>$mysoc->address, + 'mycompany_zip'=>$mysoc->zip, + 'mycompany_town'=>$mysoc->town, + 'mycompany_country'=>$mysoc->country, + 'mycompany_country_code'=>$mysoc->country_code, + 'mycompany_state'=>$mysoc->state, + 'mycompany_state_code'=>$mysoc->state_code, + 'mycompany_web'=>$mysoc->url, + 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, + 'mycompany_managers'=>$mysoc->managers, + 'mycompany_capital'=>$mysoc->capital, + 'mycompany_barcode'=>$mysoc->barcode, + 'mycompany_idprof1'=>$mysoc->idprof1, + 'mycompany_idprof2'=>$mysoc->idprof2, + 'mycompany_idprof3'=>$mysoc->idprof3, + 'mycompany_idprof4'=>$mysoc->idprof4, + 'mycompany_idprof5'=>$mysoc->idprof5, + 'mycompany_idprof6'=>$mysoc->idprof6, + 'mycompany_vatnumber'=>$mysoc->tva_intra, 'mycompany_object'=>$mysoc->object, - 'mycompany_note_private'=>$mysoc->note_private, - //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties - ); - } + 'mycompany_note_private'=>$mysoc->note_private, + //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $object Object - * @param Translate $outputlangs Language object for output - * @param string $array_key Name of the key for return array - * @return array Array of substitution key->code - */ - public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') - { - // phpcs:enable - global $conf, $extrafields; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $object Object + * @param Translate $outputlangs Language object for output + * @param string $array_key Name of the key for return array + * @return array Array of substitution key->code + */ + public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') + { + // phpcs:enable + global $conf, $extrafields; - if (empty($object->country) && !empty($object->country_code)) - { - $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); - } - if (empty($object->state) && !empty($object->state_code)) - { - $object->state = getState($object->state_code, 0); - } + if (empty($object->country) && !empty($object->country_code)) + { + $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); + } + if (empty($object->state) && !empty($object->state_code)) + { + $object->state = getState($object->state_code, 0); + } - $array_thirdparty = array( - 'company_name'=>$object->name, - 'company_name_alias' => $object->name_alias, - 'company_email'=>$object->email, - 'company_phone'=>$object->phone, - 'company_fax'=>$object->fax, - 'company_address'=>$object->address, - 'company_zip'=>$object->zip, - 'company_town'=>$object->town, - 'company_country'=>$object->country, - 'company_country_code'=>$object->country_code, - 'company_state'=>$object->state, - 'company_state_code'=>$object->state_code, - 'company_web'=>$object->url, - 'company_barcode'=>$object->barcode, - 'company_vatnumber'=>$object->tva_intra, - 'company_customercode'=>$object->code_client, - 'company_suppliercode'=>$object->code_fournisseur, - 'company_customeraccountancycode'=>$object->code_compta, - 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, - 'company_juridicalstatus'=>$object->forme_juridique, - 'company_outstanding_limit'=>$object->outstanding_limit, - 'company_capital'=>$object->capital, - 'company_idprof1'=>$object->idprof1, - 'company_idprof2'=>$object->idprof2, - 'company_idprof3'=>$object->idprof3, - 'company_idprof4'=>$object->idprof4, - 'company_idprof5'=>$object->idprof5, - 'company_idprof6'=>$object->idprof6, - 'company_note_public'=>$object->note_public, - 'company_note_private'=>$object->note_private, - 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), - 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') - ); + $array_thirdparty = array( + 'company_name'=>$object->name, + 'company_name_alias' => $object->name_alias, + 'company_email'=>$object->email, + 'company_phone'=>$object->phone, + 'company_fax'=>$object->fax, + 'company_address'=>$object->address, + 'company_zip'=>$object->zip, + 'company_town'=>$object->town, + 'company_country'=>$object->country, + 'company_country_code'=>$object->country_code, + 'company_state'=>$object->state, + 'company_state_code'=>$object->state_code, + 'company_web'=>$object->url, + 'company_barcode'=>$object->barcode, + 'company_vatnumber'=>$object->tva_intra, + 'company_customercode'=>$object->code_client, + 'company_suppliercode'=>$object->code_fournisseur, + 'company_customeraccountancycode'=>$object->code_compta, + 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, + 'company_juridicalstatus'=>$object->forme_juridique, + 'company_outstanding_limit'=>$object->outstanding_limit, + 'company_capital'=>$object->capital, + 'company_idprof1'=>$object->idprof1, + 'company_idprof2'=>$object->idprof2, + 'company_idprof3'=>$object->idprof3, + 'company_idprof4'=>$object->idprof4, + 'company_idprof5'=>$object->idprof5, + 'company_idprof6'=>$object->idprof6, + 'company_note_public'=>$object->note_public, + 'company_note_private'=>$object->note_private, + 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), + 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') + ); - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); - } + $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); + } return $array_thirdparty; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -241,9 +241,9 @@ abstract class CommonDocGenerator * @param string $array_key Name of the key for return array * @return array Array of substitution key->code */ - public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable + public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable global $conf, $extrafields; if (empty($object->country) && !empty($object->country_code)) @@ -285,67 +285,67 @@ abstract class CommonDocGenerator $array_key.'_civility' => $object->civility, ); - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); - } + $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); + } return $array_contact; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_other($outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_other($outputlangs) + { + // phpcs:enable + global $conf; - $now = dol_now('gmt'); // gmt - $array_other = array( - // Date in default language - 'current_date'=>dol_print_date($now, 'day', 'tzuser'), - 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), + $now = dol_now('gmt'); // gmt + $array_other = array( + // Date in default language + 'current_date'=>dol_print_date($now, 'day', 'tzuser'), + 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), 'current_server_date'=>dol_print_date($now, 'day', 'tzserver'), 'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'), - // Date in requested output language - 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), + // Date in requested output language + 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), 'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs), 'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs), 'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs), - ); + ); - foreach ($conf->global as $key => $val) - { - if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****'; - else $newval = $val; - $array_other['__['.$key.']__'] = $newval; - } + foreach ($conf->global as $key => $val) + { + if (isASecretKey($key)) $newval = '*****forbidden*****'; + else $newval = $val; + $array_other['__['.$key.']__'] = $newval; + } - return $array_other; - } + return $array_other; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * * @param Object $object Main object to use as data source * @param Translate $outputlangs Lang object to use for output - * @param string $array_key Name of the key for return array + * @param string $array_key Name of the key for return array * @return array Array of substitution */ public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object') { - // phpcs:enable + // phpcs:enable global $conf, $extrafields; $sumpayed = $sumdeposit = $sumcreditnote = ''; @@ -381,11 +381,11 @@ abstract class CommonDocGenerator $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), $array_key.'_source_invoice_ref'=>$invoice_source->ref, // Dates - $array_key.'_hour'=>dol_print_date($date, 'hour'), + $array_key.'_hour'=>dol_print_date($date, 'hour'), $array_key.'_date'=>dol_print_date($date, 'day'), $array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'), $array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''), - $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), + $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), $array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''), $array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''), @@ -397,6 +397,8 @@ abstract class CommonDocGenerator $array_key.'_payment_term_code'=>$object->cond_reglement_code, $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)), + $array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''), + $array_key.'_bank_iban'=>$bank_account->iban, $array_key.'_bank_bic'=>$bank_account->bic, @@ -414,8 +416,8 @@ abstract class CommonDocGenerator $array_key.'_multicurrency_code' => price2num($object->multicurrency_code), $array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx), - $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), - $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), + $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), + $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), $array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc), $array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs), $array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs), @@ -470,11 +472,11 @@ abstract class CommonDocGenerator $totalUp = 0; foreach ($object->lines as $line) { - // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility + // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0; $resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); - // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) + // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) $vatformated = vatrate($line->tva_tx); if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0; $resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva; @@ -512,7 +514,7 @@ abstract class CommonDocGenerator return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -523,7 +525,7 @@ abstract class CommonDocGenerator */ public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0) { - // phpcs:enable + // phpcs:enable global $conf; $resarray = array( @@ -535,9 +537,9 @@ abstract class CommonDocGenerator 'line_product_type'=>$line->product_type, 'line_desc'=>$line->desc, 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_localtax1_rate'=>vatrate($line->localtax1_tx), - 'line_localtax2_rate'=>vatrate($line->localtax1_tx), - 'line_up'=>price2num($line->subprice), + 'line_localtax1_rate'=>vatrate($line->localtax1_tx), + 'line_localtax2_rate'=>vatrate($line->localtax1_tx), + 'line_up'=>price2num($line->subprice), 'line_up_locale'=>price($line->subprice, 0, $outputlangs), 'line_total_up'=>price2num($line->subprice * $line->qty), 'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs), @@ -549,31 +551,31 @@ abstract class CommonDocGenerator 'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs), 'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs), 'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs), - // Dates + // Dates 'line_date_start'=>dol_print_date($line->date_start, 'day'), 'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs), - 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), - 'line_date_end'=>dol_print_date($line->date_end, 'day'), - 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), - 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), + 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), + 'line_date_end'=>dol_print_date($line->date_end, 'day'), + 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), + 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), - 'line_multicurrency_code' => price2num($line->multicurrency_code), - 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), - 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), - 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), - 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), - 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), - 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), - 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), - 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), + 'line_multicurrency_code' => price2num($line->multicurrency_code), + 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), + 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), + 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), + 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), + 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), + 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), + 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), + 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); - // Units + // Units if ($conf->global->PRODUCT_USE_UNITS) { - $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); - $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); - } + $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey = $line->table_element; @@ -583,14 +585,14 @@ abstract class CommonDocGenerator $extrafields->fetch_name_optionals_label($extrafieldkey, true); $line->fetch_optionals(); - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - // Check if the current line belongs to a supplier order - if (get_class($line) == 'CommandeFournisseurLigne') - { - // Add the product supplier extrafields to the substitutions - $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; + // Check if the current line belongs to a supplier order + if (get_class($line) == 'CommandeFournisseurLigne') + { + // Add the product supplier extrafields to the substitutions + $extrafields->fetch_name_optionals_label("product_fournisseur_price"); + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; if (!empty($extralabels) && is_array($extralabels)) { @@ -604,7 +606,7 @@ abstract class CommonDocGenerator if ($columns != "") { $columns = substr($columns, 0, strlen($columns) - 2); - $resql = $this->db->query("SELECT $columns FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$line->ref_supplier."'"); + $resql = $this->db->query("SELECT ".$columns." FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$this->db->escape($line->ref_supplier)."'"); if ($this->db->num_rows($resql) > 0) { @@ -617,7 +619,7 @@ abstract class CommonDocGenerator } } } - } + } // Load product data optional fields to the line -> enables to use "line_options_{extrafield}" if (isset($line->fk_product) && $line->fk_product > 0) @@ -631,158 +633,158 @@ abstract class CommonDocGenerator return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Expedition $object Main object to use as data source - * @param Translate $outputlangs Lang object to use for output - * @param array $array_key Name of the key for return array - * @return array Array of substitution - */ - public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable - global $conf, $extrafields; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Expedition $object Main object to use as data source + * @param Translate $outputlangs Lang object to use for output + * @param array $array_key Name of the key for return array + * @return array Array of substitution + */ + public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable + global $conf, $extrafields; dol_include_once('/core/lib/product.lib.php'); $object->list_delivery_methods($object->shipping_method_id); $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); - $array_shipment = array( - $array_key.'_id'=>$object->id, - $array_key.'_ref'=>$object->ref, - $array_key.'_ref_ext'=>$object->ref_ext, - $array_key.'_ref_customer'=>$object->ref_customer, - $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), - $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), - $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), - $array_key.'_total_ht'=>price($object->total_ht), - $array_key.'_total_vat'=>price($object->total_tva), - $array_key.'_total_ttc'=>price($object->total_ttc), - $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), - $array_key.'_note_private'=>$object->note_private, - $array_key.'_note'=>$object->note_public, - $array_key.'_tracking_number'=>$object->tracking_number, - $array_key.'_tracking_url'=>$object->tracking_url, - $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], - $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), - $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), - $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), - $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), - $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), - ); + $array_shipment = array( + $array_key.'_id'=>$object->id, + $array_key.'_ref'=>$object->ref, + $array_key.'_ref_ext'=>$object->ref_ext, + $array_key.'_ref_customer'=>$object->ref_customer, + $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), + $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), + $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), + $array_key.'_total_ht'=>price($object->total_ht), + $array_key.'_total_vat'=>price($object->total_tva), + $array_key.'_total_ttc'=>price($object->total_ttc), + $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), + $array_key.'_note_private'=>$object->note_private, + $array_key.'_note'=>$object->note_public, + $array_key.'_tracking_number'=>$object->tracking_number, + $array_key.'_tracking_url'=>$object->tracking_url, + $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], + $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), + $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), + $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), + $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), + $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), + ); - // Add vat by rates - foreach ($object->lines as $line) - { - if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; - $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; - } + // Add vat by rates + foreach ($object->lines as $line) + { + if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; + $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; + } - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); - } + $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); + } - return $array_shipment; - } + return $array_shipment; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param ExpeditionLigne $line Object line - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function get_substitutionarray_shipment_lines($line, $outputlangs) - { - // phpcs:enable - global $conf; - dol_include_once('/core/lib/product.lib.php'); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param ExpeditionLigne $line Object line + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function get_substitutionarray_shipment_lines($line, $outputlangs) + { + // phpcs:enable + global $conf; + dol_include_once('/core/lib/product.lib.php'); - $resarray = array( - 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), - 'line_product_ref'=>$line->product_ref, - 'line_product_label'=>$line->product_label, - 'line_desc'=>$line->desc, - 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_up'=>price($line->subprice), - 'line_total_up'=>price($line->subprice * $line->qty), - 'line_qty'=>$line->qty, - 'line_qty_shipped'=>$line->qty_shipped, - 'line_qty_asked'=>$line->qty_asked, - 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), - 'line_price_ht'=>price($line->total_ht), - 'line_price_ttc'=>price($line->total_ttc), - 'line_price_vat'=>price($line->total_tva), - 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), - 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), - 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), - 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), - ); + $resarray = array( + 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), + 'line_product_ref'=>$line->product_ref, + 'line_product_label'=>$line->product_label, + 'line_desc'=>$line->desc, + 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), + 'line_up'=>price($line->subprice), + 'line_total_up'=>price($line->subprice * $line->qty), + 'line_qty'=>$line->qty, + 'line_qty_shipped'=>$line->qty_shipped, + 'line_qty_asked'=>$line->qty_asked, + 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), + 'line_price_ht'=>price($line->total_ht), + 'line_price_ttc'=>price($line->total_ttc), + 'line_price_vat'=>price($line->total_tva), + 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), + 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), + 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), + 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), + ); - // Retrieve extrafields - $extrafieldkey = $line->element; - $array_key = "line"; - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $extrafields->fetch_name_optionals_label($extrafieldkey, true); - $line->fetch_optionals(); + // Retrieve extrafields + $extrafieldkey = $line->element; + $array_key = "line"; + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $extrafields->fetch_name_optionals_label($extrafieldkey, true); + $line->fetch_optionals(); - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - return $resarray; - } + return $resarray; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Object $object Dolibarr Object - * @param Translate $outputlangs Language object for output - * @param boolean $recursive Want to fetch child array or child object - * @return array Array of substitution key->code - */ - public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) - { - // phpcs:enable - $array_other = array(); - if (!empty($object)) { - foreach ($object as $key => $value) { - if (!empty($value)) { - if (!is_array($value) && !is_object($value)) { - $array_other['object_'.$key] = $value; - } - if (is_array($value) && $recursive) { - $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); - } - } - } - } - return $array_other; - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Object $object Dolibarr Object + * @param Translate $outputlangs Language object for output + * @param boolean $recursive Want to fetch child array or child object + * @return array Array of substitution key->code + */ + public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) + { + // phpcs:enable + $array_other = array(); + if (!empty($object)) { + foreach ($object as $key => $value) { + if (!empty($value)) { + if (!is_array($value) && !is_object($value)) { + $array_other['object_'.$key] = $value; + } + if (is_array($value) && $recursive) { + $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); + } + } + } + } + return $array_other; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Fill array with couple extrafield key => extrafield value - * - * @param Object $object Object with extrafields (must have $object->array_options filled) - * @param array $array_to_fill Substitution array - * @param Extrafields $extrafields Extrafields object - * @param string $array_key Prefix for name of the keys into returned array - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Fill array with couple extrafield key => extrafield value + * + * @param Object $object Object with extrafields (must have $object->array_options filled) + * @param array $array_to_fill Substitution array + * @param Extrafields $extrafields Extrafields object + * @param string $array_key Prefix for name of the keys into returned array + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) + { + // phpcs:enable global $conf; if (is_array($extrafields->attributes[$object->table_element]['label'])) { @@ -873,671 +875,671 @@ abstract class CommonDocGenerator * @param int $hidebottom Hide bottom * @return void */ - public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) - { - if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); - $pdf->line($x + $l, $y, $x + $l, $y + $h); - if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); - $pdf->line($x, $y + $h, $x, $y); - } - - - /** - * uasort callback function to Sort columns fields - * - * @param array $a PDF lines array fields configs - * @param array $b PDF lines array fields configs - * @return int Return compare result - */ - public function columnSort($a, $b) - { - if (empty($a['rank'])) { $a['rank'] = 0; } - if (empty($b['rank'])) { $b['rank'] = 0; } - if ($a['rank'] == $b['rank']) { - return 0; - } - return ($a['rank'] > $b['rank']) ? -1 : 1; - } - - /** - * Prepare Array Column Field - * - * @param object $object common object - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return null - */ - public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - global $conf; - - $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - - - // Sorting - uasort($this->cols, array($this, 'columnSort')); - - // Positionning - $curX = $this->page_largeur - $this->marge_droite; // start from right - - // Array width - $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; - - // Count flexible column - $totalDefinedColWidth = 0; - $countFlexCol = 0; - foreach ($this->cols as $colKey =>& $colDef) - { - if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - - if (!empty($colDef['scale'])) { - // In case of column width is defined by percentage - $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); - } - - if (empty($colDef['width'])) { - $countFlexCol++; - } else { - $totalDefinedColWidth += $colDef['width']; - } - } - - foreach ($this->cols as $colKey =>& $colDef) - { - // setting empty conf with default - if (!empty($colDef['title'])) { - $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); - } else { - $colDef['title'] = $this->defaultTitlesFieldsStyle; - } - - // setting empty conf with default - if (!empty($colDef['content'])) { - $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); - } else { - $colDef['content'] = $this->defaultContentsFieldsStyle; - } - - if ($this->getColumnStatus($colKey)) - { - // In case of flexible column - if (empty($colDef['width'])) { - $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; - } - - // Set positions - $lastX = $curX; - $curX = $lastX - $colDef['width']; - $colDef['xStartPos'] = $curX; - $colDef['xEndPos'] = $lastX; - } - } - } - - /** - * get column content width from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnContentWidth($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; - } - - - /** - * get column content X (abscissa) left position from column key - * - * @param string $colKey the column key - * @return float X position in mm - */ - public function getColumnContentXStart($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['xStartPos'] + $colDef['content']['padding'][3]; - } - - /** - * get column position rank from column key - * - * @param string $colKey the column key - * @return int rank on success and -1 on error - */ - public function getColumnRank($colKey) - { - if (!isset($this->cols[$colKey]['rank'])) return -1; - return $this->cols[$colKey]['rank']; - } - - /** - * get column position rank from column key - * - * @param string $newColKey the new column key - * @param array $defArray a single column definition array - * @param string $targetCol target column used to place the new column beside - * @param bool $insertAfterTarget insert before or after target column ? - * @return int new rank on success and -1 on error - */ - public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) - { - // prepare wanted rank - $rank = -1; - - // try to get rank from target column - if (!empty($targetCol)) { - $rank = $this->getColumnRank($targetCol); - if ($rank >= 0 && $insertAfterTarget) { $rank++; } - } - - // get rank from new column definition - if ($rank < 0 && !empty($defArray['rank'])) { - $rank = $defArray['rank']; - } - - // error: no rank - if ($rank < 0) { return -1; } - - foreach ($this->cols as $colKey =>& $colDef) - { - if ($rank <= $colDef['rank']) - { - $colDef['rank'] = $colDef['rank'] + 1; - } - } - - $defArray['rank'] = $rank; - $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys - - return $rank; - } - - - /** - * print standard column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param string $columnText column text - * @return null - */ - public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') - { - global $hookmanager; - - $parameters = array( - 'curY' => &$curY, - 'columnText' => $columnText, - 'colKey' => $colKey, - 'pdf' => &$pdf, - ); - $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (!$reshook) - { - if (empty($columnText)) return; - $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - - - /** - * print description column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param object $object CommonObject - * @param int $i the $object->lines array key - * @param Translate $outputlangs Output language - * @param int $hideref hide ref - * @param int $hidedesc hide desc - * @param int $issupplierline if object need supplier product - * @return null - */ - public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) + public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) { - // load desc col params - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - - // line description - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); - $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - - // Display extrafield if needed - $params = array( - 'display' => 'list', - 'printableEnable' => array(3), - 'printableEnableNotEmpty' => array(4) - ); - $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); - if (!empty($extrafieldDesc)) { - $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); - } - } - - /** - * get extrafield content for pdf writeHtmlCell compatibility - * usage for PDF line columns and object note block - * - * @param object $object common object - * @param string $extrafieldKey the extrafield key - * @return string - */ - public function getExtrafieldContent($object, $extrafieldKey) - { - global $hookmanager; - - if (empty($object->table_element)) { return; } - - $extrafieldsKeyPrefix = "options_"; - - // Cleanup extrafield key to remove prefix if present - $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); - if ($pos === 0) { - $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); - } - - $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); + $pdf->line($x + $l, $y, $x + $l, $y + $h); + if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); + $pdf->line($x, $y + $h, $x, $y); + } - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + /** + * uasort callback function to Sort columns fields + * + * @param array $a PDF lines array fields configs + * @param array $b PDF lines array fields configs + * @return int Return compare result + */ + public function columnSort($a, $b) + { + if (empty($a['rank'])) { $a['rank'] = 0; } + if (empty($b['rank'])) { $b['rank'] = 0; } + if ($a['rank'] == $b['rank']) { + return 0; + } + return ($a['rank'] > $b['rank']) ? -1 : 1; + } - $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + /** + * Prepare Array Column Field + * + * @param object $object common object + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf; - // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... - if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { - // for lack of anything better we cleanup all html tags - $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); - } - - $parameters = array( - 'object' => $object, - 'extrafields' => $extrafields, - 'extrafieldKey' => $extrafieldKey, - 'extrafieldOutputContent' =>& $extrafieldOutputContent - ); - $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if ($reshook) - { - $extrafieldOutputContent = $hookmanager->resPrint; - } - - return $extrafieldOutputContent; - } + $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - /** - * display extrafields columns content - * - * @param object $object line of common object - * @param Translate $outputlangs Output language - * @param array $params array of additionals parameters - * @return double max y value - */ - public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) - { - global $hookmanager; + // Sorting + uasort($this->cols, array($this, 'columnSort')); - if (empty($object->table_element)) { - return; - } + // Positionning + $curX = $this->page_largeur - $this->marge_droite; // start from right - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + // Array width + $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; - $defaultParams = array( - 'style' => '', - 'display' => 'auto', // auto, table, list - 'printableEnable' => array(1), - 'printableEnableNotEmpty' => array(2), + // Count flexible column + $totalDefinedColWidth = 0; + $countFlexCol = 0; + foreach ($this->cols as $colKey =>& $colDef) + { + if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - 'table' => array( - 'maxItemsInRow' => 2, - 'cellspacing' => 0, - 'cellpadding' => 0, - 'border' => 0, - 'labelcolwidth' => '25%', - 'arrayOfLineBreakType' => array('text', 'html') - ), + if (!empty($colDef['scale'])) { + // In case of column width is defined by percentage + $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); + } - 'list' => array( - 'separator' => '
' - ), + if (empty($colDef['width'])) { + $countFlexCol++; + } else { + $totalDefinedColWidth += $colDef['width']; + } + } - 'auto' => array( - 'list' => 0, // 0 for default - 'table' => 4 // if there more than x extrafield to display - ), - ); + foreach ($this->cols as $colKey =>& $colDef) + { + // setting empty conf with default + if (!empty($colDef['title'])) { + $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); + } else { + $colDef['title'] = $this->defaultTitlesFieldsStyle; + } - $params = $params + $defaultParams; + // setting empty conf with default + if (!empty($colDef['content'])) { + $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); + } else { + $colDef['content'] = $this->defaultContentsFieldsStyle; + } + + if ($this->getColumnStatus($colKey)) + { + // In case of flexible column + if (empty($colDef['width'])) { + $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; + } + + // Set positions + $lastX = $curX; + $curX = $lastX - $colDef['width']; + $colDef['xStartPos'] = $curX; + $colDef['xEndPos'] = $lastX; + } + } + } + + /** + * get column content width from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnContentWidth($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; + } - /** - * @var $extrafields ExtraFields - */ + /** + * get column content X (abscissa) left position from column key + * + * @param string $colKey the column key + * @return float X position in mm + */ + public function getColumnContentXStart($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['xStartPos'] + $colDef['content']['padding'][3]; + } - $html = ''; - $fields = array(); + /** + * get column position rank from column key + * + * @param string $colKey the column key + * @return int rank on success and -1 on error + */ + public function getColumnRank($colKey) + { + if (!isset($this->cols[$colKey]['rank'])) return -1; + return $this->cols[$colKey]['rank']; + } - if (is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Enable extrafield ? - $enabled = 0; - $disableOnEmpty = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { - $enabled = 1; - } + /** + * get column position rank from column key + * + * @param string $newColKey the new column key + * @param array $defArray a single column definition array + * @param string $targetCol target column used to place the new column beside + * @param bool $insertAfterTarget insert before or after target column ? + * @return int new rank on success and -1 on error + */ + public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) + { + // prepare wanted rank + $rank = -1; - if (in_array($printable, $params['printableEnableNotEmpty'])) { - $disableOnEmpty = 1; - } - } + // try to get rank from target column + if (!empty($targetCol)) { + $rank = $this->getColumnRank($targetCol); + if ($rank >= 0 && $insertAfterTarget) { $rank++; } + } - if (empty($enabled)) { - continue; - } + // get rank from new column definition + if ($rank < 0 && !empty($defArray['rank'])) { + $rank = $defArray['rank']; + } - $field = new stdClass(); - $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); - $field->content = $this->getExtrafieldContent($object, $key); - $field->label = $outputlangs->transnoentities($label); - $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + // error: no rank + if ($rank < 0) { return -1; } - // dont display if empty - if ($disableOnEmpty && empty($field->content)) { - continue; - } + foreach ($this->cols as $colKey =>& $colDef) + { + if ($rank <= $colDef['rank']) + { + $colDef['rank'] = $colDef['rank'] + 1; + } + } - $fields[] = $field; - } - } + $defArray['rank'] = $rank; + $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys - if (!empty($fields)) - { - // Sort extrafields by rank - uasort($fields, function ($a, $b) { - return ($a->rank > $b->rank) ? 1 : -1; + return $rank; + } + + + /** + * print standard column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param string $columnText column text + * @return null + */ + public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') + { + global $hookmanager; + + $parameters = array( + 'curY' => &$curY, + 'columnText' => $columnText, + 'colKey' => $colKey, + 'pdf' => &$pdf, + ); + $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if (!$reshook) + { + if (empty($columnText)) return; + $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + + + /** + * print description column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param object $object CommonObject + * @param int $i the $object->lines array key + * @param Translate $outputlangs Output language + * @param int $hideref hide ref + * @param int $hidedesc hide desc + * @param int $issupplierline if object need supplier product + * @return null + */ + public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) + { + // load desc col params + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + + // line description + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); + $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + + // Display extrafield if needed + $params = array( + 'display' => 'list', + 'printableEnable' => array(3), + 'printableEnableNotEmpty' => array(4) + ); + $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); + if (!empty($extrafieldDesc)) { + $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); + } + } + + /** + * get extrafield content for pdf writeHtmlCell compatibility + * usage for PDF line columns and object note block + * + * @param object $object common object + * @param string $extrafieldKey the extrafield key + * @return string + */ + public function getExtrafieldContent($object, $extrafieldKey) + { + global $hookmanager; + + if (empty($object->table_element)) { return; } + + $extrafieldsKeyPrefix = "options_"; + + // Cleanup extrafield key to remove prefix if present + $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); + if ($pos === 0) { + $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); + } + + $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + + // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... + if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { + // for lack of anything better we cleanup all html tags + $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); + } + + $parameters = array( + 'object' => $object, + 'extrafields' => $extrafields, + 'extrafieldKey' => $extrafieldKey, + 'extrafieldOutputContent' =>& $extrafieldOutputContent + ); + $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook) + { + $extrafieldOutputContent = $hookmanager->resPrint; + } + + return $extrafieldOutputContent; + } + + + /** + * display extrafields columns content + * + * @param object $object line of common object + * @param Translate $outputlangs Output language + * @param array $params array of additionals parameters + * @return double max y value + */ + public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) + { + global $hookmanager; + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $defaultParams = array( + 'style' => '', + 'display' => 'auto', // auto, table, list + 'printableEnable' => array(1), + 'printableEnableNotEmpty' => array(2), + + 'table' => array( + 'maxItemsInRow' => 2, + 'cellspacing' => 0, + 'cellpadding' => 0, + 'border' => 0, + 'labelcolwidth' => '25%', + 'arrayOfLineBreakType' => array('text', 'html') + ), + + 'list' => array( + 'separator' => '
' + ), + + 'auto' => array( + 'list' => 0, // 0 for default + 'table' => 4 // if there more than x extrafield to display + ), + ); + + $params = $params + $defaultParams; + + + /** + * @var $extrafields ExtraFields + */ + + $html = ''; + $fields = array(); + + if (is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Enable extrafield ? + $enabled = 0; + $disableOnEmpty = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { + $enabled = 1; + } + + if (in_array($printable, $params['printableEnableNotEmpty'])) { + $disableOnEmpty = 1; + } + } + + if (empty($enabled)) { + continue; + } + + $field = new stdClass(); + $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); + $field->content = $this->getExtrafieldContent($object, $key); + $field->label = $outputlangs->transnoentities($label); + $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + + // dont display if empty + if ($disableOnEmpty && empty($field->content)) { + continue; + } + + $fields[] = $field; + } + } + + if (!empty($fields)) + { + // Sort extrafields by rank + uasort($fields, function ($a, $b) { + return ($a->rank > $b->rank) ? 1 : -1; }); - // define some HTML content with style - $html .= !empty($params['style']) ? '' : ''; + // define some HTML content with style + $html .= !empty($params['style']) ? '' : ''; - // auto select display format - if ($params['display'] == 'auto') { - $lastNnumbItems = 0; - foreach ($params['auto'] as $display => $numbItems) { - if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { - $lastNnumbItems = $numbItems; - $params['display'] = $display; - } - } - } + // auto select display format + if ($params['display'] == 'auto') { + $lastNnumbItems = 0; + foreach ($params['auto'] as $display => $numbItems) { + if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { + $lastNnumbItems = $numbItems; + $params['display'] = $display; + } + } + } - if ($params['display'] == 'list') { - // Display in list format - $i = 0; - foreach ($fields as $field) { - $html .= !empty($i) ? $params['list']['separator'] : ''; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $i++; - } - } elseif ($params['display'] == 'table') { - // Display in table format - $html .= ''; + if ($params['display'] == 'list') { + // Display in list format + $i = 0; + foreach ($fields as $field) { + $html .= !empty($i) ? $params['list']['separator'] : ''; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $i++; + } + } elseif ($params['display'] == 'table') { + // Display in table format + $html .= '
'; - $html .= ""; - $itemsInRow = 0; - $maxItemsInRow = $params['table']['maxItemsInRow']; - foreach ($fields as $field) { - //$html.= !empty($html)?'
':''; - if ($itemsInRow >= $maxItemsInRow) { - // start a new line - $html .= ""; - $itemsInRow = 0; - } + $html .= ""; + $itemsInRow = 0; + $maxItemsInRow = $params['table']['maxItemsInRow']; + foreach ($fields as $field) { + //$html.= !empty($html)?'
':''; + if ($itemsInRow >= $maxItemsInRow) { + // start a new line + $html .= ""; + $itemsInRow = 0; + } - // for some type we need line break - if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { - if ($itemsInRow > 0) { - // close table row and empty cols - for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { - $html .= ""; - } - $html .= ""; + // for some type we need line break + if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { + if ($itemsInRow > 0) { + // close table row and empty cols + for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { + $html .= ""; + } + $html .= ""; - // start a new line - $html .= ""; - } + // start a new line + $html .= ""; + } - $itemsInRow = $maxItemsInRow; - $html .= '"; - } else { - $itemsInRow++; - $html .= '"; + $itemsInRow = $maxItemsInRow; + $html .= '"; + } else { + $itemsInRow++; + $html .= '"; - $html .= '"; - } - } - $html .= ""; + $html .= '"; + } + } + $html .= ""; - $html .= '
'; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $html .= "'; - $html .= ''.$field->label.' :'; - $html .= "'; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $html .= "'; + $html .= ''.$field->label.' :'; + $html .= "'; - $html .= $field->content; - $html .= "
'; + $html .= $field->content; + $html .= "
'; - } - } + $html .= ''; + } + } - return $html; - } + return $html; + } - /** - * get column status from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnStatus($colKey) - { - if (!empty($this->cols[$colKey]['status'])) { - return true; - } else return false; - } + /** + * get column status from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnStatus($colKey) + { + if (!empty($this->cols[$colKey]['status'])) { + return true; + } else return false; + } - /** - * Print standard column content - * - * @param TCPDI $pdf Pdf object - * @param float $tab_top Tab top position - * @param float $tab_height Default tab height - * @param Translate $outputlangs Output language - * @param int $hidetop Hide top - * @return float Height of col tab titles - */ - public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) - { - global $hookmanager, $conf; + /** + * Print standard column content + * + * @param TCPDI $pdf Pdf object + * @param float $tab_top Tab top position + * @param float $tab_height Default tab height + * @param Translate $outputlangs Output language + * @param int $hidetop Hide top + * @return float Height of col tab titles + */ + public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) + { + global $hookmanager, $conf; - foreach ($this->cols as $colKey => $colDef) { - $parameters = array( - 'colKey' => $colKey, - 'pdf' => $pdf, - 'outputlangs' => $outputlangs, - 'tab_top' => $tab_top, - 'tab_height' => $tab_height, - 'hidetop' => $hidetop - ); + foreach ($this->cols as $colKey => $colDef) { + $parameters = array( + 'colKey' => $colKey, + 'pdf' => $pdf, + 'outputlangs' => $outputlangs, + 'tab_top' => $tab_top, + 'tab_height' => $tab_height, + 'hidetop' => $hidetop + ); - $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) { - if (!$this->getColumnStatus($colKey)) continue; + $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) { + if (!$this->getColumnStatus($colKey)) continue; - // get title label - $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); + // get title label + $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); - // Add column separator - if (!empty($colDef['border-left'])) { - $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); - } + // Add column separator + if (!empty($colDef['border-left'])) { + $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); + } - if (empty($hidetop)) { - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); + if (empty($hidetop)) { + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); - // Add space for lines (more if we need to show a second alternative language) - global $outputlangsbis; - if (is_object($outputlangsbis)) { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); - } else { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - } + // Add space for lines (more if we need to show a second alternative language) + global $outputlangsbis; + if (is_object($outputlangsbis)) { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); + } else { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + } - $pdf->SetXY($colDef['xStartPos'], $tab_top); - $textWidth = $colDef['width']; - $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); + $pdf->SetXY($colDef['xStartPos'], $tab_top); + $textWidth = $colDef['width']; + $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); - // Add variant of translation if $outputlangsbis is an object - if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { - $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); - $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); - $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); - } + // Add variant of translation if $outputlangsbis is an object + if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { + $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); + $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); + $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); + } - $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); + $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - } + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + } - return $this->tabTitleHeight; - } + return $this->tabTitleHeight; + } - /** - * Define Array Column Field for extrafields - * - * @param object $object common object det - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @return null - */ - public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) - { - global $conf; + /** + * Define Array Column Field for extrafields + * + * @param object $object common object det + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @return null + */ + public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) + { + global $conf; - if (!empty($hidedetails)) { - return; - } + if (!empty($hidedetails)) { + return; + } - if (empty($object->table_element)) { - return; - } + if (empty($object->table_element)) { + return; + } - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; - if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Dont display separator yet even is set to be displayed (not compatible yet) - if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') - { - continue; - } + if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Dont display separator yet even is set to be displayed (not compatible yet) + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') + { + continue; + } - // Enable extrafield ? - $enabled = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if ($printable === 1 || $printable === 2) { - $enabled = 1; - } - // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols - } + // Enable extrafield ? + $enabled = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if ($printable === 1 || $printable === 2) { + $enabled = 1; + } + // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols + } - if (!$enabled) { continue; } // don't wast resourses if we don't need them... + if (!$enabled) { continue; } // don't wast resourses if we don't need them... - // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); + // Load language if required + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); - // TODO : add more extrafield customisation capacities for PDF like width, rank... + // TODO : add more extrafield customisation capacities for PDF like width, rank... - // set column definition - $def = array( - 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), - 'width' => 25, // in mm - 'status' => boolval($enabled), - 'title' => array( - 'label' => $outputlangs->transnoentities($label) - ), - 'content' => array( - 'align' => 'C' - ), - 'border-left' => true, // add left line separator - ); + // set column definition + $def = array( + 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), + 'width' => 25, // in mm + 'status' => boolval($enabled), + 'title' => array( + 'label' => $outputlangs->transnoentities($label) + ), + 'content' => array( + 'align' => 'C' + ), + 'border-left' => true, // add left line separator + ); - $alignTypeRight = array('double', 'int', 'price'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { - $def['content']['align'] = 'R'; - } + $alignTypeRight = array('double', 'int', 'price'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { + $def['content']['align'] = 'R'; + } - $alignTypeLeft = array('text', 'html'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { - $def['content']['align'] = 'L'; - } + $alignTypeLeft = array('text', 'html'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { + $def['content']['align'] = 'L'; + } - // for extrafields we use rank of extrafield to place it on PDF - $this->insertNewColumnDef("options_".$key, $def); - } - } - } + // for extrafields we use rank of extrafield to place it on PDF + $this->insertNewColumnDef("options_".$key, $def); + } + } + } } diff --git a/htdocs/core/class/commonincoterm.class.php b/htdocs/core/class/commonincoterm.class.php new file mode 100644 index 00000000000..b2d5491684e --- /dev/null +++ b/htdocs/core/class/commonincoterm.class.php @@ -0,0 +1,141 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/class/commonincoterm.class.php + * \ingroup core + * \brief File of the superclass of object classes that support incoterm (customer and supplier) + */ + + +/** + * Superclass for incoterm classes + */ +trait CommonIncoterm +{ + /** + * @var int ID incoterm. + * @see setIncoterms() + */ + public $fk_incoterms; + + /** + * @var string Label of incoterm. Used for tooltip. + * @see SetIncoterms() + */ + public $label_incoterms; + + /** + * @var string Location of incoterm. + * @see display_incoterms() + */ + public $location_incoterms; + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return incoterms informations + * TODO Use a cache for label get + * + * @return string incoterms info + */ + public function display_incoterms() + { + // phpcs:enable + $out = ''; + + $this->label_incoterms = ''; + if (!empty($this->fk_incoterms)) + { + $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $result = $this->db->query($sql); + if ($result) + { + $res = $this->db->fetch_object($result); + $out .= $res->code; + } + } + + $out .= (($out && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms; + + return $out; + } + + /** + * Return incoterms informations for pdf display + * + * @return string incoterms info + */ + public function getIncotermsForPDF() + { + $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num > 0) + { + $res = $this->db->fetch_object($resql); + return 'Incoterm : '.$res->code.' - '.$this->location_incoterms; + } else { + return ''; + } + } else { + $this->errors[] = $this->db->lasterror(); + return false; + } + } + + /** + * Define incoterms values of current object + * + * @param int $id_incoterm Id of incoterm to set or '' to remove + * @param string $location location of incoterm + * @return int <0 if KO, >0 if OK + */ + public function setIncoterms($id_incoterm, $location) + { + if ($this->id && $this->table_element) + { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); + $sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); + $sql .= " WHERE rowid = ".$this->id; + dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->fk_incoterms = $id_incoterm; + $this->location_incoterms = $location; + + $sql = 'SELECT libelle as label_incotermsFROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; + $res = $this->db->query($sql); + if ($res) + { + $obj = $this->db->fetch_object($res); + $this->label_incoterms = $obj->label_incoterms; + } + return 1; + } else { + $this->errors[] = $this->db->lasterror(); + return -1; + } + } else { + return -1; + } + } +} diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 628abc128f4..98890744701 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -24,12 +24,15 @@ */ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; /** * Superclass for invoices classes */ abstract class CommonInvoice extends CommonObject { + use CommonIncoterm; + /** * Standard invoice */ @@ -297,6 +300,7 @@ abstract class CommonInvoice extends CommonObject $table2 = 'paiement'; $field = 'fk_facture'; $field2 = 'fk_paiement'; + $field3=', p.ref_ext'; $sharedentity = 'facture'; if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') { @@ -304,10 +308,11 @@ abstract class CommonInvoice extends CommonObject $table2 = 'paiementfourn'; $field = 'fk_facturefourn'; $field2 = 'fk_paiementfourn'; + $field3=''; $sharedentity = 'facture_fourn'; } - $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'; + $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code'.$field3; $sql .= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t'; $sql .= ' WHERE pf.'.$field.' = '.$this->id; //$sql.= ' WHERE pf.'.$field.' = 1'; @@ -325,7 +330,11 @@ abstract class CommonInvoice extends CommonObject while ($i < $num) { $obj = $this->db->fetch_object($resql); - $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); + $tmp = array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref); + if (!empty($field3)) { + $tmp['ref_ext'] = $obj->ref_ext; + } + $retarray[]=$tmp; $i++; } $this->db->free($resql); @@ -453,7 +462,7 @@ abstract class CommonInvoice extends CommonObject $type = 'customer_invoice'; if ($this->element == 'invoice_supplier') $type = 'supplier_invoice'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; + $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) { @@ -535,7 +544,7 @@ abstract class CommonInvoice extends CommonObject $labelStatus = $langs->trans('BillStatusClosedPaidPartially'); $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially'); $statusType = 'status9'; - } elseif ($alreadypaid <= 0) { + } elseif ($alreadypaid == 0) { $labelStatus = $langs->trans('BillStatusNotPaid'); $labelStatusShort = $langs->trans('Bill'.$prefix.'StatusNotPaid'); $statusType = 'status1'; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index c921a43002d..43c4d4088bf 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -1,7 +1,7 @@ * Copyright (C) 2005-2013 Regis Houssin - * Copyright (C) 2010-2015 Juanjo Menent + * Copyright (C) 2010-2020 Juanjo Menent * Copyright (C) 2012-2013 Christophe Battarel * Copyright (C) 2011-2019 Philippe Grand * Copyright (C) 2012-2015 Marcos García @@ -222,9 +222,9 @@ abstract class CommonObject * @var string * @see getFullAddress(), isInEEC(), country */ - public $country_code; + public $country_code; - /** + /** * @var string * @see getFullAddress() */ @@ -238,21 +238,27 @@ abstract class CommonObject /** * @var string - * @see getFullAddress(), state + * @see getFullAddress(), $state */ - public $state_code; + public $state_code; - /** - * @var string - * @see getFullAddress(), region + /** + * @var int + * @see getFullAddress(), $region_code, $region */ - public $region; + public $region_id; /** * @var string - * @see getFullAddress(), region + * @see getFullAddress(), $region_id, $region */ - public $region_code; + public $region_code; + + /** + * @var string + * @see getFullAddress(), $region_id, $region_code + */ + public $region; /** * @var int @@ -320,7 +326,7 @@ abstract class CommonObject * @var string * @see SetDocModel() */ - public $modelpdf; + public $model_pdf; /** * @var string @@ -393,48 +399,30 @@ abstract class CommonObject */ public $comments = array(); - /** - * @var int - * @see setIncoterms() - */ - public $fk_incoterms; - - /** - * @var string - * @see SetIncoterms() - */ - public $label_incoterms; - - /** - * @var string - * @see display_incoterms() - */ - public $location_incoterms; - /** * @var string The name */ public $name; - /** - * @var string The lastname - */ + /** + * @var string The lastname + */ public $lastname; - /** - * @var string The firstname - */ + /** + * @var string The firstname + */ public $firstname; - /** - * @var string The civility code, not an integer - */ + /** + * @var string The civility code, not an integer + */ public $civility_id; // Dates /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; /** @@ -521,16 +509,16 @@ abstract class CommonObject */ public function getFormatedCustomerRef($objref) { - global $hookmanager; + global $hookmanager; - $parameters = array('objref'=>$objref); - $action = ''; - $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) - { - return $hookmanager->resArray['objref']; - } - return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); + $parameters = array('objref'=>$objref); + $action = ''; + $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) + { + return $hookmanager->resArray['objref']; + } + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -541,16 +529,16 @@ abstract class CommonObject */ public function getFormatedSupplierRef($objref) { - global $hookmanager; + global $hookmanager; - $parameters = array('objref'=>$objref); - $action = ''; - $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) - { - return $hookmanager->resArray['objref']; - } - return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); + $parameters = array('objref'=>$objref); + $action = ''; + $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) + { + return $hookmanager->resArray['objref']; + } + return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : ''); } /** @@ -622,15 +610,15 @@ abstract class CommonObject $this->country = $tmparray['label']; } - if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $tmparray = getState($this->state_id, 'all', 0, 1); + if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + $tmparray = getState($this->state_id, 'all', 0, 1); $this->state_code = $tmparray['code']; $this->state = $tmparray['label']; $this->region_code = $tmparray['region_code']; $this->region = $tmparray['region']; - } + } return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode); } @@ -703,7 +691,7 @@ abstract class CommonObject if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) { - $out .= "\n"; + $out .= "\n"; $this->fetchValuesForExtraLanguages(); if (!is_object($form)) $form = new Form($this->db); $htmltext = ''; @@ -721,11 +709,11 @@ abstract class CommonObject if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { - $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state; - } else { - $out .= ($outdone ? ' - ' : '').$this->state; - } + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { + $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state; + } else { + $out .= ($outdone ? ' - ' : '').$this->state; + } $outdone++; } @@ -764,8 +752,8 @@ abstract class CommonObject } if (!empty($this->url)) { - //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank - $out .= dol_print_url($this->url, '_blank', 0, 1); + //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank + $out .= dol_print_url($this->url, '_blank', 0, 1); $outdone++; } @@ -890,7 +878,7 @@ abstract class CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add a link between element $this->element and a contact * @@ -902,7 +890,7 @@ abstract class CommonObject */ public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user, $langs; @@ -1007,7 +995,7 @@ abstract class CommonObject } else return 0; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Copy contact from one element to current * @@ -1017,7 +1005,7 @@ abstract class CommonObject */ public function copy_linked_contact($objFrom, $source = 'internal') { - // phpcs:enable + // phpcs:enable $contacts = $objFrom->liste_contact(-1, $source); foreach ($contacts as $contact) { @@ -1030,7 +1018,7 @@ abstract class CommonObject return 1; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a link to contact line * @@ -1042,12 +1030,12 @@ abstract class CommonObject */ public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0) { - // phpcs:enable + // phpcs:enable // Insert into database $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; $sql .= " statut = ".$statut; - if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'"; - if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'"; + if ($type_contact_id) $sql .= ", fk_c_type_contact = ".((int) $type_contact_id); + if ($fk_socpeople) $sql .= ", fk_socpeople = ".((int) $fk_socpeople); $sql .= " where rowid = ".$rowid; $resql = $this->db->query($sql); if ($resql) @@ -1059,7 +1047,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete a link to contact line * @@ -1069,7 +1057,7 @@ abstract class CommonObject */ public function delete_contact($rowid, $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user; @@ -1096,7 +1084,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete all links between an object $this and all its contacts * @@ -1106,7 +1094,7 @@ abstract class CommonObject */ public function delete_linked_contact($source = '', $code = '') { - // phpcs:enable + // phpcs:enable $temp = array(); $typeContact = $this->liste_type_contact($source, '', 0, 0, $code); @@ -1131,7 +1119,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get array of all contacts for an object * @@ -1143,7 +1131,7 @@ abstract class CommonObject */ public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '') { - // phpcs:enable + // phpcs:enable global $langs; $tab = array(); @@ -1234,7 +1222,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return array with list of possible values for type of contacts * @@ -1247,7 +1235,7 @@ abstract class CommonObject */ public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '') { - // phpcs:enable + // phpcs:enable global $langs; if (empty($order)) $order = 'position'; @@ -1303,6 +1291,8 @@ abstract class CommonObject // phpcs:enable global $langs, $conf; + $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda')); + $tab = array(); $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element"; @@ -1405,9 +1395,9 @@ abstract class CommonObject if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")"; if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")"; $sql .= " AND ec.fk_c_type_contact = tc.rowid"; - $sql .= " AND tc.element = '".$element."'"; - $sql .= " AND tc.source = '".$source."'"; - if ($code) $sql .= " AND tc.code = '".$code."'"; + $sql .= " AND tc.element = '".$this->db->escape($element)."'"; + $sql .= " AND tc.source = '".$this->db->escape($source)."'"; + if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'"; $sql .= " AND tc.active = 1"; if ($status) $sql .= " AND ec.statut = ".$status; @@ -1428,7 +1418,7 @@ abstract class CommonObject return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load object contact with id=$this->contact_id into $this->contact * @@ -1437,7 +1427,7 @@ abstract class CommonObject */ public function fetch_contact($contactid = null) { - // phpcs:enable + // phpcs:enable if (empty($contactid)) $contactid = $this->contact_id; if (empty($contactid)) return 0; @@ -1449,7 +1439,7 @@ abstract class CommonObject return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty * @@ -1458,7 +1448,7 @@ abstract class CommonObject */ public function fetch_thirdparty($force_thirdparty_id = 0) { - // phpcs:enable + // phpcs:enable global $conf; if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) @@ -1511,7 +1501,7 @@ abstract class CommonObject return $this->fetch($result->rowid); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load data for barcode into properties ->barcode_type* * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but @@ -1521,7 +1511,7 @@ abstract class CommonObject */ public function fetch_barcode() { - // phpcs:enable + // phpcs:enable global $conf; dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); @@ -1560,7 +1550,7 @@ abstract class CommonObject return 0; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the project with id $this->fk_project into this->project * @@ -1568,7 +1558,7 @@ abstract class CommonObject */ public function fetch_projet() { - // phpcs:enable + // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility @@ -1582,7 +1572,7 @@ abstract class CommonObject return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the product with id $this->fk_product into this->product * @@ -1590,7 +1580,7 @@ abstract class CommonObject */ public function fetch_product() { - // phpcs:enable + // phpcs:enable include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (empty($this->fk_product)) return 0; @@ -1602,7 +1592,7 @@ abstract class CommonObject return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load the user with id $userid into this->user * @@ -1611,14 +1601,14 @@ abstract class CommonObject */ public function fetch_user($userid) { - // phpcs:enable + // phpcs:enable $user = new User($this->db); $result = $user->fetch($userid); $this->user = $user; return $result; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Read linked origin object * @@ -1626,10 +1616,10 @@ abstract class CommonObject */ public function fetch_origin() { - // phpcs:enable + // phpcs:enable if ($this->origin == 'shipping') $this->origin = 'expedition'; if ($this->origin == 'delivery') $this->origin = 'livraison'; - if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur'; + if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur'; $origin = $this->origin; @@ -1639,14 +1629,14 @@ abstract class CommonObject } /** - * Load object from specific field - * - * @param string $table Table element or element line - * @param string $field Field selected - * @param string $key Import key - * @param string $element Element name - * @return int <0 if KO, >0 if OK - */ + * Load object from specific field + * + * @param string $table Table element or element line + * @param string $field Field selected + * @param string $key Import key + * @param string $element Element name + * @return int <0 if KO, >0 if OK + */ public function fetchObjectFrom($table, $field, $key, $element = null) { global $conf; @@ -1781,7 +1771,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load properties id_previous and id_next by comparing $fieldid with $this->ref * @@ -1792,7 +1782,7 @@ abstract class CommonObject */ public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0) { - // phpcs:enable + // phpcs:enable global $conf, $user; if (!$this->table_element) @@ -1822,7 +1812,7 @@ abstract class CommonObject } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid=='rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; if (!empty($filter)) @@ -1875,7 +1865,7 @@ abstract class CommonObject } elseif ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid elseif ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc"; - $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid=='rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) + $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)'; if (!empty($filter)) @@ -2255,29 +2245,29 @@ abstract class CommonObject */ public function setRetainedWarrantyPaymentTerms($id) { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'retained_warranty_fk_cond_reglement'; + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'retained_warranty_fk_cond_reglement'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->retained_warranty_fk_cond_reglement = $id; - return 1; - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible'); - $this->error = 'Status of the object is incompatible '.$this->statut; - return -2; - } + if ($this->db->query($sql)) + { + $this->retained_warranty_fk_cond_reglement = $id; + return 1; + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Erreur '.$sql.' - '.$this->db->error()); + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible'); + $this->error = 'Status of the object is incompatible '.$this->statut; + return -2; + } } /** @@ -2421,7 +2411,8 @@ abstract class CommonObject $resql = $this->db->query($sql); if ($resql) { - $this->modelpdf = $modelpdf; + $this->model_pdf = $modelpdf; + $this->modelpdf = $modelpdf; // For bakward compatibility return 1; } else { dol_print_error($this->db); @@ -2489,7 +2480,7 @@ abstract class CommonObject // TODO: Move line related operations to CommonObjectLine? - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Save a new position (field rang) for details lines. * You can choose to set position for lines with already a position or lines without any position defined. @@ -2501,7 +2492,7 @@ abstract class CommonObject */ public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable if (!$this->table_element_line) { dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR); @@ -2605,7 +2596,7 @@ abstract class CommonObject return $rows; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a line to have a lower rank * @@ -2615,7 +2606,7 @@ abstract class CommonObject */ public function line_up($rowid, $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable $this->line_order(false, 'ASC', $fk_parent_line); // Get rang of line @@ -2625,7 +2616,7 @@ abstract class CommonObject $this->updateLineUp($rowid, $rang); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update a line to have a higher rank * @@ -2635,7 +2626,7 @@ abstract class CommonObject */ public function line_down($rowid, $fk_parent_line = true) { - // phpcs:enable + // phpcs:enable $this->line_order(false, 'ASC', $fk_parent_line); // Get rang of line @@ -2670,7 +2661,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update position of line with ajax (rang) * @@ -2679,7 +2670,7 @@ abstract class CommonObject */ public function line_ajaxorder($rows) { - // phpcs:enable + // phpcs:enable $num = count($rows); for ($i = 0; $i < $num; $i++) { @@ -2789,7 +2780,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Get max value used for position of line (rang) * @@ -2798,8 +2789,8 @@ abstract class CommonObject */ public function line_max($fk_parent_line = 0) { - // phpcs:enable - $positionfield = 'rang'; + // phpcs:enable + $positionfield = 'rang'; if ($this->table_element == 'bom') $positionfield = 'position'; // Search the last rang with fk_parent_line @@ -2837,7 +2828,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update external ref of element * @@ -2846,7 +2837,7 @@ abstract class CommonObject */ public function update_ref_ext($ref_ext) { - // phpcs:enable + // phpcs:enable if (!$this->table_element) { dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); @@ -2868,7 +2859,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update note of element * @@ -2878,7 +2869,7 @@ abstract class CommonObject */ public function update_note($note, $suffix = '') { - // phpcs:enable + // phpcs:enable global $user; if (!$this->table_element) @@ -2920,7 +2911,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update public note (kept for backward compatibility) * @@ -2931,11 +2922,11 @@ abstract class CommonObject */ public function update_note_public($note) { - // phpcs:enable + // phpcs:enable return $this->update_note($note, '_public'); } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). * Must be called at end of methods addline or updateline. @@ -2948,16 +2939,16 @@ abstract class CommonObject */ public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null) { - // phpcs:enable + // phpcs:enable global $conf, $hookmanager, $action; - $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller); - $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - return 1; // replacement code - } elseif ($reshook < 0) { - return -1; // failure - } // reshook = 0 => execute normal code + $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller); + $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + return 1; // replacement code + } elseif ($reshook < 0) { + return -1; // failure + } // reshook = 0 => execute normal code // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) $MODULE = ""; @@ -3298,16 +3289,16 @@ abstract class CommonObject { if ($justsource) { - $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; - if ($withtargettype) $sql .= " AND targettype = '".$targettype."'"; + $sql .= "fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; + if ($withtargettype) $sql .= " AND targettype = '".$this->db->escape($targettype)."'"; } elseif ($justtarget) { - $sql .= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; - if ($withsourcetype) $sql .= " AND sourcetype = '".$sourcetype."'"; + $sql .= "fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; + if ($withsourcetype) $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'"; } } else { - $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; - $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; + $sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."')"; + $sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."')"; } $sql .= ' ORDER BY '.$orderby; @@ -3840,7 +3831,7 @@ abstract class CommonObject } $weight = $line->weight ? $line->weight : 0; - ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; + ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0; $volume = $line->volume ? $line->volume : 0; ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0; @@ -3919,97 +3910,6 @@ abstract class CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return incoterms informations - * TODO Use a cache for label get - * - * @return string incoterms info - */ - public function display_incoterms() - { - // phpcs:enable - $out = ''; - $this->label_incoterms = ''; - if (!empty($this->fk_incoterms)) - { - $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $result = $this->db->query($sql); - if ($result) - { - $res = $this->db->fetch_object($result); - $out .= $res->code; - } - } - - $out .= (($res->code && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms; - - return $out; - } - - /** - * Return incoterms informations for pdf display - * - * @return string incoterms info - */ - public function getIncotermsForPDF() - { - $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num > 0) - { - $res = $this->db->fetch_object($resql); - return 'Incoterm : '.$res->code.' - '.$this->location_incoterms; - } else { - return ''; - } - } else { - $this->errors[] = $this->db->lasterror(); - return false; - } - } - - /** - * Define incoterms values of current object - * - * @param int $id_incoterm Id of incoterm to set or '' to remove - * @param string $location location of incoterm - * @return int <0 if KO, >0 if OK - */ - public function setIncoterms($id_incoterm, $location) - { - if ($this->id && $this->table_element) - { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); - $sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); - $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->fk_incoterms = $id_incoterm; - $this->location_incoterms = $location; - - $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; - $res = $this->db->query($sql); - if ($res) - { - $obj = $this->db->fetch_object($res); - $this->label_incoterms = $obj->libelle; - } - return 1; - } else { - $this->errors[] = $this->db->lasterror(); - return -1; - } - } else return -1; - } - - // -------------------- // TODO: All functions here must be redesigned and moved as they are not business functions but output functions // -------------------- @@ -4312,8 +4212,8 @@ abstract class CommonObject print ''.$langs->trans('Unit').''; } print ''.$langs->trans('ReductionShort').''; - print ''.$form->showCheckAddButtons('checkforselect', 1).''; - print ''; + print ''.$form->showCheckAddButtons('checkforselect', 1).''; + print ''; $i = 0; if (!empty($this->lines)) @@ -4370,7 +4270,7 @@ abstract class CommonObject if ($line->date_fin_reel) $date_end = $line->date_fin_reel; } - $this->tpl['id'] = $line->id; + $this->tpl['id'] = $line->id; $this->tpl['label'] = ''; if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow'); @@ -4442,10 +4342,10 @@ abstract class CommonObject $this->tpl['description'] = ' '; } - // VAT Rate - $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); - $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; - if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')'; + // VAT Rate + $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); + $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : ''; + if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')'; $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); @@ -4479,7 +4379,7 @@ abstract class CommonObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Add resources to the current object : add entry into llx_element_resources * Need $this->element & $this->id @@ -4492,7 +4392,7 @@ abstract class CommonObject */ public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0) { - // phpcs:enable + // phpcs:enable $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources ("; @@ -4523,7 +4423,7 @@ abstract class CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Delete a link to resource line * @@ -4534,7 +4434,7 @@ abstract class CommonObject */ public function delete_resource($rowid, $element, $notrigger = 0) { - // phpcs:enable + // phpcs:enable global $user; $this->db->begin(); @@ -4584,7 +4484,7 @@ abstract class CommonObject * Common function for all objects extending CommonObject for generating documents * * @param string $modelspath Relative folder where generators are placed - * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf','alpha') for example. + * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example. * @param Translate $outputlangs Output language to use * @param int $hidedetails 1 to hide details. 0 by default * @param int $hidedesc 1 to hide product description. 0 by default @@ -4604,245 +4504,245 @@ abstract class CommonObject if (empty($reshook)) { - dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - // Increase limit for PDF build - $err = error_reporting(); - error_reporting(0); - @set_time_limit(120); - error_reporting($err); + // Increase limit for PDF build + $err = error_reporting(); + error_reporting(0); + @set_time_limit(120); + error_reporting($err); - // If selected model is a filename template (then $modele="modelname" or "modelname:filename") - $tmp = explode(':', $modele, 2); - if (!empty($tmp[1])) - { - $modele = $tmp[0]; - $srctemplatepath = $tmp[1]; - } + // If selected model is a filename template (then $modele="modelname" or "modelname:filename") + $tmp = explode(':', $modele, 2); + if (!empty($tmp[1])) + { + $modele = $tmp[0]; + $srctemplatepath = $tmp[1]; + } - // Search template files + // Search template files $file = ''; $classname = ''; $filefound = ''; - $dirmodels = array('/'); - if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - foreach (array('doc', 'pdf') as $prefix) - { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php - else $file = $prefix."_".$modele.".modules.php"; + $dirmodels = array('/'); + if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + foreach (array('doc', 'pdf') as $prefix) + { + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + else $file = $prefix."_".$modele.".modules.php"; - // On verifie l'emplacement du modele - $file = dol_buildpath($reldir.$modelspath.$file, 0); - if (file_exists($file)) - { - $filefound = $file; - $classname = $prefix.'_'.$modele; - break; - } - } - if ($filefound) break; - } + // On verifie l'emplacement du modele + $file = dol_buildpath($reldir.$modelspath.$file, 0); + if (file_exists($file)) + { + $filefound = $file; + $classname = $prefix.'_'.$modele; + break; + } + } + if ($filefound) break; + } - // If generator was found - if ($filefound) - { - global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. + // If generator was found + if ($filefound) + { + global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. - require_once $file; + require_once $file; - $obj = new $classname($this->db); + $obj = new $classname($this->db); - // If generator is ODT, we must have srctemplatepath defined, if not we set it. - if ($obj->type == 'odt' && empty($srctemplatepath)) - { - $varfortemplatedir = $obj->scandir; - if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) - { - $dirtoscan = $conf->global->$varfortemplatedir; + // If generator is ODT, we must have srctemplatepath defined, if not we set it. + if ($obj->type == 'odt' && empty($srctemplatepath)) + { + $varfortemplatedir = $obj->scandir; + if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) + { + $dirtoscan = $conf->global->$varfortemplatedir; - $listoffiles = array(); + $listoffiles = array(); - // Now we add first model found in directories scanned - $listofdir = explode(',', $dirtoscan); - 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)) - { - $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); - } - } + // Now we add first model found in directories scanned + $listofdir = explode(',', $dirtoscan); + 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)) + { + $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); + if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + } + } - if (count($listoffiles)) - { - foreach ($listoffiles as $record) - { - $srctemplatepath = $record['fullname']; - break; - } - } - } + if (count($listoffiles)) + { + foreach ($listoffiles as $record) + { + $srctemplatepath = $record['fullname']; + break; + } + } + } - if (empty($srctemplatepath)) - { - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; - return -1; - } - } + if (empty($srctemplatepath)) + { + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined'; + return -1; + } + } - if ($obj->type == 'odt' && !empty($srctemplatepath)) - { - if (!dol_is_file($srctemplatepath)) - { - dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); - $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } + if ($obj->type == 'odt' && !empty($srctemplatepath)) + { + if (!dol_is_file($srctemplatepath)) + { + dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); + $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + return -1; + } + } - // 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; + // 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 (in_array(get_class($this), array('Adherent'))) - { - $arrayofrecords = array(); // The write_file of templates of adherent class need this var - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); - } else { - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); - } - // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. + if (in_array(get_class($this), array('Adherent'))) + { + $arrayofrecords = array(); // The write_file of templates of adherent class need this var + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + } else { + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. - if ($resultwritefile > 0) - { - $outputlangs->charset_output = $sav_charset_output; + if ($resultwritefile > 0) + { + $outputlangs->charset_output = $sav_charset_output; - // We delete old preview - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_delete_preview($this); + // We delete old preview + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_delete_preview($this); - // Index file in database - if (!empty($obj->result['fullpath'])) - { - $destfull = $obj->result['fullpath']; - $upload_dir = dirname($destfull); - $destfile = basename($destfull); - $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); + // Index file in database + if (!empty($obj->result['fullpath'])) + { + $destfull = $obj->result['fullpath']; + $upload_dir = dirname($destfull); + $destfile = basename($destfull); + $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir); - if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir - { - $filename = basename($destfile); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + { + $filename = basename($destfile); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile = new EcmFiles($this->db); - $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile = new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename); - // Set the public "share" key - $setsharekey = false; - if ($this->element == 'propal') - { - $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok - if ($useonlinesignature) $setsharekey = true; - if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; - } - if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } - if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { - $setsharekey = true; - } + // Set the public "share" key + $setsharekey = false; + if ($this->element == 'propal') + { + $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok + if ($useonlinesignature) $setsharekey = true; + if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true; + } + if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } + if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) { + $setsharekey = true; + } - if ($setsharekey) { - if (empty($ecmfile->share)) // Because object not found or share not set yet - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $ecmfile->share = getRandomPassword(true); - } - } + if ($setsharekey) { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } - if ($result > 0) - { - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->update($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } else { - $ecmfile->entity = $conf->entity; - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content - $ecmfile->fullpath_orig = ''; - $ecmfile->gen_or_uploaded = 'generated'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $ecmfile->src_object_type = $this->table_element; - $ecmfile->src_object_id = $this->id; + if ($result > 0) + { + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->update($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } else { + $ecmfile->entity = $conf->entity; + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $ecmfile->src_object_type = $this->table_element; + $ecmfile->src_object_id = $this->id; - $result = $ecmfile->create($user); - if ($result < 0) { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } + $result = $ecmfile->create($user); + if ($result < 0) { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } - /*$this->result['fullname']=$destfull; + /*$this->result['fullname']=$destfull; $this->result['filepath']=$ecmfile->filepath; $this->result['filename']=$ecmfile->filename;*/ - //var_dump($obj->update_main_doc_field);exit; + //var_dump($obj->update_main_doc_field);exit; - // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) - $update_main_doc_field = 0; - if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; - if ($update_main_doc_field && !empty($this->table_element)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; - $sql .= ' WHERE rowid = '.$this->id; + // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) + $update_main_doc_field = 0; + if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; + if ($update_main_doc_field && !empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql .= ' WHERE rowid = '.$this->id; - $resql = $this->db->query($sql); - if (!$resql) { + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); } else { - $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; - } - } - } - } else { - dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); - } + $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename; + } + } + } + } else { + dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING); + } - // Success in building document. We build meta file. - dol_meta_create($this); + // Success in building document. We build meta file. + dol_meta_create($this); - return 1; - } else { - $outputlangs->charset_output = $sav_charset_output; - dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); - return -1; - } - } else { - if (! $filefound) { - $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; - dol_print_error('', $this->error); - } else { - $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); - dol_print_error('', $this->error); - } - return -1; - } + return 1; + } else { + $outputlangs->charset_output = $sav_charset_output; + dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors); + return -1; + } + } else { + if (!$filefound) { + $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele; + dol_print_error('', $this->error); + } else { + $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound); + dol_print_error('', $this->error); + } + return -1; + } } else return $reshook; } @@ -4987,7 +4887,7 @@ abstract class CommonObject // Request to get translation values for object $sql = "SELECT rowid, property, lang , value"; $sql .= " FROM ".MAIN_DB_PREFIX."object_lang"; - $sql .= " WHERE type_object = '".$element."'"; + $sql .= " WHERE type_object = '".$this->db->escape($element)."'"; $sql .= " AND fk_object = ".$this->id; //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose @@ -5187,7 +5087,7 @@ abstract class CommonObject } } $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql .= " WHERE fk_object = ".$rowid; + $sql .= " WHERE fk_object = ".((int) $rowid); //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose $resql = $this->db->query($sql); @@ -5324,7 +5224,7 @@ abstract class CommonObject if ($this->array_options[$key] === '') $mandatorypb = true; if ($mandatorypb) { - dol_syslog("Mandatory extra field ".$key." is empty"); + dol_syslog("Mandatory extra field ".$key." is empty"); $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel); return -1; } @@ -5338,8 +5238,8 @@ abstract class CommonObject if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) { $value = dol_eval($attrfieldcomputed, 1, 0); - dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); - $new_array_options[$key] = $value; + dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); + $new_array_options[$key] = $value; } else { $new_array_options[$key] = null; } @@ -5470,13 +5370,13 @@ abstract class CommonObject // We must insert a default value for fields for other entities that are mandatory to avoid not null error if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) - { - if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously - { - $sql .= ",".$tmpkey; - } - } + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + { + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + { + $sql .= ",".$tmpkey; + } + } } $sql .= ") VALUES (".$this->id; @@ -5497,14 +5397,14 @@ abstract class CommonObject // We must insert a default value for fields for other entities that are mandatory to avoid not null error if (is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) { - foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) - { - if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously - { - if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0"; - else $sql .= ", ''"; - } - } + foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) + { + if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) // If field not already added previously + { + if (in_array($tmpval, array('int', 'double', 'price'))) $sql .= ", 0"; + else $sql .= ", ''"; + } + } } $sql .= ")"; @@ -5833,38 +5733,38 @@ abstract class CommonObject } $out = ''; - $type = ''; - $param = array(); - $param['options'] = array(); - $reg = array(); - $size = $this->fields[$key]['size']; - // Because we work on extrafields - if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); - $type = 'link'; - } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type = 'link'; - } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[2].':'.$reg[3] => 'N'); - $type = 'link'; - } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); - $type = 'sellist'; - } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { - $param['options'] = array(); - $type = 'varchar'; - $size = $reg[1]; - } elseif (preg_match('/varchar/', $val['type'])) { - $param['options'] = array(); - $type = 'varchar'; - } elseif (is_array($this->fields[$key]['arrayofkeyval'])) { - $param['options'] = $this->fields[$key]['arrayofkeyval']; - $type = 'select'; - } else { - $param['options'] = array(); - $type = $this->fields[$key]['type']; - } + $type = ''; + $param = array(); + $param['options'] = array(); + $reg = array(); + $size = $this->fields[$key]['size']; + // Because we work on extrafields + if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'link'; + } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3] => 'N'); + $type = 'link'; + } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { + $param['options'] = array(); + $type = 'varchar'; + $size = $reg[1]; + } elseif (preg_match('/varchar/', $val['type'])) { + $param['options'] = array(); + $type = 'varchar'; + } elseif (is_array($this->fields[$key]['arrayofkeyval'])) { + $param['options'] = $this->fields[$key]['arrayofkeyval']; + $type = 'select'; + } else { + $param['options'] = array(); + $type = $this->fields[$key]['type']; + } $label = $this->fields[$key]['label']; //$elementtype=$this->fields[$key]['elementtype']; // Seems not used @@ -5887,11 +5787,9 @@ abstract class CommonObject } // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine - if (empty($morecss) && !empty($val['css'])) - { - $morecss = $val['css']; - } elseif (empty($morecss)) - { + if (empty($morecss) && !empty($val['css'])) { + $morecss = $val['css']; + } elseif (empty($morecss)) { if ($type == 'date') { $morecss = 'minwidth100imp'; @@ -5938,17 +5836,17 @@ abstract class CommonObject { $tmp = explode(',', $size); $newsize = $tmp[0]; - $out = ''; + $out = ''; } elseif (in_array($type, array('real'))) { - $out = ''; + $out = ''; } elseif (preg_match('/varchar/', $type)) { - $out = ''; + $out = ''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out = ''; - } elseif ($type == 'text') + $out = ''; + } elseif (preg_match('/^text/', $type)) { if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { @@ -5958,7 +5856,7 @@ abstract class CommonObject } else { $out = ''; } - } elseif ($type == 'html') + } elseif (preg_match('/^html/', $type)) { if (!preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field { @@ -5999,7 +5897,7 @@ abstract class CommonObject } $out .= ''; } elseif ($type == 'checkbox') @@ -1296,8 +1309,8 @@ class ExtraFields // 2 : key fields name (if differ of rowid) // 3 : key field parent (for dependent lists) // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value - // 5 : id category type - // 6 : ids categories list separated by comma for category root + // 5 : id category type + // 6 : ids categories list separated by comma for category root $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { @@ -1312,173 +1325,173 @@ class ExtraFields } } - $filter_categorie = false; - if (count($InfoFieldList) > 5) { - if ($InfoFieldList[0] == 'categorie') { - $filter_categorie = true; - } - } + $filter_categorie = false; + if (count($InfoFieldList) > 5) { + if ($InfoFieldList[0] == 'categorie') { + $filter_categorie = true; + } + } - if ($filter_categorie === false) { - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $keyList .= ', '; - $keyList .= implode(', ', $fields_label); - } + if ($filter_categorie === false) { + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } - $sqlwhere = ''; - $sql = 'SELECT '.$keyList; - $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; - if (!empty($InfoFieldList[4])) { - // can use SELECT request - if (strpos($InfoFieldList[4], '$SEL$') !== false) { - $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); - } + $sqlwhere = ''; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; + if (!empty($InfoFieldList[4])) { + // can use SELECT request + if (strpos($InfoFieldList[4], '$SEL$') !== false) { + $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]); + } - // current object id can be use into filter - if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { - $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); - } elseif (preg_match("#^.*list.php$#", $_SERVER["PHP_SELF"])) { - // Pattern for word=$ID$ - $word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$'; + // current object id can be use into filter + if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) { + $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]); + } elseif (preg_match("#^.*list.php$#", $_SERVER["PHP_SELF"])) { + // Pattern for word=$ID$ + $word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$'; - // Removing space arount =, ( and ) - $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); + // Removing space arount =, ( and ) + $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); - $nbPreg = 1; - // While we have parenthesis - while ($nbPreg != 0) { - // Init des compteurs - $nbPregRepl = $nbPregSel = 0; - // On retire toutes les parenthèses sans = avant - $InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*('.$word.')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl); - // On retire les espaces autour des = et parenthèses - $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); - // On retire toutes les parenthèses avec = avant - $InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*('.$word.')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel); - // On retire les espaces autour des = et parenthèses - $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); + $nbPreg = 1; + // While we have parenthesis + while ($nbPreg != 0) { + // Init des compteurs + $nbPregRepl = $nbPregSel = 0; + // On retire toutes les parenthèses sans = avant + $InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*('.$word.')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl); + // On retire les espaces autour des = et parenthèses + $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); + // On retire toutes les parenthèses avec = avant + $InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*('.$word.')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel); + // On retire les espaces autour des = et parenthèses + $InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]); - // Calcul du compteur général pour la boucle - $nbPreg = $nbPregRepl + $nbPregSel; - } + // Calcul du compteur général pour la boucle + $nbPreg = $nbPregRepl + $nbPregSel; + } - // Si l'on a un AND ou un OR, avant ou après - preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); - while (!empty($matchCondition[0])) { - // If the two sides differ but are not empty - if (!empty($matchCondition[1]) && !empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3]) { - // Nobody sain would do that without parentheses - $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); - } else { - if (!empty($matchCondition[1])) { - $boolCond = (($matchCondition[1] == "AND") ? ' AND TRUE ' : ' OR FALSE '); - $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond.$matchCondition[3], $InfoFieldList[4]); - } elseif (!empty($matchCondition[3])) { - $boolCond = (($matchCondition[3] == "AND") ? ' TRUE AND ' : ' FALSE OR'); - $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond, $InfoFieldList[4]); - } else { - $InfoFieldList[4] = " TRUE "; - } - } + // Si l'on a un AND ou un OR, avant ou après + preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); + while (!empty($matchCondition[0])) { + // If the two sides differ but are not empty + if (!empty($matchCondition[1]) && !empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3]) { + // Nobody sain would do that without parentheses + $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); + } else { + if (!empty($matchCondition[1])) { + $boolCond = (($matchCondition[1] == "AND") ? ' AND TRUE ' : ' OR FALSE '); + $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond.$matchCondition[3], $InfoFieldList[4]); + } elseif (!empty($matchCondition[3])) { + $boolCond = (($matchCondition[3] == "AND") ? ' TRUE AND ' : ' FALSE OR'); + $InfoFieldList[4] = str_replace($matchCondition[0], $boolCond, $InfoFieldList[4]); + } else { + $InfoFieldList[4] = " TRUE "; + } + } - // Si l'on a un AND ou un OR, avant ou après - preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); - } - } else { - $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); - } + // Si l'on a un AND ou un OR, avant ou après + preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition); + } + } else { + $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]); + } - // We have to join on extrafield table - if (strpos($InfoFieldList[4], 'extra.') !== false) { - $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; - $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; - } else { - $sqlwhere .= ' WHERE '.$InfoFieldList[4]; - } - } else { - $sqlwhere .= ' WHERE 1=1'; - } - // Some tables may have field, some other not. For the moment we disable it. - if (in_array($InfoFieldList[0], array('tablewithentity'))) { - $sqlwhere .= ' AND entity = '.$conf->entity; - } - // $sql.=preg_replace('/^ AND /','',$sqlwhere); - // print $sql; + // We have to join on extrafield table + if (strpos($InfoFieldList[4], 'extra.') !== false) { + $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4]; + } else { + $sqlwhere .= ' WHERE '.$InfoFieldList[4]; + } + } else { + $sqlwhere .= ' WHERE 1=1'; + } + // Some tables may have field, some other not. For the moment we disable it. + if (in_array($InfoFieldList[0], array('tablewithentity'))) { + $sqlwhere .= ' AND entity = '.$conf->entity; + } + // $sql.=preg_replace('/^ AND /','',$sqlwhere); + // print $sql; - $sql .= $sqlwhere; - dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) { - $num = $this->db->num_rows($resql); - $i = 0; + $sql .= $sqlwhere; + dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; - $data = array(); + $data = array(); - while ($i < $num) { - $labeltoshow = ''; - $obj = $this->db->fetch_object($resql); + while ($i < $num) { + $labeltoshow = ''; + $obj = $this->db->fetch_object($resql); - $notrans = false; - // Several field into label (eq table:code|libelle:rowid) - $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) { - $notrans = true; - foreach ($fields_label as $field_toshow) { - $labeltoshow .= $obj->$field_toshow.' '; - } - } else { - $labeltoshow = $obj->{$InfoFieldList[1]}; - } - $labeltoshow = dol_trunc($labeltoshow, 45); + $notrans = false; + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $notrans = true; + foreach ($fields_label as $field_toshow) { + $labeltoshow .= $obj->$field_toshow.' '; + } + } else { + $labeltoshow = $obj->{$InfoFieldList[1]}; + } + $labeltoshow = dol_trunc($labeltoshow, 45); - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - foreach ($fields_label as $field_toshow) { - $translabel = $langs->trans($obj->$field_toshow); - if ($translabel != $obj->$field_toshow) { - $labeltoshow = dol_trunc($translabel, 18).' '; - } else { - $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; - } - } + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + foreach ($fields_label as $field_toshow) { + $translabel = $langs->trans($obj->$field_toshow); + if ($translabel != $obj->$field_toshow) { + $labeltoshow = dol_trunc($translabel, 18).' '; + } else { + $labeltoshow = dol_trunc($obj->$field_toshow, 18).' '; + } + } - $data[$obj->rowid] = $labeltoshow; - } else { - if (!$notrans) { - $translabel = $langs->trans($obj->{$InfoFieldList[1]}); - if ($translabel != $obj->{$InfoFieldList[1]}) { - $labeltoshow = dol_trunc($translabel, 18); - } else { - $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); - } - } - if (empty($labeltoshow)) - $labeltoshow = '(not defined)'; + $data[$obj->rowid] = $labeltoshow; + } else { + if (!$notrans) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + if ($translabel != $obj->{$InfoFieldList[1]}) { + $labeltoshow = dol_trunc($translabel, 18); + } else { + $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); + } + } + if (empty($labeltoshow)) + $labeltoshow = '(not defined)'; - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { - $data[$obj->rowid] = $labeltoshow; - } + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid] = $labeltoshow; + } - if (!empty($InfoFieldList[3]) && $parentField) { - $parent = $parentName.':'.$obj->{$parentField}; - } + if (!empty($InfoFieldList[3]) && $parentField) { + $parent = $parentName.':'.$obj->{$parentField}; + } - $data[$obj->rowid] = $labeltoshow; - } + $data[$obj->rowid] = $labeltoshow; + } - $i++; - } - $this->db->free($resql); + $i++; + } + $this->db->free($resql); - $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); - } else { - print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; - } - } else { + $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); + } else { + print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.
'; + } + } else { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1); - $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); - } + $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1); + $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); + } } } elseif ($type == 'link') { @@ -1664,9 +1677,9 @@ class ExtraFields $translabel = $langs->trans($obj->$field_toshow); } if ($translabel != $field_toshow) { - $value .= dol_trunc($translabel, 18) . ' '; + $value .= dol_trunc($translabel, 18).' '; } else { - $value .= $obj->$field_toshow . ' '; + $value .= $obj->$field_toshow.' '; } } } else { @@ -1681,7 +1694,7 @@ class ExtraFields } } } else { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $toprint = array(); $obj = $this->db->fetch_object($resql); @@ -1689,7 +1702,7 @@ class ExtraFields $c->fetch($obj->rowid); $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text foreach ($ways as $way) { - $toprint[] = '
  • color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '
  • '; + $toprint[] = '
  • color ? ' style="background: #'.$c->color.';"' : ' style="background: #aaa"').'>'.img_object('', 'category').' '.$way.'
  • '; } $value = '
      '.implode(' ', $toprint).'
    '; } @@ -1762,9 +1775,9 @@ class ExtraFields $translabel = $langs->trans($obj->$field_toshow); } if ($translabel != $field_toshow) { - $toprint[] = '
  • ' . dol_trunc($translabel, 18) . '
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[] = '
  • ' . $obj->$field_toshow . '
  • '; + $toprint[] = '
  • '.$obj->$field_toshow.'
  • '; } } } else { @@ -1773,15 +1786,15 @@ class ExtraFields $translabel = $langs->trans($obj->{$InfoFieldList[1]}); } if ($translabel != $obj->{$InfoFieldList[1]}) { - $toprint[] = '
  • ' . dol_trunc($translabel, 18) . '
  • '; + $toprint[] = '
  • '.dol_trunc($translabel, 18).'
  • '; } else { - $toprint[] = '
  • ' . $obj->{$InfoFieldList[1]} . '
  • '; + $toprint[] = '
  • '.$obj->{$InfoFieldList[1]}.'
  • '; } } } } } else { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $toprint = array(); while ($obj = $this->db->fetch_object($resql)) { @@ -1790,7 +1803,7 @@ class ExtraFields $c->fetch($obj->rowid); $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text foreach ($ways as $way) { - $toprint[] = '
  • color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '
  • '; + $toprint[] = '
  • color ? ' style="background: #'.$c->color.';"' : ' style="background: #aaa"').'>'.img_object('', 'category').' '.$way.'
  • '; } } } @@ -1861,7 +1874,7 @@ class ExtraFields $align = ''; - if ($type == 'date') + if ($type == 'date') { $align = "center"; } elseif ($type == 'datetime') @@ -1909,43 +1922,43 @@ class ExtraFields $out .= $langs->trans($this->attributes[$object->table_element]['label'][$key]); $out .= ''; - $extrafield_param = $this->attributes[$object->table_element]['param'][$key]; - if (!empty($extrafield_param) && is_array($extrafield_param)) { - $extrafield_param_list = array_keys($extrafield_param['options']); + $extrafield_param = $this->attributes[$object->table_element]['param'][$key]; + if (!empty($extrafield_param) && is_array($extrafield_param)) { + $extrafield_param_list = array_keys($extrafield_param['options']); - if (count($extrafield_param_list) > 0) { - $extrafield_collapse_display_value = intval($extrafield_param_list[0]); - if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) { - // Set the collapse_display status to cookie in priority or if ignorecollapsesetup is 1, if cookie and ignorecollapsesetup not defined, use the setup. - $collapse_display = ((isset($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key]) || GETPOST('ignorecollapsesetup', 'int')) ? ($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key] ? true : false) : ($extrafield_collapse_display_value == 2 ? false : true)); - $extrafields_collapse_num = $this->attributes[$object->table_element]['pos'][$key]; + if (count($extrafield_param_list) > 0) { + $extrafield_collapse_display_value = intval($extrafield_param_list[0]); + if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) { + // Set the collapse_display status to cookie in priority or if ignorecollapsesetup is 1, if cookie and ignorecollapsesetup not defined, use the setup. + $collapse_display = ((isset($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key]) || GETPOST('ignorecollapsesetup', 'int')) ? ($_COOKIE['DOLCOLLAPSE_'.$object->table_element.'_extrafields_'.$key] ? true : false) : ($extrafield_collapse_display_value == 2 ? false : true)); + $extrafields_collapse_num = $this->attributes[$object->table_element]['pos'][$key]; - $out .= ''; - $out .= ''; - } - } - } + $out .= ''; + $out .= ''; + } + } + } return $out; } @@ -1975,7 +1988,7 @@ class ExtraFields foreach ($extralabels as $key => $value) { if (!empty($onlykey) && $onlykey != '@GETPOSTISSET' && $key != $onlykey) continue; - if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && ! GETPOSTISSET('options_'.$key)) continue; + if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && !GETPOSTISSET('options_'.$key)) continue; $key_type = $this->attributes[$object->table_element]['type'][$key]; if ($key_type == 'separate') continue; @@ -1996,8 +2009,8 @@ class ExtraFields if ($this->attributes[$object->table_element]['required'][$key]) // Value is required { // Check if empty without using GETPOST, value can be alpha, int, array, etc... - if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0') - || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select') + if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0') + || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select') || (is_array($_POST["options_".$key]) && empty($_POST["options_".$key]))) { //print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key]; diff --git a/htdocs/core/class/fiscalyear.class.php b/htdocs/core/class/fiscalyear.class.php index 0686b68115a..c0216f16a19 100644 --- a/htdocs/core/class/fiscalyear.class.php +++ b/htdocs/core/class/fiscalyear.class.php @@ -35,6 +35,8 @@ class Fiscalyear extends CommonObject */ public $element = 'fiscalyear'; + public $picto = 'technic'; + /** * @var string Name of table without prefix where object is stored */ @@ -97,6 +99,7 @@ class Fiscalyear extends CommonObject public $statuts = array(); public $statuts_short = array(); + /** * Constructor * @@ -267,6 +270,78 @@ class Fiscalyear extends CommonObject } } + /** + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $notooltip = 0, $save_lastsearch_value = -1) + { + global $conf, $langs, $user; + + if (empty($this->ref)) $this->ref = $this->id; + + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + + $result = ''; + + $url = DOL_URL_ROOT.'/accountancy/admin/fiscalyear_card.php?id='.$this->id; + + if (!$user->rights->accounting->fiscalyear->write) + $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 = ''; + + if ($user->rights->accounting->fiscalyear->write) { + $label = ''.$langs->trans("FiscalPeriod").''; + $label .= '
    '.$langs->trans('Ref').': '.$this->id; + if (isset($this->statut)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } + } + + $linkclose = ''; + if (empty($notooltip) && $user->rights->accounting->fiscalyear->write) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("FiscalYear"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend = ''; + + if ($option === 'nolink') { + $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; + $result .= $linkend; + + return $result; + } + /** * Give a label from a status * diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php index 089e9fb6717..3c094ff5a6b 100644 --- a/htdocs/core/class/hookmanager.class.php +++ b/htdocs/core/class/hookmanager.class.php @@ -30,9 +30,9 @@ class HookManager { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -44,18 +44,18 @@ class HookManager */ public $errors = array(); - // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...) - public $contextarray = array(); + // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...) + public $contextarray = array(); // Array with instantiated classes - public $hooks = array(); + public $hooks = array(); // Array result - public $resArray = array(); + public $resArray = array(); // Printable result - public $resPrint = ''; + public $resPrint = ''; // Nb of qualified hook ran - public $resNbOfHooks = 0; + public $resNbOfHooks = 0; /** * Constructor @@ -84,9 +84,9 @@ class HookManager global $conf; // Test if there is hooks to manage - if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return; + if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return; - // For backward compatibility + // For backward compatibility if (!is_array($arraycontext)) $arraycontext = array($arraycontext); $this->contextarray = array_unique(array_merge($arraycontext, $this->contextarray)); // All contexts are concatenated @@ -130,28 +130,29 @@ class HookManager return 1; } - /** - * Execute hooks (if they were initialized) for the given method - * - * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...) - * @param array $parameters Array of parameters - * @param Object $object Object to use hooks on - * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) - * @return mixed For 'addreplace' hooks (doActions,formObjectOptions,pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. - * For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...): Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. - * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller. - * $this->error or this->errors are also defined by class called by this function if error. - */ + /** + * Execute hooks (if they were initialized) for the given method + * + * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...) + * @param array $parameters Array of parameters + * @param Object $object Object to use hooks on + * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) + * @return mixed For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. + * For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...): Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. + * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller. + * $this->error or this->errors are also defined by class called by this function if error. + */ public function executeHooks($method, $parameters = array(), &$object = '', &$action = '') { - if (!is_array($this->hooks) || empty($this->hooks)) return ''; + if (!is_array($this->hooks) || empty($this->hooks)) return 0; // No hook available, do nothing. - $parameters['context'] = join(':', $this->contextarray); - //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']); + $parameters['context'] = join(':', $this->contextarray); + //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']); - // Define type of hook ('output' or 'addreplace'). Type 'returnvalue' is deprecated because a 'addreplace' hook can also return resPrint and resArray). - $hooktype = 'output'; - if (in_array( + // Define type of hook ('output' or 'addreplace'). + // TODO Remove hooks with type 'output'. All hooks must be converted into 'addreplace' hooks. + $hooktype = 'output'; + if (in_array( $method, array( 'addCalendarChoice', @@ -171,32 +172,33 @@ class HookManager 'formattachOptions', 'formBuilddocLineOptions', 'formatNotificationMessage', + 'formConfirm', 'getAccessForbiddenMessage', 'getDirList', 'getFormMail', 'getFormatedCustomerRef', - 'getFormatedSupplierRef', + 'getFormatedSupplierRef', 'getIdProfUrl', 'getInputIdProf', 'moveUploadedFile', 'moreHtmlStatus', 'pdf_build_address', 'pdf_writelinedesc', - 'pdf_getlinenum', - 'pdf_getlineref', - 'pdf_getlineref_supplier', - 'pdf_getlinevatrate', - 'pdf_getlineupexcltax', - 'pdf_getlineupwithtax', - 'pdf_getlineqty', - 'pdf_getlineqty_asked', - 'pdf_getlineqty_shipped', - 'pdf_getlineqty_keeptoship', - 'pdf_getlineunit', - 'pdf_getlineremisepercent', - 'pdf_getlineprogress', - 'pdf_getlinetotalexcltax', - 'pdf_getlinetotalwithtax', + 'pdf_getlinenum', + 'pdf_getlineref', + 'pdf_getlineref_supplier', + 'pdf_getlinevatrate', + 'pdf_getlineupexcltax', + 'pdf_getlineupwithtax', + 'pdf_getlineqty', + 'pdf_getlineqty_asked', + 'pdf_getlineqty_shipped', + 'pdf_getlineqty_keeptoship', + 'pdf_getlineunit', + 'pdf_getlineremisepercent', + 'pdf_getlineprogress', + 'pdf_getlinetotalexcltax', + 'pdf_getlinetotalwithtax', 'paymentsupplierinvoices', 'printAddress', 'printEmail', @@ -211,93 +213,88 @@ class HookManager 'showLinkToObjectBlock', 'setContentSecurityPolicy', 'setHtmlTitle', - 'completeTabsHead' + 'completeTabsHead' ) )) $hooktype = 'addreplace'; - if ($method == 'insertExtraFields') { - $hooktype = 'returnvalue'; // @deprecated. TODO Remove all code with "executeHooks('insertExtraFields'" as soon as there is a trigger available. - dol_syslog("Warning: The hook 'insertExtraFields' is deprecated and must not be used. Use instead trigger on CRUD event (ask it to dev team if not implemented)", LOG_WARNING); - } + // Init return properties + $this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0; - // Init return properties - $this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0; + // Loop on each hook to qualify modules that have declared context + $modulealreadyexecuted = array(); + $resaction = 0; $error = 0; + foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context + { + if (!empty($modules)) + { + foreach ($modules as $module => $actionclassinstance) + { + //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
    \n"; - // Loop on each hook to qualify modules that have declared context - $modulealreadyexecuted = array(); - $resaction = 0; $error = 0; $result = ''; - foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context - { - if (!empty($modules)) - { - foreach ($modules as $module => $actionclassinstance) - { - //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
    \n"; + // test to avoid running twice a hook, when a module implements several active contexts + if (in_array($module, $modulealreadyexecuted)) continue; - // test to avoid running twice a hook, when a module implements several active contexts - if (in_array($module, $modulealreadyexecuted)) continue; + // jump to next module/class if method does not exist + if (!method_exists($actionclassinstance, $method)) continue; - // jump to next module/class if method does not exist - if (!method_exists($actionclassinstance, $method)) continue; + $this->resNbOfHooks++; - $this->resNbOfHooks++; + $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice - $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice + // Clean class (an error may have been set from a previous call of another method for same module/hook) + $actionclassinstance->error = 0; + $actionclassinstance->errors = array(); - // Clean class (an error may have been set from a previous call of another method for same module/hook) - $actionclassinstance->error = 0; - $actionclassinstance->errors = array(); + dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG); - dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG); + // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return; + $parameters['currentcontext'] = $context; + // Hooks that must return int (hooks with type 'addreplace') + if ($hooktype == 'addreplace') + { + $resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) + if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) + { + $error++; + $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); + dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); + } - // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return; - $parameters['currentcontext'] = $context; - // Hooks that must return int (hooks with type 'addreplace') - if ($hooktype == 'addreplace') - { - $resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) - if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) - { - $error++; - $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); - dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); - } + if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); + if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; + } + // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...) + else { + // TODO. this test should be done into the method of hook by returning nothing + if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue; - if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); - if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; - } - // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...) - else { - // TODO. this test should be done into the method of hook by returning nothing - if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue; + //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); + $resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) - //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); - $resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) + if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); + if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; + if (is_numeric($resaction) && $resaction < 0) + { + $error++; + $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); + dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); + } + // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string + if (!is_array($resaction) && !is_numeric($resaction)) + { + dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR); + if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; } + } + } - if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); - if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; - if (is_numeric($resaction) && $resaction < 0) - { - $error++; - $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); - dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); - } - // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string - if (!is_array($resaction) && !is_numeric($resaction)) - { - dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR); - if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; } - } - } + //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
    \n"; - //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
    \n"; + unset($actionclassinstance->results); + unset($actionclassinstance->resprints); + } + } + } - unset($actionclassinstance->results); - unset($actionclassinstance->resprints); - } - } - } - - return ($error ?-1 : $resaction); + return ($error ? -1 : $resaction); } } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index c94b86e363c..9f9068bfcf4 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -200,12 +200,12 @@ class Form if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) { $tmp = explode(':', $typeofdata); - $ret .= ''; + $ret .= ''; } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) { $tmp = explode(':', $typeofdata); $valuetoshow = price2num($editvalue ? $editvalue : $value); - $ret .= ''; + $ret .= ''; } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor' { $tmp = explode(':', $typeofdata); @@ -218,7 +218,7 @@ class Form } $valuetoshow = ($editvalue ? $editvalue : $value); - $ret .= ''; + print ''; // Zip / Town print ''.$langs->trans("Zip").' / '.$langs->trans("Town").''; @@ -787,12 +787,12 @@ if (!empty($id) && $action != 'edit') if ($object->statut == 0) { - print ''; + print ''; } if (($object->statut == 0 || $object->statut == 1) && $totalpaid == 0 && $object->paid == 0) { - print '"; + print '"; } // Create payment @@ -817,7 +817,7 @@ if (!empty($id) && $action != 'edit') { if ($object->statut == -1 || $object->statut == 0) { - print '"; + print '"; } else { print '"; } @@ -839,7 +839,7 @@ if (!empty($id) && $action != 'edit') $genallowed = (($object->paid == 0 || $user->admin) && $user->rights->don->lire); $delallowed = $user->rights->don->creer; - print $formfile->showdocuments('donation', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf); + print $formfile->showdocuments('donation', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('don')); diff --git a/htdocs/don/class/api_donations.class.php b/htdocs/don/class/api_donations.class.php index 5d35b24707f..2d61241c738 100644 --- a/htdocs/don/class/api_donations.class.php +++ b/htdocs/don/class/api_donations.class.php @@ -127,7 +127,7 @@ class Donations extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -135,21 +135,21 @@ class Donations extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; while ($i < $min) { - $obj = $db->fetch_object($result); - $don_static = new Don($db); + $obj = $this->db->fetch_object($result); + $don_static = new Don($this->db); if ($don_static->fetch($obj->rowid)) { // Add external contacts ids //$don_static->contacts_ids = $don_static->liste_contact(-1, 'external', 1); @@ -158,7 +158,7 @@ class Donations extends DolibarrApi $i++; } } else { - throw new RestException(503, 'Error when retrieve donation list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve donation list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No donation found'); diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index 6b6cbb3d36e..3ccaa573e8c 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -36,12 +36,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class Don extends CommonObject { - /** + /** * @var string ID to identify managed object */ public $element = 'don'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'don'; @@ -57,7 +57,7 @@ class Don extends CommonObject */ public $ismultientitymanaged = 1; - /** + /** * @var string String with name of icon for object don. Must be the part after the 'object_' into object_myobject.png */ public $picto = 'donation'; @@ -65,60 +65,60 @@ class Don extends CommonObject /** * @var string Date of the donation */ - public $date; + public $date; - /** - * amount of donation - * @var double - */ - public $amount; + /** + * amount of donation + * @var double + */ + public $amount; - /** + /** * @var string Thirdparty name */ - public $societe; + public $societe; - /** + /** * @var string Address */ public $address; - /** + /** * @var string Zipcode */ - public $zip; + public $zip; - /** + /** * @var string Town */ - public $town; + public $town; - /** + /** * @var string Email */ - public $email; - public $public; + public $email; + public $public; - /** - * @var int project ID - */ - public $fk_project; + /** + * @var int project ID + */ + public $fk_project; - /** - * @var int type payment ID - */ - public $fk_typepayment; + /** + * @var int type payment ID + */ + public $fk_typepayment; public $num_payment; public $date_valid; public $modepaymentid = 0; - /** + /** * @var array Array of status label */ public $labelStatus; - /** + /** * @var array Array of status label short */ public $labelStatusShort; @@ -130,424 +130,424 @@ class Don extends CommonObject const STATUS_CANCELED = -1; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Returns the donation status label (draft, valid, abandoned, paid) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->statut, $mode); - } + /** + * Returns the donation status label (draft, valid, abandoned, paid) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return the label of a given status - * - * @param int $status Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { - global $langs; - $langs->load("donations"); - $this->labelStatus[-1] = $langs->trans("Canceled"); - $this->labelStatus[0] = $langs->trans("DonationStatusPromiseNotValidated"); - $this->labelStatus[1] = $langs->trans("DonationStatusPromiseValidated"); - $this->labelStatus[2] = $langs->trans("DonationStatusPaid"); - $this->labelStatusShort[-1] = $langs->trans("Canceled"); - $this->labelStatusShort[0] = $langs->trans("DonationStatusPromiseNotValidatedShort"); - $this->labelStatusShort[1] = $langs->trans("DonationStatusPromiseValidatedShort"); - $this->labelStatusShort[2] = $langs->trans("DonationStatusPaidShort"); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the label of a given status + * + * @param int $status Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + $langs->load("donations"); + $this->labelStatus[-1] = $langs->trans("Canceled"); + $this->labelStatus[0] = $langs->trans("DonationStatusPromiseNotValidated"); + $this->labelStatus[1] = $langs->trans("DonationStatusPromiseValidated"); + $this->labelStatus[2] = $langs->trans("DonationStatusPaid"); + $this->labelStatusShort[-1] = $langs->trans("Canceled"); + $this->labelStatusShort[0] = $langs->trans("DonationStatusPromiseNotValidatedShort"); + $this->labelStatusShort[1] = $langs->trans("DonationStatusPromiseValidatedShort"); + $this->labelStatusShort[2] = $langs->trans("DonationStatusPaidShort"); + } - $statusType = 'status'.$status; - if ($status == self::STATUS_CANCELED) $statusType = 'status9'; - if ($status == self::STATUS_PAID) $statusType = 'status6'; + $statusType = 'status'.$status; + if ($status == self::STATUS_CANCELED) $statusType = 'status9'; + if ($status == self::STATUS_PAID) $statusType = 'status6'; - return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); - } + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } - /** - * 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() - { - global $conf, $user, $langs; + /** + * 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() + { + global $conf, $user, $langs; - $now = dol_now(); + $now = dol_now(); - // Charge tableau des id de societe socids - $socids = array(); + // Charge tableau des id de societe socids + $socids = array(); - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe"; - $sql .= " WHERE client IN (1, 3)"; - $sql .= " AND entity = ".$conf->entity; - $sql .= " LIMIT 10"; + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe"; + $sql .= " WHERE client IN (1, 3)"; + $sql .= " AND entity = ".$conf->entity; + $sql .= " LIMIT 10"; - $resql = $this->db->query($sql); - if ($resql) - { - $num_socs = $this->db->num_rows($resql); - $i = 0; - while ($i < $num_socs) - { - $i++; + $resql = $this->db->query($sql); + if ($resql) + { + $num_socs = $this->db->num_rows($resql); + $i = 0; + while ($i < $num_socs) + { + $i++; - $row = $this->db->fetch_row($resql); - $socids[$i] = $row[0]; - } - } + $row = $this->db->fetch_row($resql); + $socids[$i] = $row[0]; + } + } - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->lastname = 'Doe'; - $this->firstname = 'John'; - $this->socid = 1; - $this->date = $now; - $this->date_valid = $now; - $this->amount = 100; - $this->public = 1; - $this->societe = 'The Company'; - $this->address = 'Twist road'; - $this->zip = '99999'; - $this->town = 'Town'; - $this->note_private = 'Private note'; - $this->note_public = 'Public note'; - $this->email = 'email@email.com'; - $this->note = ''; - $this->statut = 1; - } + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->lastname = 'Doe'; + $this->firstname = 'John'; + $this->socid = 1; + $this->date = $now; + $this->date_valid = $now; + $this->amount = 100; + $this->public = 1; + $this->societe = 'The Company'; + $this->address = 'Twist road'; + $this->zip = '99999'; + $this->town = 'Town'; + $this->note_private = 'Private note'; + $this->note_public = 'Public note'; + $this->email = 'email@email.com'; + $this->note = ''; + $this->statut = 1; + } - /** - * Check params and init ->errors array. - * TODO This function seems to not be used by core code. - * - * @param int $minimum Minimum - * @return int 0 if KO, >0 if OK - */ - public function check($minimum = 0) - { - global $langs; - $langs->load('main'); - $langs->load('companies'); + /** + * Check params and init ->errors array. + * TODO This function seems to not be used by core code. + * + * @param int $minimum Minimum + * @return int 0 if KO, >0 if OK + */ + public function check($minimum = 0) + { + global $langs; + $langs->load('main'); + $langs->load('companies'); - $error_string = array(); - $err = 0; + $error_string = array(); + $err = 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->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) - { - $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Address')); - $err++; - } + if (dol_strlen(trim($this->address)) == 0) + { + $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Address')); + $err++; + } - if (dol_strlen(trim($this->zip)) == 0) - { - $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Zip')); - $err++; - } + if (dol_strlen(trim($this->zip)) == 0) + { + $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Zip')); + $err++; + } - if (dol_strlen(trim($this->town)) == 0) - { - $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Town')); - $err++; - } + if (dol_strlen(trim($this->town)) == 0) + { + $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Town')); + $err++; + } - if (dol_strlen(trim($this->email)) == 0) - { - $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMail')); - $err++; - } + if (dol_strlen(trim($this->email)) == 0) + { + $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMail')); + $err++; + } - $this->amount = trim($this->amount); + $this->amount = trim($this->amount); - $map = range(0, 9); - $len = dol_strlen($this->amount); - 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; - break; - } - } + $map = range(0, 9); + $len = dol_strlen($this->amount); + 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; + break; + } + } - if (!$amount_invalid) - { - if ($this->amount == 0) - { - $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount')); - $err++; - } else { - if ($this->amount < $minimum && $minimum > 0) - { - $error_string[] = $langs->trans('MinimumAmount', $langs->transnoentitiesnoconv('$minimum')); - $err++; - } - } - } + if (!$amount_invalid) + { + if ($this->amount == 0) + { + $error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount')); + $err++; + } else { + if ($this->amount < $minimum && $minimum > 0) + { + $error_string[] = $langs->trans('MinimumAmount', $langs->transnoentitiesnoconv('$minimum')); + $err++; + } + } + } - if ($err) - { - $this->errors = $error_string; - return 0; - } else { - return 1; - } - } + if ($err) + { + $this->errors = $error_string; + return 0; + } else { + return 1; + } + } - /** - * Create donation record into database - * - * @param User $user User who created the donation - * @param int $notrigger Disable triggers - * @return int <0 if KO, id of created donation if OK - * TODO add numbering module for Ref - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Create donation record into database + * + * @param User $user User who created the donation + * @param int $notrigger Disable triggers + * @return int <0 if KO, id of created donation if OK + * TODO add numbering module for Ref + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; $ret = 0; - $now = dol_now(); + $now = dol_now(); - // Clean parameters - $this->address = ($this->address > 0 ? $this->address : $this->address); - $this->zip = ($this->zip > 0 ? $this->zip : $this->zip); - $this->town = ($this->town > 0 ? $this->town : $this->town); - $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); - $this->country = ($this->country ? $this->country : $this->country); + // Clean parameters + $this->address = ($this->address > 0 ? $this->address : $this->address); + $this->zip = ($this->zip > 0 ? $this->zip : $this->zip); + $this->town = ($this->town > 0 ? $this->town : $this->town); + $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); + $this->country = ($this->country ? $this->country : $this->country); - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."don ("; - $sql .= "datec"; - $sql .= ", entity"; - $sql .= ", amount"; - $sql .= ", fk_payment"; - $sql .= ", fk_soc"; - $sql .= ", firstname"; - $sql .= ", lastname"; - $sql .= ", societe"; - $sql .= ", address"; - $sql .= ", zip"; - $sql .= ", town"; - $sql .= ", fk_country"; - $sql .= ", public"; - $sql .= ", fk_projet"; - $sql .= ", note_private"; - $sql .= ", note_public"; - $sql .= ", fk_user_author"; - $sql .= ", fk_user_valid"; - $sql .= ", datedon"; - $sql .= ", email"; - $sql .= ", phone"; - $sql .= ", phone_mobile"; - $sql .= ") VALUES ("; - $sql .= "'".$this->db->idate($now)."'"; - $sql .= ", ".$conf->entity; - $sql .= ", ".price2num($this->amount); - $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); - $sql .= ", ".($this->socid > 0 ? $this->socid : "null"); - $sql .= ", '".$this->db->escape($this->firstname)."'"; - $sql .= ", '".$this->db->escape($this->lastname)."'"; - $sql .= ", '".$this->db->escape($this->societe)."'"; - $sql .= ", '".$this->db->escape($this->address)."'"; - $sql .= ", '".$this->db->escape($this->zip)."'"; - $sql .= ", '".$this->db->escape($this->town)."'"; - $sql .= ", ".($this->country_id > 0 ? $this->country_id : '0'); - $sql .= ", ".((int) $this->public); - $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); - $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL"); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."don ("; + $sql .= "datec"; + $sql .= ", entity"; + $sql .= ", amount"; + $sql .= ", fk_payment"; + $sql .= ", fk_soc"; + $sql .= ", firstname"; + $sql .= ", lastname"; + $sql .= ", societe"; + $sql .= ", address"; + $sql .= ", zip"; + $sql .= ", town"; + $sql .= ", fk_country"; + $sql .= ", public"; + $sql .= ", fk_projet"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", fk_user_author"; + $sql .= ", fk_user_valid"; + $sql .= ", datedon"; + $sql .= ", email"; + $sql .= ", phone"; + $sql .= ", phone_mobile"; + $sql .= ") VALUES ("; + $sql .= "'".$this->db->idate($now)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", ".price2num($this->amount); + $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); + $sql .= ", ".($this->socid > 0 ? $this->socid : "null"); + $sql .= ", '".$this->db->escape($this->firstname)."'"; + $sql .= ", '".$this->db->escape($this->lastname)."'"; + $sql .= ", '".$this->db->escape($this->societe)."'"; + $sql .= ", '".$this->db->escape($this->address)."'"; + $sql .= ", '".$this->db->escape($this->zip)."'"; + $sql .= ", '".$this->db->escape($this->town)."'"; + $sql .= ", ".($this->country_id > 0 ? $this->country_id : '0'); + $sql .= ", ".((int) $this->public); + $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "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"; - $sql .= ", '".$this->db->idate($this->date)."'"; - $sql .= ", '".$this->db->escape($this->email)."'"; - $sql .= ", '".$this->db->escape($this->phone)."'"; - $sql .= ", '".$this->db->escape($this->phone_mobile)."'"; - $sql .= ")"; + $sql .= ", ".$user->id; + $sql .= ", null"; + $sql .= ", '".$this->db->idate($this->date)."'"; + $sql .= ", '".$this->db->escape($this->email)."'"; + $sql .= ", '".$this->db->escape($this->phone)."'"; + $sql .= ", '".$this->db->escape($this->phone_mobile)."'"; + $sql .= ")"; - $resql = $this->db->query($sql); - if ($resql) - { + $resql = $this->db->query($sql); + if ($resql) + { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."don"); $ret = $this->id; - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('DON_CREATE', $user); - if ($result < 0) { $error++; } - // End call triggers - } - } else { - $this->error = $this->db->lasterror(); - $this->errno = $this->db->lasterrno(); - $error++; - } + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('DON_CREATE', $user); + if ($result < 0) { $error++; } + // End call triggers + } + } else { + $this->error = $this->db->lasterror(); + $this->errno = $this->db->lasterrno(); + $error++; + } // Update extrafield - if (!$error) { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } + if (!$error) { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) - { - //$res = $this->setValid($user); - //if ($res < 0) $error++; - } + { + //$res = $this->setValid($user); + //if ($res < 0) $error++; + } - if (!$error) - { - $this->db->commit(); - return $ret; - } else { - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return $ret; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Update a donation record - * - * @param User $user Objet utilisateur qui met a jour le don - * @param int $notrigger Disable triggers - * @return int >0 if OK, <0 if KO - */ - public function update($user, $notrigger = 0) - { - global $langs, $conf; + /** + * Update a donation record + * + * @param User $user Objet utilisateur qui met a jour le don + * @param int $notrigger Disable triggers + * @return int >0 if OK, <0 if KO + */ + public function update($user, $notrigger = 0) + { + global $langs, $conf; $error = 0; - // Clean parameters - $this->address = ($this->address > 0 ? $this->address : $this->address); - $this->zip = ($this->zip > 0 ? $this->zip : $this->zip); - $this->town = ($this->town > 0 ? $this->town : $this->town); - $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); - $this->country = ($this->country ? $this->country : $this->country); + // Clean parameters + $this->address = ($this->address > 0 ? $this->address : $this->address); + $this->zip = ($this->zip > 0 ? $this->zip : $this->zip); + $this->town = ($this->town > 0 ? $this->town : $this->town); + $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); + $this->country = ($this->country ? $this->country : $this->country); - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."don SET "; - $sql .= "amount = ".price2num($this->amount); - $sql .= ",fk_payment = ".($this->modepaymentid ? $this->modepaymentid : "null"); - $sql .= ",firstname = '".$this->db->escape($this->firstname)."'"; - $sql .= ",lastname='".$this->db->escape($this->lastname)."'"; - $sql .= ",societe='".$this->db->escape($this->societe)."'"; - $sql .= ",address='".$this->db->escape($this->address)."'"; - $sql .= ",zip='".$this->db->escape($this->zip)."'"; - $sql .= ",town='".$this->db->escape($this->town)."'"; - $sql .= ",fk_country = ".($this->country_id > 0 ? $this->country_id : '0'); - $sql .= ",public=".$this->public; - $sql .= ",fk_projet=".($this->fk_project > 0 ? $this->fk_project : 'null'); - $sql .= ",note_private=".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL"); - $sql .= ",note_public=".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL"); - $sql .= ",datedon='".$this->db->idate($this->date)."'"; - $sql .= ",date_valid=".($this->date_valid ? "'".$this->db->idate($this->date)."'" : "null"); - $sql .= ",email='".$this->db->escape($this->email)."'"; - $sql .= ",phone='".$this->db->escape($this->phone)."'"; - $sql .= ",phone_mobile='".$this->db->escape($this->phone_mobile)."'"; - $sql .= ",fk_statut=".$this->statut; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."don SET "; + $sql .= "amount = ".price2num($this->amount); + $sql .= ",fk_payment = ".($this->modepaymentid ? $this->modepaymentid : "null"); + $sql .= ",firstname = '".$this->db->escape($this->firstname)."'"; + $sql .= ",lastname='".$this->db->escape($this->lastname)."'"; + $sql .= ",societe='".$this->db->escape($this->societe)."'"; + $sql .= ",address='".$this->db->escape($this->address)."'"; + $sql .= ",zip='".$this->db->escape($this->zip)."'"; + $sql .= ",town='".$this->db->escape($this->town)."'"; + $sql .= ",fk_country = ".($this->country_id > 0 ? $this->country_id : '0'); + $sql .= ",public=".$this->public; + $sql .= ",fk_projet=".($this->fk_project > 0 ? $this->fk_project : 'null'); + $sql .= ",note_private=".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL"); + $sql .= ",note_public=".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL"); + $sql .= ",datedon='".$this->db->idate($this->date)."'"; + $sql .= ",date_valid=".($this->date_valid ? "'".$this->db->idate($this->date)."'" : "null"); + $sql .= ",email='".$this->db->escape($this->email)."'"; + $sql .= ",phone='".$this->db->escape($this->phone)."'"; + $sql .= ",phone_mobile='".$this->db->escape($this->phone_mobile)."'"; + $sql .= ",fk_statut=".$this->statut; + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::Update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('DON_MODIFY', $user); - if ($result < 0) { $error++; } - // End call triggers - } - - // Update extrafield - if (!$error) + dol_syslog(get_class($this)."::Update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$notrigger) { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } + // Call trigger + $result = $this->call_trigger('DON_MODIFY', $user); + if ($result < 0) { $error++; } + // End call triggers + } + + // Update extrafield + if (!$error) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } if (!$error) - { - $this->db->commit(); - $result = 1; - } else { - $this->db->rollback(); - $result = -1; - } - } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - $this->db->rollback(); - dol_syslog(get_class($this)."::Update error -2 ".$this->error, LOG_ERR); - $result = -2; - } + { + $this->db->commit(); + $result = 1; + } else { + $this->db->rollback(); + $result = -1; + } + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $this->db->rollback(); + dol_syslog(get_class($this)."::Update error -2 ".$this->error, LOG_ERR); + $result = -2; + } return $result; } - /** - * Delete a donation from database - * - * @param User $user User - * @param int $notrigger Disable triggers - * @return int <0 if KO, 0 if not possible, >0 if OK - */ - public function delete($user, $notrigger = 0) - { + /** + * Delete a donation from database + * + * @param User $user User + * @param int $notrigger Disable triggers + * @return int <0 if KO, 0 if not possible, >0 if OK + */ + public function delete($user, $notrigger = 0) + { global $user, $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -556,156 +556,157 @@ class Don extends CommonObject $this->db->begin(); if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('DON_DELETE', $user); + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('DON_DELETE', $user); - if ($result < 0) { - $error++; - } - // End call triggers - } - } + if ($result < 0) { + $error++; + } + // End call triggers + } + } - // Delete donation - if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."don_extrafields"; - $sql .= " WHERE fk_object=".$this->id; + // Delete donation + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."don_extrafields"; + $sql .= " WHERE fk_object=".$this->id; - $resql = $this->db->query($sql); - if (!$resql) - { - $this->errors[] = $this->db->lasterror(); - $error++; - } - } + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->lasterror(); + $error++; + } + } if (!$error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."don"; - $sql .= " WHERE rowid=".$this->id; + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."don"; + $sql .= " WHERE rowid=".$this->id; - $resql = $this->db->query($sql); - if (!$resql) - { - $this->errors[] = $this->db->lasterror(); - $error++; - } - } + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->lasterror(); + $error++; + } + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - foreach ($this->errors as $errmsg) - { + if (!$error) + { + $this->db->commit(); + return 1; + } else { + foreach ($this->errors as $errmsg) + { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } - } + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + } - /** - * Load donation from database - * - * @param int $id Id of donation to load - * @param string $ref Ref of donation to load - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $conf; + /** + * Load donation from database + * + * @param int $id Id of donation to load + * @param string $ref Ref of donation to load + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $conf; - $sql = "SELECT d.rowid, d.datec, d.date_valid, d.tms as datem, d.datedon,"; - $sql .= " d.fk_soc as socid,d.firstname, d.lastname, d.societe, d.amount, d.fk_statut, d.address, d.zip, d.town, "; - $sql .= " d.fk_country, d.country as country_olddata, d.public, d.amount, d.fk_payment, d.paid, d.note_private, d.note_public, d.email, d.phone, "; - $sql .= " d.phone_mobile, d.fk_projet as fk_project, d.model_pdf,"; - $sql .= " p.ref as project_ref,"; - $sql .= " cp.libelle as payment_label, cp.code as payment_code,"; - $sql .= " c.code as country_code, c.label as country"; - $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_projet"; - $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)) - { - $sql .= " AND d.rowid=".$id; - } elseif (!empty($ref)) - { - $sql .= " AND d.ref='".$this->db->escape($ref)."'"; - } + $sql = "SELECT d.rowid, d.datec, d.date_valid, d.tms as datem, d.datedon,"; + $sql .= " d.fk_soc as socid,d.firstname, d.lastname, d.societe, d.amount, d.fk_statut, d.address, d.zip, d.town, "; + $sql .= " d.fk_country, d.country as country_olddata, d.public, d.amount, d.fk_payment, d.paid, d.note_private, d.note_public, d.email, d.phone, "; + $sql .= " d.phone_mobile, d.fk_projet as fk_project, d.model_pdf,"; + $sql .= " p.ref as project_ref,"; + $sql .= " cp.libelle as payment_label, cp.code as payment_code,"; + $sql .= " c.code as country_code, c.label as country"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_projet"; + $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)) + { + $sql .= " AND d.rowid=".$id; + } 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)) - { - $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->date_creation = $this->db->jdate($obj->datec); - $this->datec = $this->db->jdate($obj->datec); - $this->date_validation = $this->db->jdate($obj->date_valid); - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->date_modification = $this->db->jdate($obj->datem); - $this->datem = $this->db->jdate($obj->datem); - $this->date = $this->db->jdate($obj->datedon); - $this->socid = $obj->socid; - $this->firstname = $obj->firstname; - $this->lastname = $obj->lastname; - $this->societe = $obj->societe; - $this->statut = $obj->fk_statut; - $this->address = $obj->address; - $this->zip = $obj->zip; - $this->town = $obj->town; - $this->country_id = $obj->fk_country; - $this->country_code = $obj->country_code; - $this->country = $obj->country; - $this->country_olddata = $obj->country_olddata; // deprecated - $this->email = $obj->email; - $this->phone = $obj->phone; - $this->phone_mobile = $obj->phone_mobile; - $this->project = $obj->project_ref; - $this->fk_projet = $obj->fk_project; // deprecated - $this->fk_project = $obj->fk_project; - $this->public = $obj->public; - $this->mode_reglement_id = $obj->fk_payment; - $this->mode_reglement_code = $obj->payment_code; - $this->mode_reglement = $obj->payment_label; - $this->paid = $obj->paid; - $this->amount = $obj->amount; - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->modelpdf = $obj->model_pdf; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->date_creation = $this->db->jdate($obj->datec); + $this->datec = $this->db->jdate($obj->datec); + $this->date_validation = $this->db->jdate($obj->date_valid); + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_modification = $this->db->jdate($obj->datem); + $this->datem = $this->db->jdate($obj->datem); + $this->date = $this->db->jdate($obj->datedon); + $this->socid = $obj->socid; + $this->firstname = $obj->firstname; + $this->lastname = $obj->lastname; + $this->societe = $obj->societe; + $this->statut = $obj->fk_statut; + $this->address = $obj->address; + $this->zip = $obj->zip; + $this->town = $obj->town; + $this->country_id = $obj->fk_country; + $this->country_code = $obj->country_code; + $this->country = $obj->country; + $this->country_olddata = $obj->country_olddata; // deprecated + $this->email = $obj->email; + $this->phone = $obj->phone; + $this->phone_mobile = $obj->phone_mobile; + $this->project = $obj->project_ref; + $this->fk_projet = $obj->fk_project; // deprecated + $this->fk_project = $obj->fk_project; + $this->public = $obj->public; + $this->mode_reglement_id = $obj->fk_payment; + $this->mode_reglement_code = $obj->payment_code; + $this->mode_reglement = $obj->payment_label; + $this->paid = $obj->paid; + $this->amount = $obj->amount; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - } - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + } + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } /** * Validate a intervention - * - * @param User $user User that validate - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ + * + * @param User $user User that validate + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ public function setValid($user, $notrigger = 0) { return $this->valid_promesse($this->id, $user->id, $notrigger); @@ -713,14 +714,14 @@ class Don extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Validate a promise of donation - * - * @param int $id id of donation - * @param int $userid User who validate the donation/promise - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function valid_promesse($id, $userid, $notrigger = 0) + * Validate a promise of donation + * + * @param int $id id of donation + * @param int $userid User who validate the donation/promise + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function valid_promesse($id, $userid, $notrigger = 0) { // phpcs:enable global $langs, $user; @@ -729,197 +730,197 @@ class Don extends CommonObject $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 1, fk_user_valid = ".$userid." WHERE rowid = ".$id." AND fk_statut = 0"; + $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 (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('DON_VALIDATE', $user); - if ($result < 0) { $error++; } - // End call triggers - } - } - } else { - $error++; - $this->error = $this->db->lasterror(); - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('DON_VALIDATE', $user); + if ($result < 0) { $error++; } + // End call triggers + } + } + } else { + $error++; + $this->error = $this->db->lasterror(); + } - 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; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Classify the donation as paid, the donation was received - * - * @param int $id id of donation - * @param int $modepayment mode of payment - * @return int <0 if KO, >0 if OK - */ - public function set_paid($id, $modepayment = 0) - { - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 2"; - if ($modepayment) - { - $sql .= ", fk_payment=".$modepayment; - } - $sql .= " WHERE rowid = ".$id." AND fk_statut = 1"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Classify the donation as paid, the donation was received + * + * @param int $id id of donation + * @param int $modepayment mode of payment + * @return int <0 if KO, >0 if OK + */ + public function set_paid($id, $modepayment = 0) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 2"; + if ($modepayment) + { + $sql .= ", fk_payment=".$modepayment; + } + $sql .= " WHERE rowid = ".$id." AND fk_statut = 1"; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { - return 1; - } else { - return 0; - } - } else { - dol_print_error($this->db); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { + return 1; + } else { + return 0; + } + } else { + dol_print_error($this->db); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set donation to status cancelled - * - * @param int $id id of donation - * @return int <0 if KO, >0 if OK - */ - public function set_cancel($id) - { - // phpcs:enable - $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = -1 WHERE rowid = ".$id; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set donation to status cancelled + * + * @param int $id id of donation + * @return int <0 if KO, >0 if OK + */ + public function set_cancel($id) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = -1 WHERE rowid = ".$id; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { - return 1; - } else { - return 0; - } - } else { - dol_print_error($this->db); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->affected_rows($resql)) + { + return 1; + } else { + return 0; + } + } else { + dol_print_error($this->db); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Sum of donations - * - * @param string $param 1=promesses de dons validees , 2=xxx, 3=encaisses - * @return int Summ of donations - */ - public function sum_donations($param) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Sum of donations + * + * @param string $param 1=promesses de dons validees , 2=xxx, 3=encaisses + * @return int Summ of donations + */ + public function sum_donations($param) + { + // phpcs:enable + global $conf; - $result = 0; + $result = 0; - $sql = "SELECT sum(amount) as total"; - $sql .= " FROM ".MAIN_DB_PREFIX."don"; - $sql .= " WHERE fk_statut = ".$param; - $sql .= " AND entity = ".$conf->entity; + $sql = "SELECT sum(amount) as total"; + $sql .= " FROM ".MAIN_DB_PREFIX."don"; + $sql .= " WHERE fk_statut = ".$param; + $sql .= " AND entity = ".$conf->entity; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $result = $obj->total; - } + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $result = $obj->total; + } - return $result; - } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Charge indicateurs this->nb pour le tableau de bord - * - * @return int <0 if KO, >0 if OK - */ - public function load_state_board() - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge indicateurs this->nb pour le tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + public function load_state_board() + { + // phpcs:enable + global $conf; - $this->nb = array(); + $this->nb = array(); - $sql = "SELECT count(d.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; - $sql .= " WHERE d.fk_statut > 0"; - $sql .= " AND d.entity IN (".getEntity('donation').")"; + $sql = "SELECT count(d.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; + $sql .= " WHERE d.fk_statut > 0"; + $sql .= " AND d.entity IN (".getEntity('donation').")"; - $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $this->nb["donations"] = $obj->nb; - } - $this->db->free($resql); - return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + $this->nb["donations"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $notooltip 1=Disable tooltip - * @param string $moretitle Add more text to title tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string Chaine avec URL - */ - public function getNomUrl($withpicto = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1) - { - global $conf, $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $notooltip 1=Disable tooltip + * @param string $moretitle Add more text to title tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + public function getNomUrl($withpicto = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1) + { + 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 = ''.$langs->trans("Donation").''; - if (!empty($this->id)) { - $label .= '
    '.$langs->trans('Ref').': '.$this->id; - } - if ($moretitle) $label .= ' - '.$moretitle; + $result = ''; + $label = img_picto('', $this->picto).' '.$langs->trans("Donation").''; + if (!empty($this->id)) { + $label .= '
    '.$langs->trans('Ref').': '.$this->id; + } + if ($moretitle) $label .= ' - '.$moretitle; - $url = DOL_URL_ROOT.'/don/card.php?id='.$this->id; + $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 = ''; + $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; - $result .= $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; + $result .= $linkend; - return $result; - } + return $result; + } /** * Information on record @@ -984,8 +985,8 @@ class Don extends CommonObject if (!dol_strlen($modele)) { $modele = 'html_cerfafr'; - if ($this->modelpdf) { - $modele = $this->modelpdf; + if ($this->model_pdf) { + $modele = $this->model_pdf; } elseif (!empty($conf->global->DON_ADDON_MODEL)) { $modele = $conf->global->DON_ADDON_MODEL; } diff --git a/htdocs/don/document.php b/htdocs/don/document.php index 0d56ff5bd63..9265692241d 100644 --- a/htdocs/don/document.php +++ b/htdocs/don/document.php @@ -45,7 +45,7 @@ $langs->loadLangs(array("companies", "other", "donations")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); @@ -56,8 +56,8 @@ $result = restrictedArea($user, 'don', $id, ''); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/don/info.php b/htdocs/don/info.php index 170c577dc00..8a12e319ef8 100644 --- a/htdocs/don/info.php +++ b/htdocs/don/info.php @@ -35,7 +35,7 @@ $langs->load("donations"); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check diff --git a/htdocs/don/list.php b/htdocs/don/list.php index cc12daabb6c..c98f2f8a000 100644 --- a/htdocs/don/list.php +++ b/htdocs/don/list.php @@ -96,7 +96,7 @@ $sql .= " FROM ".MAIN_DB_PREFIX."don as d LEFT JOIN ".MAIN_DB_PREFIX."projet AS $sql .= " ON p.rowid = d.fk_projet WHERE d.entity IN (".getEntity('donation').")"; if ($search_status != '' && $search_status != '-4') { - $sql .= " AND d.fk_statut IN (".$db->escape($search_status).")"; + $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; } if (trim($search_ref) != '') { diff --git a/htdocs/don/note.php b/htdocs/don/note.php index 111ea2399a3..6df77ad2bc1 100644 --- a/htdocs/don/note.php +++ b/htdocs/don/note.php @@ -40,7 +40,7 @@ $langs->loadLangs(array("companies", "bills", "donations")); $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); // Security check diff --git a/htdocs/don/payment/card.php b/htdocs/don/payment/card.php index 6d1285b5f17..26f540969ee 100644 --- a/htdocs/don/payment/card.php +++ b/htdocs/don/payment/card.php @@ -33,9 +33,9 @@ if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank $langs->loadLangs(array("bills", "banks", "companies")); // Security check -$id = GETPOST('rowid') ?GETPOST('rowid', 'int') : GETPOST('id', 'int'); +$id = GETPOST('rowid') ? GETPOST('rowid', 'int') : GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); -$confirm = GETPOST('confirm'); +$confirm = GETPOST('confirm', 'alpha'); if ($user->socid) $socid = $user->socid; // TODO Add rule to restrict access payment //$result = restrictedArea($user, 'facture', $id,''); @@ -80,20 +80,20 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->don->cree { $db->commit(); - $factures = array(); // TODO Get all id of invoices linked to this payment - foreach ($factures as $id) + $donations = array(); // TODO Get all id of donation linked to this payment + foreach ($donations as $id) { - $fac = new Facture($db); - $fac->fetch($id); + $donation = new Don($db); + $donation->fetch($id); $outputlangs = $langs; - if (!empty($_REQUEST['lang_id'])) + if (!empty(GETPOST('lang_id'))) { $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); + $outputlangs->setDefaultLang(GETPOST('lang_id')); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $fac->generateDocument($fac->modelpdf, $outputlangs); + $donation->generateDocument($donation->model_pdf, $outputlangs); } } @@ -137,8 +137,7 @@ if ($action == 'delete') */ if ($action == 'valide') { - $facid = GETPOST('facid', 'int'); - print $form->formconfirm('card.php?id='.$object->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide', '', 0, 2); + print $form->formconfirm('card.php?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide', '', 0, 2); } @@ -263,26 +262,13 @@ dol_fiche_end(); */ print '
    '; -/* -if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) -{ - if ($user->socid == 0 && $object->statut == 0 && $_GET['action'] == '') - { - if ($user->rights->facture->paiement) - { - print ''.$langs->trans('Valid').''; - } - } -} -*/ - if (empty($action)) { if ($user->rights->don->supprimer) { if (!$disable_delete) { - print ''.$langs->trans('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 50c469a5f1a..3983765d904 100644 --- a/htdocs/don/payment/payment.php +++ b/htdocs/don/payment/payment.php @@ -107,7 +107,7 @@ if ($action == 'add_payment') $payment->amounts = $amounts; // Tableau de montant $payment->paymenttype = GETPOST("paymenttype", 'int'); $payment->num_payment = GETPOST("num_payment", 'alphanohtml'); - $payment->note_public = GETPOST("note_public", 'none'); + $payment->note_public = GETPOST("note_public", 'restricthtml'); if (!$error) { diff --git a/htdocs/ecm/ajax/ecmdatabase.php b/htdocs/ecm/ajax/ecmdatabase.php index 5ba61c53a8d..e817f6af4a4 100644 --- a/htdocs/ecm/ajax/ecmdatabase.php +++ b/htdocs/ecm/ajax/ecmdatabase.php @@ -28,7 +28,7 @@ if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $element = GETPOST('element', 'alpha'); /* diff --git a/htdocs/ecm/class/ecmdirectory.class.php b/htdocs/ecm/class/ecmdirectory.class.php index 9c09ee0f534..dc39550c0cf 100644 --- a/htdocs/ecm/class/ecmdirectory.class.php +++ b/htdocs/ecm/class/ecmdirectory.class.php @@ -25,7 +25,7 @@ /** * Class to manage ECM directories */ -class EcmDirectory // extends CommonObject +class EcmDirectory extends CommonObject { /** * @var string ID to identify managed object @@ -35,7 +35,7 @@ class EcmDirectory // extends CommonObject /** * @var string Name of table without prefix where object is stored */ - //public $table_element='ecm_directories'; + public $table_element = 'ecm_directories'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png @@ -321,7 +321,7 @@ class EcmDirectory // extends CommonObject $sql .= " t.fk_user_c,"; $sql .= " t.fk_user_m,"; $sql .= " t.date_c as date_c,"; - $sql .= " t.date_m as date_m"; + $sql .= " t.tms as date_m"; $sql .= " FROM ".MAIN_DB_PREFIX."ecm_directories as t"; $sql .= " WHERE t.rowid = ".$id; @@ -345,6 +345,10 @@ class EcmDirectory // extends CommonObject $this->date_m = $this->db->jdate($obj->date_m); } + // Retrieve all extrafields for ecm_files + // fetch optionals attributes and labels + $this->fetch_optionals(); + $this->db->free($resql); return $obj ? 1 : 0; diff --git a/htdocs/ecm/class/ecmfiles.class.php b/htdocs/ecm/class/ecmfiles.class.php index 17717ca4f2a..b0c1df8316f 100644 --- a/htdocs/ecm/class/ecmfiles.class.php +++ b/htdocs/ecm/class/ecmfiles.class.php @@ -235,14 +235,14 @@ class EcmFiles extends CommonObject $sql .= 'gen_or_uploaded,'; $sql .= 'extraparams,'; $sql .= 'date_c,'; - $sql .= 'date_m,'; + $sql .= 'tms,'; $sql .= 'fk_user_c,'; $sql .= 'fk_user_m,'; $sql .= 'acl,'; $sql .= 'src_object_type,'; $sql .= 'src_object_id'; $sql .= ') VALUES ('; - $sql .= " '".$ref."', "; + $sql .= " '".$this->db->escape($ref)."', "; $sql .= ' '.(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").','; $sql .= ' '.(!isset($this->share) ? 'NULL' : "'".$this->db->escape($this->share)."'").','; $sql .= ' '.$this->entity.','; @@ -333,7 +333,7 @@ class EcmFiles extends CommonObject $sql .= " t.gen_or_uploaded,"; $sql .= " t.extraparams,"; $sql .= " t.date_c,"; - $sql .= " t.date_m,"; + $sql .= " t.tms as date_m,"; $sql .= " t.fk_user_c,"; $sql .= " t.fk_user_m,"; $sql .= " t.acl,"; @@ -403,9 +403,9 @@ class EcmFiles extends CommonObject $this->src_object_id = $obj->src_object_id; } - // Retrieve all extrafields for invoice + // Retrieve all extrafields for ecm_files // fetch optionals attributes and labels - // $this->fetch_optionals(); + $this->fetch_optionals(); // $this->fetch_lines(); @@ -455,7 +455,7 @@ class EcmFiles extends CommonObject $sql .= " t.gen_or_uploaded,"; $sql .= " t.extraparams,"; $sql .= " t.date_c,"; - $sql .= " t.date_m,"; + $sql .= " t.tms as date_m,"; $sql .= " t.fk_user_c,"; $sql .= " t.fk_user_m,"; $sql .= " t.acl,"; @@ -612,7 +612,7 @@ class EcmFiles extends CommonObject $sql .= ' gen_or_uploaded = '.(isset($this->gen_or_uploaded) ? "'".$this->db->escape($this->gen_or_uploaded)."'" : "null").','; $sql .= ' extraparams = '.(isset($this->extraparams) ? "'".$this->db->escape($this->extraparams)."'" : "null").','; $sql .= ' date_c = '.(!isset($this->date_c) || dol_strlen($this->date_c) != 0 ? "'".$this->db->idate($this->date_c)."'" : 'null').','; - //$sql .= ' date_m = '.(! isset($this->date_m) || dol_strlen($this->date_m) != 0 ? "'".$this->db->idate($this->date_m)."'" : 'null').','; // Field automatically updated + //$sql .= ' tms = '.(! isset($this->date_m) || dol_strlen($this->date_m) != 0 ? "'".$this->db->idate($this->date_m)."'" : 'null').','; // Field automatically updated $sql .= ' fk_user_m = '.($this->fk_user_m > 0 ? $this->fk_user_m : $user->id).','; $sql .= ' acl = '.(isset($this->acl) ? "'".$this->db->escape($this->acl)."'" : "null").','; $sql .= ' src_object_id = '.($this->src_object_id > 0 ? $this->src_object_id : "null").','; diff --git a/htdocs/ecm/dir_add_card.php b/htdocs/ecm/dir_add_card.php index e17892097af..a84beb605cb 100644 --- a/htdocs/ecm/dir_add_card.php +++ b/htdocs/ecm/dir_add_card.php @@ -120,9 +120,9 @@ if ($action == 'add' && $permtoadd) } } - $ref = trim(GETPOST("ref", 'alpha')); - $label = trim(GETPOST("label", 'alpha')); - $desc = trim(GETPOST("desc", 'alpha')); + $ref = GETPOST("ref", 'alpha'); + $label = GETPOST("label", 'alpha'); + $desc = GETPOST("desc", 'alpha'); $catParent = GETPOST("catParent", 'alpha'); // Can be an int (with ECM) or a string (with generic filemanager) if ($catParent == '-1') $catParent = 0; @@ -292,7 +292,7 @@ if (empty($action) || $action == 'delete_section') print '
    '; if ($user->rights->ecm->setup) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } diff --git a/htdocs/ecm/dir_card.php b/htdocs/ecm/dir_card.php index 27d08e9119f..62929c5341f 100644 --- a/htdocs/ecm/dir_card.php +++ b/htdocs/ecm/dir_card.php @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by page $langs->loadLangs(array('ecm', 'companies', 'other')); @@ -204,6 +205,16 @@ if ($action == 'update' && !GETPOST('cancel', 'alpha')) // Fetch was already done $ecmdir->label = dol_sanitizeFileName(GETPOST("label")); $ecmdir->description = GETPOST("description"); + $ret = $extrafields->setOptionalsFromPost(null, $ecmdir); + if ($ret < 0) $error++; + if (!$error) { + // Actions on extra fields + $result = $ecmdir->insertExtraFields(); + if ($result < 0) { + setEventMessages($ecmdir->error, $ecmdir->errors, 'errors'); + $error++; + } + } $result = $ecmdir->update($user); if ($result > 0) { @@ -266,6 +277,10 @@ if ($action == 'update' && !GETPOST('cancel', 'alpha')) $form = new Form($db); $object = new EcmDirectory($db); // Need to create a new one instance +$extrafields = new ExtraFields($db); +// fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + if ($module == 'ecm') { @@ -415,6 +430,7 @@ print ''; print ''.$langs->trans("TotalSizeOfAttachedFiles").''; print dol_print_size($totalsize); print ''; +print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view')); print ''; if ($action == 'edit') @@ -457,7 +473,7 @@ if ($action != 'edit' && $action != 'delete') //{ if ($permtoadd) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } diff --git a/htdocs/ecm/file_card.php b/htdocs/ecm/file_card.php index 144f9fe6bae..d5a66ca4134 100644 --- a/htdocs/ecm/file_card.php +++ b/htdocs/ecm/file_card.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2008-2020 Laurent Destailleur * * 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,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by page $langs->loadLangs(array('ecm', 'companies', 'other', 'users', 'orders', 'propal', 'bills', 'contracts', 'categories')); @@ -43,8 +44,8 @@ $socid = GETPOST("socid", "int"); // Security check if ($user->socid > 0) { - $action = ''; - $socid = $user->socid; + $action = ''; + $socid = $user->socid; } $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -61,14 +62,14 @@ if (!$sortfield) $sortfield = "label"; $section = GETPOST("section", 'alpha'); if (!$section) { - dol_print_error('', 'Error, section parameter missing'); - exit; + dol_print_error('', 'Error, section parameter missing'); + exit; } $urlfile = GETPOST("urlfile"); if (!$urlfile) { - dol_print_error('', "ErrorParamNotDefined"); - exit; + dol_print_error('', "ErrorParamNotDefined"); + exit; } // Load ecm object @@ -76,8 +77,8 @@ $ecmdir = new EcmDirectory($db); $result = $ecmdir->fetch(GETPOST("section", 'alpha')); if (!$result > 0) { - dol_print_error($db, $ecmdir->error); - exit; + dol_print_error($db, $ecmdir->error); + exit; } $relativepath = $ecmdir->getRelativePath(); $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; @@ -94,6 +95,10 @@ $filepathtodocument = $relativetodocument.$file->label; // Try to load object from index $object = new ECMFiles($db); +$extrafields = new ExtraFields($db); +// fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + $result = $object->fetch(0, '', $filepathtodocument); if ($result < 0) { @@ -109,68 +114,67 @@ if ($result < 0) if ($cancel) { - $action = ''; - if ($backtopage) - { - header("Location: ".$backtopage); - exit; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); - exit; - } + $action = ''; + if ($backtopage) + { + header("Location: ".$backtopage); + exit; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); + exit; + } } // Rename file if ($action == 'update') { - $error = 0; + $error = 0; - $oldlabel = GETPOST('urlfile', 'alpha'); - $newlabel = GETPOST('label', 'alpha'); + $oldlabel = GETPOST('urlfile', 'alpha'); + $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha')); $shareenabled = GETPOST('shareenabled', 'alpha'); - //$db->begin(); + //$db->begin(); - $olddir = $ecmdir->getRelativePath(0); // Relative to ecm - $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document - $newdirrelativetodocument = 'ecm/'.$olddir; - $olddir = $conf->ecm->dir_output.'/'.$olddir; - $newdir = $olddir; + $olddir = $ecmdir->getRelativePath(0); // Relative to ecm + $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document + $newdirrelativetodocument = 'ecm/'.$olddir; + $olddir = $conf->ecm->dir_output.'/'.$olddir; + $newdir = $olddir; - $oldfile = $olddir.$oldlabel; - $newfile = $newdir.$newlabel; - $newfileformove = $newfile; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { - $newfileformove .= '.noexe'; - } - //var_dump($oldfile);var_dump($newfile);exit; + $oldfile = $olddir.$oldlabel; + $newfile = $newdir.$newlabel; + $newfileformove = $newfile; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { + $newfileformove .= '.noexe'; + } + //var_dump($oldfile);var_dump($newfile);exit; - // Now we update index of file - $db->begin(); + // Now we update index of file + $db->begin(); + //print $oldfile.' - '.$newfile; + if ($newlabel != $oldlabel) + { + $result = dol_move($oldfile, $newfileformove); // This include update of database + if (!$result) + { + $langs->load('errors'); + setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); + $error++; + } - //print $oldfile.' - '.$newfile; - if ($newlabel != $oldlabel) - { - $result = dol_move($oldfile, $newfileformove); // This include update of database - if (!$result) - { - $langs->load('errors'); - setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); - $error++; - } + // Reload object after the move + $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); + if ($result < 0) + { + dol_print_error($db, $object->error, $object->errors); + exit; + } + } - // Reload object after the move - $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); - if ($result < 0) - { - dol_print_error($db, $object->error, $object->errors); - exit; - } - } - - if (!$error) - { + if (!$error) + { if ($shareenabled) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -181,6 +185,16 @@ if ($action == 'update') if ($object->id > 0) { + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) $error++; + if (!$error) { + // Actions on extra fields + $result = $object->insertExtraFields(); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } // Call update to set the share key $result = $object->update($user); if ($result < 0) @@ -203,23 +217,23 @@ if ($action == 'update') setEventMessages($object->error, $object->errors, 'warnings'); } } - } + } - if (!$error) - { - $db->commit(); + if (!$error) + { + $db->commit(); - $urlfile = $newlabel; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $newfileformove)) { - $urlfile .= '.noexe'; - } + $urlfile = $newlabel; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $newfileformove)) { + $urlfile .= '.noexe'; + } - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); - exit; - } else { - $db->rollback(); - } + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); + exit; + } else { + $db->rollback(); + } } @@ -284,7 +298,7 @@ dol_banner_tab($object, '', $linkback, 0, '', '', $s); print '
    '; print '
    '; -print ''; +print '
    '; print ''; @@ -365,8 +379,9 @@ if (!empty($object->share)) print 'share ? ' checked="checked"' : '').' /> '; } } -print ''; - +print ''; +print ''; +print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view')); print '
    '.$langs->trans("ECMCreationDate").''; print dol_print_date(dol_filemtime($fullpath), 'dayhour'); print '
    '; print '
    '; @@ -377,20 +392,20 @@ dol_fiche_end(); if ($action == 'edit') { - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; - print ''; + print ''; } // Confirmation de la suppression d'une ligne categorie if ($action == 'delete_file') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); } if ($action != 'edit') @@ -398,14 +413,14 @@ if ($action != 'edit') // Actions buttons print '
    '; - if ($user->rights->ecm->setup) - { - print ''.$langs->trans('Edit').''; - } - /* if ($user->rights->ecm->setup) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Edit').''; + } + /* + if ($user->rights->ecm->setup) + { + print ''.$langs->trans('Delete').''; } else { diff --git a/htdocs/ecm/index.php b/htdocs/ecm/index.php index 4db7b897b6a..d3ddb99fbdf 100644 --- a/htdocs/ecm/index.php +++ b/htdocs/ecm/index.php @@ -83,7 +83,7 @@ $error = 0; //include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; // Upload file (code similar but different than actions_linkedfiles.inc.php) -if (GETPOST("sendit", 'none') && !empty($conf->global->MAIN_UPLOAD_DOC)) +if (GETPOST("sendit", 'alphanohtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) { // Define relativepath and upload_dir $relativepath = ''; @@ -127,7 +127,6 @@ if ($action == 'confirm_deletefile') $upload_dir = $conf->ecm->dir_output.($relativepath ? '/'.$relativepath : ''); $file = $upload_dir."/".GETPOST('urlfile', 'alpha'); - $ret = dol_delete_file($file); // This include also the delete from file index in database. if ($ret) { diff --git a/htdocs/ecm/index_auto.php b/htdocs/ecm/index_auto.php index c9a8e1dc551..e8bf1465fb5 100644 --- a/htdocs/ecm/index_auto.php +++ b/htdocs/ecm/index_auto.php @@ -315,7 +315,7 @@ if (!empty($conf->global->ECM_AUTO_TREE_ENABLED)) if (!empty($conf->contrat->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'contract', 'test'=>$conf->contrat->enabled, 'label'=>$langs->trans("Contracts"), 'desc'=>$langs->trans("ECMDocsByContracts")); } if (!empty($conf->commande->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'order', 'test'=>$conf->commande->enabled, 'label'=>$langs->trans("CustomersOrders"), 'desc'=>$langs->trans("ECMDocsByOrders")); } if (!empty($conf->facture->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'invoice', 'test'=>$conf->facture->enabled, 'label'=>$langs->trans("CustomersInvoices"), 'desc'=>$langs->trans("ECMDocsByInvoices")); } - if (!empty($conf->supplier_proposal->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'supplier_proposal', 'test'=>$conf->supplier_proposal->enabled, 'label'=>$langs->trans("SupplierProposals"), 'desc'=>$langs->trans("ECMDocsBySupplierProposals")); } + if (!empty($conf->supplier_proposal->enabled)) { $langs->load("supplier_proposal"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'supplier_proposal', 'test'=>$conf->supplier_proposal->enabled, 'label'=>$langs->trans("SupplierProposals"), 'desc'=>$langs->trans("ECMDocsBySupplierProposals")); } if (!empty($conf->fournisseur->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'order_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersOrders"), 'desc'=>$langs->trans("ECMDocsByOrders")); } if (!empty($conf->fournisseur->enabled)) { $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'invoice_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersInvoices"), 'desc'=>$langs->trans("ECMDocsByInvoices")); } if (!empty($conf->tax->enabled)) { $langs->load("compta"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'tax', 'test'=>$conf->tax->enabled, 'label'=>$langs->trans("SocialContributions"), 'desc'=>$langs->trans("ECMDocsBySocialContributions")); } @@ -324,6 +324,8 @@ if (!empty($conf->global->ECM_AUTO_TREE_ENABLED)) if (!empty($conf->expensereport->enabled)) { $langs->load("trips"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'expensereport', 'test'=>$conf->expensereport->enabled, 'label'=>$langs->trans("ExpenseReports"), 'desc'=>$langs->trans("ECMDocsByExpenseReports")); } if (!empty($conf->holiday->enabled)) { $langs->load("holiday"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'holiday', 'test'=>$conf->holiday->enabled, 'label'=>$langs->trans("Holidays"), 'desc'=>$langs->trans("ECMDocsByHolidays")); } if (!empty($conf->banque->enabled)) { $langs->load("banks"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'banque', 'test'=>$conf->banque->enabled, 'label'=>$langs->trans("BankAccount"), 'desc'=>$langs->trans("ECMDocsByBankAccount")); } + if (!empty($conf->mrp->enabled)) { $langs->load("mrp"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'mrp-mo', 'test'=>$conf->mrp->enabled, 'label'=>$langs->trans("MOs"), 'desc'=>$langs->trans("ECMDocsByMO")); } + if (!empty($conf->recruitment->enabled)) { $langs->load("recruitment"); $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'recruitment-recruitmentcandidature', 'test'=>$conf->recruitment->enabled, 'label'=>$langs->trans("Candidatures"), 'desc'=>$langs->trans("ECMDocsByCandidature")); } $rowspan++; $sectionauto[] = array('level'=>1, 'module'=>'user', 'test'=>1, 'label'=>$langs->trans("Users"), 'desc'=>$langs->trans("ECMDocsByUsers")); } @@ -350,7 +352,7 @@ print '
    '; // Toolbar $url = ((!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) ? '#' : ($_SERVER["PHP_SELF"].'?action=refreshmanual'.($module ? '&module='.$module : '').($section ? '&section='.$section : ''))); -print ''; +print ''; print ''; print ''; diff --git a/htdocs/ecm/search.php b/htdocs/ecm/search.php index d996f2400ee..8100ff46ba3 100644 --- a/htdocs/ecm/search.php +++ b/htdocs/ecm/search.php @@ -41,7 +41,7 @@ $user->getrights('ecm'); // Get parameters $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $section = GETPOST('section'); if (!$section) $section = 0; diff --git a/htdocs/emailcollector/class/emailcollector.class.php b/htdocs/emailcollector/class/emailcollector.class.php index 1a546256483..943b7c73fb3 100644 --- a/htdocs/emailcollector/class/emailcollector.class.php +++ b/htdocs/emailcollector/class/emailcollector.class.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php'; +require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php'; /** @@ -35,304 +36,337 @@ require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php'; */ class EmailCollector extends CommonObject { - /** - * @var string ID to identify managed object - */ - public $element = 'emailcollector'; - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'emailcollector_emailcollector'; - /** - * @var int Does emailcollector support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - */ - public $ismultientitymanaged = 1; - /** - * @var int Does emailcollector support extrafields ? 0=No, 1=Yes - */ - public $isextrafieldmanaged = 0; - /** - * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png - */ - public $picto = 'generic'; + /** + * @var string ID to identify managed object + */ + public $element = 'emailcollector'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'emailcollector_emailcollector'; + /** + * @var int Does emailcollector support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 1; + /** + * @var int Does emailcollector support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + /** + * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png + */ + public $picto = 'generic'; - /** - * @var int Field with ID of parent key if this field has a parent - */ - public $fk_element = 'fk_emailcollector'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + public $fk_element = 'fk_emailcollector'; - /** + /** * @var array List of child tables. To test if we can delete object. - */ - protected $childtables = array(); - /** - * @var array List of child tables. To know object to delete on cascade. - */ - protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction'); + */ + protected $childtables = array(); + /** + * @var array List of child tables. To know object to delete on cascade. + */ + protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction'); - /** - * 'type' if the field format. - * '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. Using a negative value means field is not shown by default on list but can be selected for viewing) - * '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) - * '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. - * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record - * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") - */ + /** + * 'type' if the field format. + * '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. Using a negative value means field is not shown by default on list but can be selected for viewing) + * '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) + * '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. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + */ - // 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', 'visible'=>2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1), - 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), - 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'help'=>'Example: MyCollector1'), - 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector'), - 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1), - 'host' => array('type'=>'varchar(255)', 'label'=>'EMailHost', 'visible'=>1, 'enabled'=>1, 'position'=>90, 'notnull'=>1, 'searchall'=>1, 'comment'=>"IMAP server", 'help'=>'Example: imap.gmail.com'), - 'hostcharset' => array('type'=>'varchar(16)', 'label'=>'HostCharset', 'visible'=>-1, 'enabled'=>1, 'position'=>91, 'notnull'=>0, 'searchall'=>0, 'comment'=>"IMAP server charset", 'help'=>'Example: "UTF-8" (May be "US-ASCII" with some Office365)'), - 'login' => array('type'=>'varchar(128)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>101, 'notnull'=>-1, 'index'=>1, 'comment'=>"IMAP login", 'help'=>'Example: myaccount@gmail.com'), - 'password' => array('type'=>'password', 'label'=>'Password', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>-1, 'comment'=>"IMAP password", 'help'=>'WithGMailYouCanCreateADedicatedPassword'), - 'source_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxSourceDirectory', 'visible'=>-1, 'enabled'=>1, 'position'=>103, 'notnull'=>1, 'default' => 'Inbox', 'help'=>'Example: INBOX'), - //'filter' => array('type'=>'text', 'label'=>'Filter', 'visible'=>1, 'enabled'=>1, 'position'=>105), - //'actiontodo' => array('type'=>'varchar(255)', 'label'=>'ActionToDo', 'visible'=>1, 'enabled'=>1, 'position'=>106), - 'target_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxTargetDirectory', 'visible'=>1, 'enabled'=>1, 'position'=>110, 'notnull'=>0, 'help'=>"EmailCollectorTargetDir"), - 'maxemailpercollect' => array('type'=>'integer', 'label'=>'MaxEmailCollectPerCollect', 'visible'=>-1, 'enabled'=>1, 'position'=>111, 'default'=>100), - 'datelastresult' => array('type'=>'datetime', 'label'=>'DateLastCollectResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>121, 'notnull'=>-1,), - 'codelastresult' => array('type'=>'varchar(16)', 'label'=>'CodeLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>122, 'notnull'=>-1,), - 'lastresult' => array('type'=>'varchar(255)', 'label'=>'LastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>123, 'notnull'=>-1,), - 'datelastok' => array('type'=>'datetime', 'label'=>'DateLastcollectResultOk', 'visible'=>1, 'enabled'=>'$action != "create"', 'position'=>125, 'notnull'=>-1,), - 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>0, 'enabled'=>1, 'position'=>61, 'notnull'=>-1,), - 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>0, 'enabled'=>1, 'position'=>62, 'notnull'=>-1,), - 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), - 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,), - //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), - 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,), - 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,), - //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), - 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,), - 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Inactive', '1'=>'Active')) - ); + // 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', 'visible'=>2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'help'=>'Example: MyCollector1'), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector'), + 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1), + 'host' => array('type'=>'varchar(255)', 'label'=>'EMailHost', 'visible'=>1, 'enabled'=>1, 'position'=>90, 'notnull'=>1, 'searchall'=>1, 'comment'=>"IMAP server", 'help'=>'Example: imap.gmail.com'), + 'hostcharset' => array('type'=>'varchar(16)', 'label'=>'HostCharset', 'visible'=>-1, 'enabled'=>1, 'position'=>91, 'notnull'=>0, 'searchall'=>0, 'comment'=>"IMAP server charset", 'help'=>'Example: "UTF-8" (May be "US-ASCII" with some Office365)'), + 'login' => array('type'=>'varchar(128)', 'label'=>'Login', 'visible'=>1, 'enabled'=>1, 'position'=>101, 'notnull'=>-1, 'index'=>1, 'comment'=>"IMAP login", 'help'=>'Example: myaccount@gmail.com'), + 'password' => array('type'=>'password', 'label'=>'Password', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>-1, 'comment'=>"IMAP password", 'help'=>'WithGMailYouCanCreateADedicatedPassword'), + 'source_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxSourceDirectory', 'visible'=>-1, 'enabled'=>1, 'position'=>103, 'notnull'=>1, 'default' => 'Inbox', 'help'=>'Example: INBOX'), + //'filter' => array('type'=>'text', 'label'=>'Filter', 'visible'=>1, 'enabled'=>1, 'position'=>105), + //'actiontodo' => array('type'=>'varchar(255)', 'label'=>'ActionToDo', 'visible'=>1, 'enabled'=>1, 'position'=>106), + 'target_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxTargetDirectory', 'visible'=>1, 'enabled'=>1, 'position'=>110, 'notnull'=>0, 'help'=>"EmailCollectorTargetDir"), + 'maxemailpercollect' => array('type'=>'integer', 'label'=>'MaxEmailCollectPerCollect', 'visible'=>-1, 'enabled'=>1, 'position'=>111, 'default'=>100), + 'datelastresult' => array('type'=>'datetime', 'label'=>'DateLastCollectResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>121, 'notnull'=>-1,), + 'codelastresult' => array('type'=>'varchar(16)', 'label'=>'CodeLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>122, 'notnull'=>-1,), + 'lastresult' => array('type'=>'varchar(255)', 'label'=>'LastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>123, 'notnull'=>-1,), + 'datelastok' => array('type'=>'datetime', 'label'=>'DateLastcollectResultOk', 'visible'=>1, 'enabled'=>'$action != "create"', 'position'=>125, 'notnull'=>-1,), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>0, 'enabled'=>1, 'position'=>61, 'notnull'=>-1,), + 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>0, 'enabled'=>1, 'position'=>62, 'notnull'=>-1,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,), + //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), + 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,), + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,), + //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Inactive', '1'=>'Active')) + ); - /** - * @var int ID - */ - public $rowid; + /** + * @var int ID + */ + public $rowid; - /** - * @var string Ref - */ - public $ref; + /** + * @var string Ref + */ + public $ref; - /** - * @var int Entity - */ - public $entity; + /** + * @var int Entity + */ + public $entity; - /** - * @var string label - */ - public $label; + /** + * @var string label + */ + public $label; - /** - * @var int Status - */ - public $status; + /** + * @var int Status + */ + public $status; - /** - * @var integer|string date_creation - */ - public $date_creation; + /** + * @var integer|string date_creation + */ + public $date_creation; - public $tms; + public $tms; - /** - * @var int ID - */ - public $fk_user_creat; + /** + * @var int ID + */ + public $fk_user_creat; - /** - * @var int ID - */ - public $fk_user_modif; + /** + * @var int ID + */ + public $fk_user_modif; - public $import_key; + public $import_key; - public $host; - public $hostcharset; - public $login; - public $password; - public $source_directory; - public $target_directory; - public $maxemailpercollect; + public $host; + public $hostcharset; + public $login; + public $password; + public $source_directory; + public $target_directory; + public $maxemailpercollect; - /** - * @var integer|string $datelastresult - */ - public $datelastresult; + /** + * @var integer|string $datelastresult + */ + public $datelastresult; - public $lastresult; - // END MODULEBUILDER PROPERTIES + public $lastresult; + // END MODULEBUILDER PROPERTIES - public $filters; - public $actions; + public $filters; + public $actions; - public $debuginfo; + public $debuginfo; - const STATUS_DISABLED = 0; - const STATUS_ENABLED = 1; + const STATUS_DISABLED = 0; + const STATUS_ENABLED = 1; - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct(DoliDB $db) - { - global $conf, $langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; - $this->db = $db; + $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'])) - { - unset($this->fields[$key]); - } - } + // 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 - foreach ($this->fields as $key => $val) - { - if (is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { - $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); - } - } - } - } + // Translate some data of arrayofkeyval + foreach ($this->fields as $key => $val) + { + if (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); - } + /** + * 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) + { + $id = $this->createCommon($user, $notrigger); - /** - * Clone and 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; + if (is_array($this->filters) && count($this->filters)) { + $emailcollectorfilter = new EmailCollectorFilter($this->db); - dol_syslog(__METHOD__, LOG_DEBUG); + foreach ($this->filters as $filter) { + $emailcollectorfilter->type = $filter['type']; + $emailcollectorfilter->rulevalue = $filter['rulevalue']; + $emailcollectorfilter->fk_emailcollector = $this->id; + $emailcollectorfilter->status = $filter['status']; - $object = new self($this->db); + $emailcollectorfilter->create($user); + } + } - $this->db->begin(); + if (is_array($this->filters) && count($this->filters)) { + $emailcollectoroperation = new EmailCollectorAction($this->db); - // Load source object - $object->fetchCommon($fromid); - // Reset some properties - unset($object->id); - unset($object->fk_user_creat); - unset($object->import_key); + foreach ($this->actions as $operation) { + $emailcollectoroperation->type = $operation['type']; + $emailcollectoroperation->actionparam = $operation['actionparam']; + $emailcollectoroperation->fk_emailcollector = $this->id; + $emailcollectoroperation->status = $operation['status']; + $emailcollectoroperation->position = $operation['position']; - // Clear fields - $object->ref = "copy_of_".$object->ref; - $object->title = $langs->trans("CopyOf")." ".$object->title; - // ... - // Clear extrafields that are unique - 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) - { - $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { - //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; - unset($object->array_options[$key]); - } - } - } + $emailcollectoroperation->create($user); + } + } - // Create clone - $object->context['createfromclone'] = 'createfromclone'; - $result = $object->createCommon($user); - if ($result < 0) { - $error++; - $this->error = $object->error; - $this->errors = $object->errors; - } + return $id; + } - unset($object->context['createfromclone']); + /** + * Clone and 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; - // End - if (!$error) { - $this->db->commit(); - return $object; - } else { - $this->db->rollback(); - return -1; - } - } + dol_syslog(__METHOD__, LOG_DEBUG); - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, 0 if not found, >0 if OK - */ - public function fetch($id, $ref = null) - { - $result = $this->fetchCommon($id, $ref); - //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); - return $result; - } + $object = new self($this->db); - /** - * Load object lines in memory from the database - * - * @return int <0 if KO, 0 if not found, >0 if OK - */ - /* + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + + $object->fetchFilters(); // Rules + $object->fetchActions(); // Operations + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + // Clear extrafields that are unique + 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) + { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) + { + //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->create($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 + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + /* public function fetchLines() { $this->lines=array(); @@ -343,655 +377,678 @@ class EmailCollector extends CommonObject } */ - /** - * Fetch all account and load objects into an array - * - * @param User $user User - * @param int $activeOnly filter if active - * @param string $sortfield field for sorting - * @param string $sortorder sorting order - * @param int $limit sort limit - * @param int $page page to start on - * @return array Array with key => EmailCollector object - */ - public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0) - { - global $langs; + /** + * Fetch all account and load objects into an array + * + * @param User $user User + * @param int $activeOnly filter if active + * @param string $sortfield field for sorting + * @param string $sortorder sorting order + * @param int $limit sort limit + * @param int $page page to start on + * @return array Array with key => EmailCollector object + */ + public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0) + { + global $langs; - $obj_ret = array(); + $obj_ret = array(); - $sql = "SELECT s.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s"; - $sql .= ' WHERE s.entity IN ('.getEntity('emailcollector').')'; - if ($activeOnly) { - $sql .= " AND s.status = 1"; - } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + $sql = "SELECT s.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s"; + $sql .= ' WHERE s.entity IN ('.getEntity('emailcollector').')'; + if ($activeOnly) { + $sql .= " AND s.status = 1"; + } + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - $emailcollector_static = new EmailCollector($this->db); - if ($emailcollector_static->fetch($obj->rowid)) { - $obj_ret[] = $emailcollector_static; - } - $i++; - } - } else { - $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list'; - dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR); - $ret = -1; - } - if (!count($obj_ret)) { - dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + $emailcollector_static = new EmailCollector($this->db); + if ($emailcollector_static->fetch($obj->rowid)) { + $obj_ret[] = $emailcollector_static; + } + $i++; + } + } else { + $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list'; + dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR); + $ret = -1; + } + if (!count($obj_ret)) { + dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG); + } - return $obj_ret; - } + return $obj_ret; + } - /** - * 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); - } + /** + * 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, 1); - } + /** + * 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, 1); + } - /** - * Return a link to the object card (with optionaly the picto) - * - * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param string $option On what the link point to ('nolink', ...) - * @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 String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) - { - global $conf, $langs, $hookmanager; + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @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 String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + 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 = ''; + $result = ''; - $label = ''.$langs->trans("EmailCollector").''; - $label .= '
    '; - $label .= ''.$langs->trans('Ref').': '.$this->ref; + $label = ''.$langs->trans("EmailCollector").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; - $url = dol_buildpath('/admin/emailcollector_card.php', 1).'?id='.$this->id; + $url = dol_buildpath('/admin/emailcollector_card.php', 1).'?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("ShowEmailCollector"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowEmailCollector"); + $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.'"' : ''); + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); - $linkstart = ''; - $linkend = ''; + $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; - $result .= $linkend; - //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + $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('emailcollectordao')); - $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; + global $action, $hookmanager; + $hookmanager->initHooks(array('emailcollectordao')); + $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 $result; + } - /** - * Return label of the 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 - * @return string Label of status - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } + /** + * Return label of the 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 + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return the status - * - * @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 - * @return string Label of status - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { - global $langs; - //$langs->load("mymodule"); - $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled'); - $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled'); - $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans('Enabled'); - $this->labelStatusShort[self::STATUS_DISABLED] = $langs->trans('Disabled'); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the status + * + * @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 + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled'); + $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled'); + $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans('Enabled'); + $this->labelStatusShort[self::STATUS_DISABLED] = $langs->trans('Disabled'); + } - $statusType = 'status5'; - if ($status == self::STATUS_ENABLED) $statusType = 'status4'; + $statusType = 'status5'; + if ($status == self::STATUS_ENABLED) $statusType = 'status4'; - return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); - } + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } - /** - * Charge les informations d'ordre info dans l'objet commande - * - * @param int $id Id of order - * @return void - */ - public function info($id) - { - $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; - $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; - } + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + public function info($id) + { + $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; + $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; + } - if ($obj->fk_user_valid) - { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } + 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) - { - $cluser = new User($this->db); - $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; - } + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->datem); - $this->date_validation = $this->db->jdate($obj->datev); - } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * Initialise object with example values - * Id must be 0 if object instance is a specimen - * - * @return void - */ - public function initAsSpecimen() - { - $this->initAsSpecimenCommon(); - } + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } - /** - * Fetch filters - * - * @return int <0 if KO, >0 if OK - */ - public function fetchFilters() - { - $this->filters = array(); + /** + * Fetch filters + * + * @return int <0 if KO, >0 if OK + * @see fetchActions() + */ + public function fetchFilters() + { + $this->filters = array(); - $sql = 'SELECT rowid, type, rulevalue, status'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter'; - $sql .= ' WHERE fk_emailcollector = '.$this->id; - //$sql.= ' ORDER BY position'; + $sql = 'SELECT rowid, type, rulevalue, status'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter'; + $sql .= ' WHERE fk_emailcollector = '.$this->id; + //$sql.= ' ORDER BY position'; - $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->filters[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'rulevalue'=>$obj->rulevalue, 'status'=>$obj->status); - $i++; - } - $this->db->free($resql); - } else dol_print_error($this->db); + $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->filters[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'rulevalue'=>$obj->rulevalue, 'status'=>$obj->status); + $i++; + } + $this->db->free($resql); + } else dol_print_error($this->db); - return 1; - } + return 1; + } - /** - * Fetch actions - * - * @return int <0 if KO, >0 if OK - */ - public function fetchActions() - { - $this->actions = array(); + /** + * Fetch actions + * + * @return int <0 if KO, >0 if OK + * @see fetchFilters() + */ + public function fetchActions() + { + $this->actions = array(); - $sql = 'SELECT rowid, type, actionparam, status'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction'; - $sql .= ' WHERE fk_emailcollector = '.$this->id; - $sql .= ' ORDER BY position'; + $sql = 'SELECT rowid, type, actionparam, status'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction'; + $sql .= ' WHERE fk_emailcollector = '.$this->id; + $sql .= ' ORDER BY position'; - $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->actions[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'actionparam'=>$obj->actionparam, 'status'=>$obj->status); - $i++; - } - $this->db->free($resql); - } else dol_print_error($this->db); - } + $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->actions[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'actionparam'=>$obj->actionparam, 'status'=>$obj->status); + $i++; + } + $this->db->free($resql); + } else dol_print_error($this->db); + } - /** - * Return the connectstring to use with IMAP connection function - * - * @param int $ssl Add /ssl tag - * @param int $norsh Add /norsh to connectstring - * @return string - */ - public function getConnectStringIMAP($ssl = 1, $norsh = 0) - { - global $conf; + /** + * Return the connectstring to use with IMAP connection function + * + * @param int $ssl Add /ssl tag + * @param int $norsh Add /norsh to connectstring + * @return string + */ + public function getConnectStringIMAP($ssl = 1, $norsh = 0) + { + global $conf; - // Connect to IMAP - $flags = '/service=imap'; // IMAP - if ($ssl) $flags .= '/ssl'; // '/tls' - $flags .= '/novalidate-cert'; - //$flags.='/readonly'; - //$flags.='/debug'; - if ($norsh || !empty($conf->global->IMPA_FORCE_NORSH)) $flags .= '/norsh'; + // Connect to IMAP + $flags = '/service=imap'; // IMAP + if ($ssl) $flags .= '/ssl'; // '/tls' + $flags .= '/novalidate-cert'; + //$flags.='/readonly'; + //$flags.='/debug'; + if ($norsh || !empty($conf->global->IMPA_FORCE_NORSH)) $flags .= '/norsh'; - $connectstringserver = '{'.$this->host.':993'.$flags.'}'; + $connectstringserver = '{'.$this->host.':993'.$flags.'}'; - return $connectstringserver; - } + return $connectstringserver; + } - /** - * Convert str to UTF-7 imap default mailbox names - * - * @param string $str String to encode - * @return string Encode string - */ - public function getEncodedUtf7($str) - { - if (function_exists('mb_convert_encoding')) { - // change spaces by entropy because mb_convert fail with spaces - $str = preg_replace("/ /", "xyxy", $str); - // if mb_convert work - if ($str = mb_convert_encoding($str, "UTF-7")) { - // change characters - $str = preg_replace("/\+A/", "&A", $str); - // change to spaces again - $str = preg_replace("/xyxy/", " ", $str); - return $str; - } else { - // print error and return false - $this->error = "error: is not possible to encode this string '".$str."'"; - return false; - } - } else { - return $str; - } - } + /** + * Convert str to UTF-7 imap default mailbox names + * + * @param string $str String to encode + * @return string Encode string + */ + public function getEncodedUtf7($str) + { + if (function_exists('mb_convert_encoding')) { + // change spaces by entropy because mb_convert fail with spaces + $str = preg_replace("/ /", "xyxy", $str); + // if mb_convert work + if ($str = mb_convert_encoding($str, "UTF-7")) { + // change characters + $str = preg_replace("/\+A/", "&A", $str); + // change to spaces again + $str = preg_replace("/xyxy/", " ", $str); + return $str; + } else { + // print error and return false + $this->error = "error: is not possible to encode this string '".$str."'"; + return false; + } + } else { + return $str; + } + } - /** - * Action executed by scheduler - * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters' - * - * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) - */ - public function doCollect() - { - global $user; + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters' + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doCollect() + { + global $user; - $nberror = 0; + $nberror = 0; - $arrayofcollectors = $this->fetchAll($user, 1); + $arrayofcollectors = $this->fetchAll($user, 1); - // Loop on each collector - foreach ($arrayofcollectors as $emailcollector) - { - $result = $emailcollector->doCollectOneCollector(); - dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id); + // Loop on each collector + foreach ($arrayofcollectors as $emailcollector) + { + $result = $emailcollector->doCollectOneCollector(); + dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id); - $this->error .= 'EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'
    '; - if (!empty($emailcollector->errors)) $this->error .= join('
    ', $emailcollector->errors); - $this->output .= 'EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'
    '; - } + $this->error .= 'EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'
    '; + if (!empty($emailcollector->errors)) $this->error .= join('
    ', $emailcollector->errors); + $this->output .= 'EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'
    '; + } - return $nberror; - } + return $nberror; + } - /** - * overwitePropertiesOfObject - * - * @param object $object Current object - * @param string $actionparam Action parameters - * @param string $messagetext Body - * @param string $subject Subject - * @param string $header Header - * @return int 0=OK, Nb of error if error - */ - private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header) - { - $errorforthisaction = 0; + /** + * overwitePropertiesOfObject + * + * @param object $object Current object + * @param string $actionparam Action parameters + * @param string $messagetext Body + * @param string $subject Subject + * @param string $header Header + * @return int 0=OK, Nb of error if error + */ + private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header) + { + $errorforthisaction = 0; - // Overwrite values with values extracted from source email - // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....' - $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); - foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) - { - $tmpclass = ''; $tmpproperty = ''; - $tmparray = explode('.', $propertytooverwrite); - if (count($tmparray) == 2) - { - $tmpclass = $tmparray[0]; - $tmpproperty = $tmparray[1]; - } else { - $tmpproperty = $tmparray[0]; - } - if ($tmpclass && ($tmpclass != $object->element)) continue; // Property is for another type of object + // Overwrite values with values extracted from source email + // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....' + $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); + foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) + { + $tmpclass = ''; $tmpproperty = ''; + $tmparray = explode('.', $propertytooverwrite); + if (count($tmparray) == 2) + { + $tmpclass = $tmparray[0]; + $tmpproperty = $tmparray[1]; + } else { + $tmpproperty = $tmparray[0]; + } + if ($tmpclass && ($tmpclass != $object->element)) continue; // Property is for another type of object - //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty)) - if ($tmpproperty) - { - $sourcestring = ''; - $sourcefield = ''; - $regexstring = ''; - //$transformationstring=''; - $regforregex = array(); - if (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*):([^:])$/', $valueforproperty, $regforregex)) - { - $sourcefield = $regforregex[1]; - $regexstring = $regforregex[2]; - //$transofrmationstring=$regforregex[3]; - } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex)) - { - $sourcefield = $regforregex[1]; - $regexstring = $regforregex[2]; - } - if (!empty($sourcefield) && !empty($regexstring)) - { - if (strtolower($sourcefield) == 'body') $sourcestring = $messagetext; - elseif (strtolower($sourcefield) == 'subject') $sourcestring = $subject; - elseif (strtolower($sourcefield) == 'header') $sourcestring = $header; + //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty)) + if ($tmpproperty) + { + $sourcestring = ''; + $sourcefield = ''; + $regexstring = ''; + //$transformationstring=''; + $regforregex = array(); + if (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*):([^:])$/', $valueforproperty, $regforregex)) + { + $sourcefield = $regforregex[1]; + $regexstring = $regforregex[2]; + //$transofrmationstring=$regforregex[3]; + } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex)) + { + $sourcefield = $regforregex[1]; + $regexstring = $regforregex[2]; + } + if (!empty($sourcefield) && !empty($regexstring)) + { + if (strtolower($sourcefield) == 'body') $sourcestring = $messagetext; + elseif (strtolower($sourcefield) == 'subject') $sourcestring = $subject; + elseif (strtolower($sourcefield) == 'header') $sourcestring = $header; - if ($sourcestring) - { - $regforval = array(); - $regexoptions = ''; - if (strtolower($sourcefield) == 'body') $regexoptions = 'ms'; // The m means ^ and $ char is valid at each new line. The s means the char '.' is valid for new lines char too - if (strtolower($sourcefield) == 'header') $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line. + if ($sourcestring) + { + $regforval = array(); + $regexoptions = ''; + if (strtolower($sourcefield) == 'body') $regexoptions = 'ms'; // The m means ^ and $ char is valid at each new line. The s means the char '.' is valid for new lines char too + if (strtolower($sourcefield) == 'header') $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line. - //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring); - if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) - { - //var_dump($regforval[count($regforval)-1]);exit; - // Overwrite param $tmpproperty - $object->$tmpproperty = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null; - } else { - // Regex not found - $object->$tmpproperty = null; - } - } else { - // Nothing can be done for this param - $errorforthisaction++; - $this->error = 'The extract rule to use has on an unknown source (must be HEADER, SUBJECT or BODY)'; - $this->errors[] = $this->error; - } - } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) - { - $valuecurrent = ''; - if (preg_match('/^options_/', $tmpproperty)) $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)]; - else $valuecurrent = $object->$tmpproperty; + //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring); + if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) + { + //var_dump($regforval[count($regforval)-1]);exit; + // Overwrite param $tmpproperty + $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null; + if (strtolower($sourcefield) == 'header') { + $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted); + } else { + $object->$tmpproperty = $valueextracted; + } + } else { + // Regex not found + $object->$tmpproperty = null; + } + } else { + // Nothing can be done for this param + $errorforthisaction++; + $this->error = 'The extract rule to use has on an unknown source (must be HEADER, SUBJECT or BODY)'; + $this->errors[] = $this->error; + } + } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) + { + $valuecurrent = ''; + if (preg_match('/^options_/', $tmpproperty)) $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)]; + else $valuecurrent = $object->$tmpproperty; - if ($regforregex[1] == 'SET' || empty($valuecurrent)) - { - $valuetouse = $regforregex[2]; - $substitutionarray = array(); - $matcharray = array(); - preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray); - //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray); - if (is_array($matcharray[1])) // $matcharray[1] is array with list of substitution key found without the __ - { - foreach ($matcharray[1] as $keytoreplace) - { - if ($keytoreplace && isset($object->$keytoreplace)) - { - $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace; - } - } - } - //var_dump($substitutionarray); - dol_syslog(var_export($substitutionarray, true)); - //var_dump($substitutionarray); - $valuetouse = make_substitutions($valuetouse, $substitutionarray); - if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse; - else $object->$tmpproperty = $valuetouse; - } - } else { - $errorforthisaction++; - $this->error = 'Bad syntax for description of action parameters: '.$actionparam; - $this->errors[] = $this->error; - } - } - } + if ($regforregex[1] == 'SET' || empty($valuecurrent)) + { + $valuetouse = $regforregex[2]; + $substitutionarray = array(); + $matcharray = array(); + preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray); + //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray); + if (is_array($matcharray[1])) // $matcharray[1] is array with list of substitution key found without the __ + { + foreach ($matcharray[1] as $keytoreplace) + { + if ($keytoreplace && isset($object->$keytoreplace)) + { + $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace; + } + } + } + //var_dump($substitutionarray); + dol_syslog(var_export($substitutionarray, true)); + //var_dump($substitutionarray); + $valuetouse = make_substitutions($valuetouse, $substitutionarray); + if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse; + else $object->$tmpproperty = $valuetouse; + } + } else { + $errorforthisaction++; + $this->error = 'Bad syntax for description of action parameters: '.$actionparam; + $this->errors[] = $this->error; + } + } + } - return $errorforthisaction; - } + return $errorforthisaction; + } - /** - * Execute collect for current collector loaded previously with fetch. - * - * @return int <0 if KO, >0 if OK - */ - public function doCollectOneCollector() - { - global $conf, $langs, $user; + /** + * Execute collect for current collector loaded previously with fetch. + * + * @return int <0 if KO, >0 if OK + */ + public function doCollectOneCollector() + { + global $conf, $langs, $user; - //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - dol_syslog("EmailCollector::doCollectOneCollector start", LOG_DEBUG); + dol_syslog("EmailCollector::doCollectOneCollector start", LOG_DEBUG); - $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda")); + $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda")); - $error = 0; - $this->output = ''; - $this->error = ''; + $error = 0; + $this->output = ''; + $this->error = ''; - $now = dol_now(); + $now = dol_now(); - if (empty($this->host)) - { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost')); - return -1; - } - if (empty($this->login)) - { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login')); - return -1; - } - if (empty($this->source_directory)) - { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory')); - return -1; - } - if (!function_exists('imap_open')) - { - $this->error = 'IMAP function not enabled on your PHP'; - return -2; - } + if (empty($this->host)) + { + $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost')); + return -1; + } + if (empty($this->login)) + { + $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login')); + return -1; + } + if (empty($this->source_directory)) + { + $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory')); + return -1; + } + if (!function_exists('imap_open')) + { + $this->error = 'IMAP function not enabled on your PHP'; + return -2; + } - $this->fetchFilters(); - $this->fetchActions(); + $this->fetchFilters(); + $this->fetchActions(); - $sourcedir = $this->source_directory; - $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag' + $sourcedir = $this->source_directory; + $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag' - $connectstringserver = $this->getConnectStringIMAP(); - $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir); - $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir); + $connectstringserver = $this->getConnectStringIMAP(); + $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir); + $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir); - $connection = imap_open($connectstringsource, $this->login, $this->password); - if (!$connection) - { - $this->error = 'Failed to open IMAP connection '.$connectstringsource; - return -3; - } - imap_errors(); // Clear stack of errors. + $connection = imap_open($connectstringsource, $this->login, $this->password); + if (!$connection) + { + $this->error = 'Failed to open IMAP connection '.$connectstringsource; + return -3; + } + imap_errors(); // Clear stack of errors. - $host = dol_getprefix('email'); + $host = dol_getprefix('email'); //$host = '123456'; - // Define the IMAP search string - // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible) - // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2 - //$search='ALL'; - $search = 'UNDELETED'; // Seems not supported by some servers - $searchhead = ''; - $searchfilterdoltrackid = 0; - $searchfilternodoltrackid = 0; - foreach ($this->filters as $rule) - { - if (empty($rule['status'])) continue; + // Define the IMAP search string + // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible) + // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2 + //$search='ALL'; + $search = 'UNDELETED'; // Seems not supported by some servers + $searchhead = ''; + $searchfilterdoltrackid = 0; + $searchfilternodoltrackid = 0; + $searchfilterisanswer = 0; + $searchfilterisnotanswer = 0; + foreach ($this->filters as $rule) + { + if (empty($rule['status'])) continue; - if ($rule['type'] == 'to') $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'bcc') $search .= ($search ? ' ' : '').'BCC'; - if ($rule['type'] == 'cc') $search .= ($search ? ' ' : '').'CC'; - if ($rule['type'] == 'from') $search .= ($search ? ' ' : '').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'subject') $search .= ($search ? ' ' : '').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'body') $search .= ($search ? ' ' : '').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'header') $search .= ($search ? ' ' : '').'HEADER '.$rule['rulevalue']; + if ($rule['type'] == 'to') { + $tmprulevaluearray = explode('*', $rule['rulevalue']); + if (count($tmprulevaluearray) >= 2) { + foreach ($tmprulevaluearray as $tmprulevalue) { + $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $tmprulevalue).'"'; + } + } else { + $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $rule['rulevalue']).'"'; + } + } + if ($rule['type'] == 'bcc') $search .= ($search ? ' ' : '').'BCC'; + if ($rule['type'] == 'cc') $search .= ($search ? ' ' : '').'CC'; + if ($rule['type'] == 'from') $search .= ($search ? ' ' : '').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'subject') $search .= ($search ? ' ' : '').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'body') $search .= ($search ? ' ' : '').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'header') $search .= ($search ? ' ' : '').'HEADER '.$rule['rulevalue']; - if ($rule['type'] == 'notinsubject') $search .= ($search ? ' ' : '').'SUBJECT NOT "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'notinbody') $search .= ($search ? ' ' : '').'BODY NOT "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'notinsubject') $search .= ($search ? ' ' : '').'SUBJECT NOT "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'notinbody') $search .= ($search ? ' ' : '').'BODY NOT "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'seen') $search .= ($search ? ' ' : '').'SEEN'; - if ($rule['type'] == 'unseen') $search .= ($search ? ' ' : '').'UNSEEN'; - if ($rule['type'] == 'unanswered') $search .= ($search ? ' ' : '').'UNANSWERED'; - if ($rule['type'] == 'answered') $search .= ($search ? ' ' : '').'ANSWERED'; - if ($rule['type'] == 'smaller') $search .= ($search ? ' ' : '').'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'larger') $search .= ($search ? ' ' : '').'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'seen') $search .= ($search ? ' ' : '').'SEEN'; + if ($rule['type'] == 'unseen') $search .= ($search ? ' ' : '').'UNSEEN'; + if ($rule['type'] == 'unanswered') $search .= ($search ? ' ' : '').'UNANSWERED'; + if ($rule['type'] == 'answered') $search .= ($search ? ' ' : '').'ANSWERED'; + if ($rule['type'] == 'smaller') $search .= ($search ? ' ' : '').'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"'; + if ($rule['type'] == 'larger') $search .= ($search ? ' ' : '').'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"'; - if ($rule['type'] == 'withtrackingid') { $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/'; } - if ($rule['type'] == 'withouttrackingid') { $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/'; } - } + if ($rule['type'] == 'withtrackingidinmsgid') { $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/'; } + if ($rule['type'] == 'withouttrackingidinmsgid') { $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/'; } + if ($rule['type'] == 'withtrackingid') { $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/'; } + if ($rule['type'] == 'withouttrackingid') { $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/'; } - if (empty($targetdir)) // Use last date as filter if there is no targetdir defined. - { - $fromdate = 0; - if ($this->datelastok) $fromdate = $this->datelastok; - if ($fromdate > 0) $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10) - //$search.=($search?' ':'').'SINCE 8-Apr-2018'; - } - dol_syslog("IMAP search string = ".$search); - //var_dump($search); + if ($rule['type'] == 'isanswer') { $searchfilterisanswer++; $searchhead .= '/References.*@.*/'; } + if ($rule['type'] == 'isnotanswer') { $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/'; } + } - $nbemailprocessed = 0; - $nbemailok = 0; - $nbactiondone = 0; - $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8"); + if (empty($targetdir)) // Use last date as filter if there is no targetdir defined. + { + $fromdate = 0; + if ($this->datelastok) $fromdate = $this->datelastok; + if ($fromdate > 0) $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10) + //$search.=($search?' ':'').'SINCE 8-Apr-2018'; + } + dol_syslog("IMAP search string = ".$search); + //var_dump($search); - // Scan IMAP inbox - $arrayofemail = imap_search($connection, $search, null, $charset); - if ($arrayofemail === false) - { - // Nothing found or search string not understood - $mapoferrrors = imap_errors(); - if ($mapoferrrors !== false) - { - $error++; - $this->error = "Search string not understood - ".join(',', $mapoferrrors); - $this->errors[] = $this->error; - } - } + $nbemailprocessed = 0; + $nbemailok = 0; + $nbactiondone = 0; + $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8"); - // Loop on each email found - if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) - { - // Loop to get part html and plain - /* + // Scan IMAP inbox + $arrayofemail = imap_search($connection, $search, null, $charset); + if ($arrayofemail === false) + { + // Nothing found or search string not understood + $mapoferrrors = imap_errors(); + if ($mapoferrrors !== false) + { + $error++; + $this->error = "Search string not understood - ".join(',', $mapoferrrors); + $this->errors[] = $this->error; + } + } + + // Loop on each email found + if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) + { + // Loop to get part html and plain + /* 0 multipart/mixed 1 multipart/alternative 1.1 text/plain @@ -1006,14 +1063,14 @@ class EmailCollector extends CommonObject 2.2.1 text/plain 2.2.2 text/html */ - /** - * create_part_array - * - * @param Object $structure Structure - * @param string $prefix prefix - * @return array Array with number and object - */ - /*function createPartArray($structure, $prefix = "") + /** + * create_part_array + * + * @param Object $structure Structure + * @param string $prefix prefix + * @return array Array with number and object + */ + /*function createPartArray($structure, $prefix = "") { //print_r($structure); $part_array=array(); @@ -1027,15 +1084,15 @@ class EmailCollector extends CommonObject return $part_array; }*/ - /** - * Sub function for createPartArray(). Only called by createPartArray() and itself. - * - * @param Object $obj Structure - * @param string $partno Part no - * @param array $part_array array - * @return void - */ - /*function addPartToArray($obj, $partno, &$part_array) + /** + * Sub function for createPartArray(). Only called by createPartArray() and itself. + * + * @param Object $obj Structure + * @param string $partno Part no + * @param array $part_array array + * @return void + */ + /*function addPartToArray($obj, $partno, &$part_array) { $part_array[] = array('part_number' => $partno, 'part_object' => $obj); if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type @@ -1063,104 +1120,137 @@ class EmailCollector extends CommonObject } }*/ - dol_syslog("Start of loop on email", LOG_INFO, 1); + dol_syslog("Start of loop on email", LOG_INFO, 1); - $i = 0; - foreach ($arrayofemail as $imapemail) - { - if ($nbemailprocessed > 1000) - { - break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect - } + $iforemailloop = 0; + foreach ($arrayofemail as $imapemail) + { + if ($nbemailprocessed > 1000) + { + break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect + } - $i++; + $iforemailloop++; - $header = imap_fetchheader($connection, $imapemail, 0); - $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines - $matches = array(); - preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches); - $headers = array_combine($matches[1], $matches[2]); - //var_dump($headers); + $header = imap_fetchheader($connection, $imapemail, 0); + $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines + /*print $header; + print $header;*/ - dol_syslog("** Process email ".$i." References: ".$headers['References']); + $matches = array(); + preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches); + $headers = array_combine($matches[1], $matches[2]); - // If there is a filter on trackid - if ($searchfilterdoltrackid > 0) - { - if (empty($headers['References']) || !preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) - { - $nbemailprocessed++; - continue; - } - } - if ($searchfilternodoltrackid > 0) - { - if (!empty($headers['References']) && preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) - { - $nbemailprocessed++; - continue; - } - } + if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) { $headers['In-Reply-To'] = $headers['in-reply-to']; } + if (!empty($headers['references']) && empty($headers['References'])) { $headers['References'] = $headers['references']; } + if (!empty($headers['message-id']) && empty($headers['Message-ID'])) { $headers['Message-ID'] = $headers['message-id']; } - $thirdpartystatic = new Societe($this->db); - $contactstatic = new Contact($this->db); - $projectstatic = new Project($this->db); - - $nbactiondoneforemail = 0; - $errorforemail = 0; - $errorforactions = 0; - $thirdpartyfoundby = ''; - $contactfoundby = ''; - $projectfoundby = ''; - - $this->db->begin(); + $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']); - // GET Email meta datas - $overview = imap_fetch_overview($connection, $imapemail, 0); + dol_syslog("** Process email ".$iforemailloop." References: ".$headers['References']); + //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." References: ".dol_escape_htmltag($headers['References'])." In-Reply-To: ".dol_escape_htmltag($headers['In-Reply-To'])."
    \n"; - dol_syslog("msgid=".$overview[0]->message_id." date=".dol_print_date($overview[0]->udate, 'dayrfc', 'gmt')." subject=".$overview[0]->subject); + // If there is a filter on trackid + if ($searchfilterdoltrackid > 0) + { + if (empty($headers['References']) || !preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) + { + $nbemailprocessed++; + continue; // Exclude email + } + } + if ($searchfilternodoltrackid > 0) + { + if (!empty($headers['References']) && preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) + { + $nbemailprocessed++; + continue; // Exclude email + } + } - // Decode $overview[0]->subject according to RFC2047 - // Can use also imap_mime_header_decode($str) - // Can use also mb_decode_mimeheader($str) - // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') - if (function_exists('iconv_mime_decode')) { - $overview[0]->subject = iconv_mime_decode($overview[0]->subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'); - } elseif (function_exists('imap_mime_header_decode')) { - $elements = imap_mime_header_decode($overview[0]->subject); - $newstring = ''; - if (!empty($elements)) { - $num = count($elements); - for ($i = 0; $i < $num; $i++) { - $newstring .= ($newstring ? ' ' : '').$elements[$i]->text; - } - $overview[0]->subject = $newstring; - } - } elseif (function_exists('mb_decode_mimeheader')) { - $overview[0]->subject = mb_decode_mimeheader($overview[0]->subject); - } - // Removed emojis - $overview[0]->subject = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview[0]->subject); + if ($searchfilterisanswer > 0) { + if (empty($headers['In-Reply-To'])) + { + $nbemailprocessed++; + continue; // Exclude email + } + // Note: we can have + // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten) + $isanswer = 0; + if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) $isanswer = 1; + //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply + //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1; - // Parse IMAP email structure - global $htmlmsg, $plainmsg, $charset, $attachments; - $this->getmsg($connection, $imapemail); + if (!$isanswer) { + $nbemailprocessed++; + continue; // Exclude email + } + } + if ($searchfilterisnotanswer > 0) { + if (!empty($headers['In-Reply-To'])) + { + // Note: we can have + // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten) + $isanswer = 0; + if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) $isanswer = 1; + //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply + //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1; + if ($isanswer) { + $nbemailprocessed++; + continue; // Exclude email + } + } + } - //$htmlmsg,$plainmsg,$charset,$attachments - $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0); - // Removed emojis - $messagetext = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $messagetext); + //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected
    \n"; - /*var_dump($plainmsg); + $thirdpartystatic = new Societe($this->db); + $contactstatic = new Contact($this->db); + $projectstatic = new Project($this->db); + + $nbactiondoneforemail = 0; + $errorforemail = 0; + $errorforactions = 0; + $thirdpartyfoundby = ''; + $contactfoundby = ''; + $projectfoundby = ''; + $ticketfoundby = ''; + $candidaturefoundby = ''; + + $this->db->begin(); + + + // GET Email meta datas + $overview = imap_fetch_overview($connection, $imapemail, 0); + + dol_syslog("msgid=".$overview[0]->message_id." date=".dol_print_date($overview[0]->udate, 'dayrfc', 'gmt')." from=".$overview[0]->from." to=".$overview[0]->to." subject=".$overview[0]->subject); + + $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject); + + $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from); + + // Removed emojis + $overview[0]->subject = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview[0]->subject); + + // Parse IMAP email structure + global $htmlmsg, $plainmsg, $charset, $attachments; + $this->getmsg($connection, $imapemail); + + //$htmlmsg,$plainmsg,$charset,$attachments + $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0); + // Removed emojis + $messagetext = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $messagetext); + + /*var_dump($plainmsg); var_dump($htmlmsg); var_dump($messagetext);*/ - /*var_dump($charset); + /*var_dump($charset); var_dump($attachments); exit;*/ - // Parse IMAP email structure - /* + // Parse IMAP email structure + /* $structure = imap_fetchstructure($connection, $imapemail, 0); $partplain = $parthtml = -1; @@ -1199,583 +1289,796 @@ class EmailCollector extends CommonObject $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK); */ - //var_dump($messagetext); - //var_dump($structure->parts[0]->parts); - //print $header; - //print $messagetext; - //exit; + //var_dump($messagetext); + //var_dump($structure->parts[0]->parts); + //print $header; + //print $messagetext; + //exit; - $fromstring = $overview[0]->from; - $sender = $overview[0]->sender; - $to = $overview[0]->to; - $sendtocc = $overview[0]->cc; - $sendtobcc = $overview[0]->bcc; - $date = $overview[0]->udate; - $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id); - $subject = $overview[0]->subject; - //var_dump($msgid);exit; + $fromstring = $overview[0]->from; - $reg = array(); - if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) - { - $from = $reg[2]; - $fromtext = $reg[1]; - } else { - $from = $fromstring; - $fromtext = ''; - } - $fk_element_id = 0; $fk_element_type = ''; + $sender = $overview[0]->sender; + $to = $overview[0]->to; + $sendtocc = $overview[0]->cc; + $sendtobcc = $overview[0]->bcc; + $date = $overview[0]->udate; + $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id); + $subject = $overview[0]->subject; + //var_dump($msgid);exit; - $contactid = 0; $thirdpartyid = 0; $projectid = 0; - - // Analyze TrackId in field References. For example: - // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e> - // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e> - // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e> - $trackid = ''; - $objectid = 0; - $objectemail = null; - - $reg = array(); - if (!empty($headers['References']) && preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $headers['References'], $reg)) - { - $trackid = $reg[1].$reg[2]; - - if ($reg[1] == 'inv') - { - $objectid = $reg[2]; - $objectemail = new Facture($this->db); - } - if ($reg[1] == 'proj') - { - $objectid = $reg[2]; - $objectemail = new Project($this->db); - } - if ($reg[1] == 'con') - { - $objectid = $reg[2]; - $objectemail = new Contact($this->db); - } - if ($reg[1] == 'thi') - { - $objectid = $reg[2]; - $objectemail = new Societe($this->db); - } - if ($reg[1] == 'use') - { - $objectid = $reg[2]; - $objectemail = new User($this->db); - } - if ($reg[1] == 'tic') - { - $objectid = $reg[2]; - $objectemail = new Ticket($this->db); - } - - if (is_object($objectemail)) - { - $result = $objectemail->fetch($objectid); - if ($result > 0) - { - $fk_element_id = $objectemail->id; - $fk_element_type = $objectemail->element; - // Fix fk_element_type - if ($fk_element_type == 'facture') $fk_element_type = 'invoice'; - - $thirdpartyid = $objectemail->fk_soc; - $contactid = $objectemail->fk_socpeople; - $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet; - } - } - - // Project - if ($projectid > 0) - { - $result = $projectstatic->fetch($projectid); - if ($result <= 0) $projectstatic->id = 0; - else { - $projectid = $projectstatic->id; - $projectfoundby = 'trackid ('.$trackid.')'; - if (empty($contactid)) $contactid = $projectstatic->fk_contact; - if (empty($thirdpartyid)) $thirdpartyid = $projectstatic->fk_soc; - } - } - // Contact - if ($contactid > 0) - { - $result = $contactstatic->fetch($contactid); - if ($result <= 0) $contactstatic->id = 0; - else { - $contactid = $contactstatic->id; - $contactfoundby = 'trackid ('.$trackid.')'; - if (empty($thirdpartyid)) $thirdpartyid = $contactstatic->fk_soc; - } - } - // Thirdparty - if ($thirdpartyid > 0) - { - $result = $thirdpartystatic->fetch($thirdpartyid); - if ($result <= 0) $thirdpartystatic->id = 0; - else { - $thirdpartyid = $thirdpartystatic->id; - $thirdpartyfoundby = 'trackid ('.$trackid.')'; - } - } - } - - if (empty($contactid)) // Try to find contact using email - { - $result = $contactstatic->fetch(0, null, '', $from); - - if ($result > 0) - { - $contactid = $contactstatic->id; - $contactfoundby = 'email of contact ('.$from.')'; - if ($contactstatic->socid > 0) - { - $result = $thirdpartystatic->fetch($contactstatic->socid); - if ($result > 0) - { - $thirdpartyid = $thirdpartystatic->id; - $thirdpartyfoundby = 'email of contact ('.$from.')'; - } - } - } - } - - if (empty($thirdpartyid)) // Try to find thirdparty using email - { - $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from); - if ($result > 0) $thirdpartyfoundby = 'email ('.$from.')'; - } - - // Do operations - foreach ($this->actions as $operation) - { - if ($errorforactions) break; - if (empty($operation['status'])) continue; - - // Make Operation - dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id); - - $actioncode = 'EMAIL_IN'; - // If we scan the Sent box, we use the code for out email - if ($this->source_directory == 'Sent') $actioncode = 'EMAIL_OUT'; - - $description = $descriptiontitle = $descriptionmeta = $descriptionfull = ''; - if (in_array($operation['type'], array('recordevent', 'project', 'ticket'))) - { - if ($operation['type'] == 'project') $descriptiontitle = $langs->trans("ProjectCreatedByEmailCollector", $msgid); - elseif ($operation['type'] == 'ticket') $descriptiontitle = $langs->trans("TicketCreatedByEmailCollector", $msgid); - else $descriptiontitle = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from; - - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject)); - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring)); - if ($sender) $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender)); - $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to)); - if ($sendtocc) $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc)); - //if ($bcc) $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Bcc").' : '.dol_escape_htmltag($bcc)); - } - - // Search and create thirdparty - if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') - { - if (empty($operation['actionparam'])) - { - $errorforactions++; - $this->error = "Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data"; - $this->errors[] = $this->error; - } else { - $actionparam = $operation['actionparam']; - $nametouseforthirdparty = ''; - - // $this->actionparam = 'SET:aaa' or 'EXTRACT:BODY:....' - $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); - foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) - { - $sourcestring = ''; - $sourcefield = ''; - $regexstring = ''; - $regforregex = array(); - - if (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex)) - { - $sourcefield = $regforregex[1]; - $regexstring = $regforregex[2]; - } - - if (!empty($sourcefield) && !empty($regexstring)) - { - if (strtolower($sourcefield) == 'body') $sourcestring = $messagetext; - elseif (strtolower($sourcefield) == 'subject') $sourcestring = $subject; - elseif (strtolower($sourcefield) == 'header') $sourcestring = $header; - - if ($sourcestring) - { - $regforval = array(); - //var_dump($regexstring);var_dump($sourcestring); - if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) - { - //var_dump($regforval[count($regforval)-1]);exit; - // Overwrite param $tmpproperty - $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null; - } else { - // Regex not found - $nametouseforthirdparty = null; - } - //var_dump($object->$tmpproperty);exit; - } else { - // Nothing can be done for this param - $errorforactions++; - $this->error = 'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)'; - $this->errors[] = $this->error; - } - } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) - { - //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1]; - //else $object->$tmpproperty = $reg[1]; - $nametouseforthirdparty = $reg[2]; - } else { - $errorforactions++; - $this->error = 'Bad syntax for description of action parameters: '.$actionparam; - $this->errors[] = $this->error; - break; - } - } - - if (!$errorforactions && $nametouseforthirdparty) - { - $result = $thirdpartystatic->fetch(0, $nametouseforthirdparty); - if ($result < 0) - { - $errorforactions++; - $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)'; - $this->errors[] = $this->error; - break; - } elseif ($result == 0) - { - if ($operation['type'] == 'loadthirdparty') - { - dol_syslog("Third party with name ".$nametouseforthirdparty." was not found"); - - $errorforactions++; - $this->error = 'ErrorFailedToLoadThirdParty'; - $this->errors[] = 'ErrorFailedToLoadThirdParty'; - } elseif ($operation['type'] == 'loadandcreatethirdparty') - { - dol_syslog("Third party with name ".$nametouseforthirdparty." was not found. We try to create it."); - - // Create thirdparty - $thirdpartystatic->name = $nametouseforthirdparty; - if ($fromtext != $nametouseforthirdparty) $thirdpartystatic->name_alias = $fromtext; - $thirdpartystatic->email = $from; - - // Overwrite values with values extracted from source email - $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header); - - if ($errorforthisaction) - { - $errorforactions++; - } else { - $result = $thirdpartystatic->create($user); - if ($result <= 0) - { - $errorforactions++; - $this->error = $thirdpartystatic->error; - $this->errors = $thirdpartystatic->errors; - } - } - } - } - } - } - } - // Create event - elseif ($operation['type'] == 'recordevent') - { - $alreadycreated = 0; - // TODO Check if $msg ID already in database for $conf->entity + $reg = array(); + if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) + { + $from = $reg[2]; + $fromtext = $reg[1]; + } else { + $from = $fromstring; + $fromtext = ''; + } + $fk_element_id = 0; $fk_element_type = ''; - if (!$alreadycreated) - { - if ($projectstatic->id > 0) - { - if ($projectfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby); - } - if ($thirdpartystatic->id > 0) - { - if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - if ($contactstatic->id > 0) - { - if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } + $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0; - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); + // Analyze TrackId in field References. For example: + // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e> + // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e> + // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e> + $trackid = ''; + $objectid = 0; + $objectemail = null; - $descriptionfull = $description; - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); + $reg = array(); + if (!empty($headers['References'])) + { + $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']); + //var_dump($headers['References']); + //var_dump($arrayofreferences); - // Insert record of emails sent - $actioncomm = new ActionComm($this->db); - $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) - $actioncomm->code = 'AC_'.$actioncode; - $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from; - $actioncomm->note_private = $descriptionfull; - $actioncomm->fk_project = $projectstatic->id; - $actioncomm->datep = $date; - $actioncomm->datef = $date; - $actioncomm->percentage = -1; // Not applicable - $actioncomm->socid = $thirdpartystatic->id; - $actioncomm->contact_id = $contactstatic->id; - $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array()); - $actioncomm->authorid = $user->id; // User saving action - $actioncomm->userownerid = $user->id; // Owner of action - // Fields when action is an email (content should be added into note) - $actioncomm->email_msgid = $msgid; - $actioncomm->email_from = $fromstring; - $actioncomm->email_sender = $sender; - $actioncomm->email_to = $to; - $actioncomm->email_tocc = $sendtocc; - $actioncomm->email_tobcc = $sendtobcc; - $actioncomm->email_subject = $subject; - $actioncomm->errors_to = ''; + foreach ($arrayofreferences as $reference) { + //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($date, 'dayhour').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."
    \n"; + if (preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $reference, $reg)) { + // This is a Dolibarr reference + $trackid = $reg[1].$reg[2]; - if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) - { - $actioncomm->fk_element = $fk_element_id; - $actioncomm->elementtype = $fk_element_type; - } + $objectid = $reg[2]; + if ($reg[1] == 'inv') + { + $objectemail = new Facture($this->db); + } + if ($reg[1] == 'proj') + { + $objectemail = new Project($this->db); + } + if ($reg[1] == 'con') + { + $objectemail = new Contact($this->db); + } + if ($reg[1] == 'thi') + { + $objectemail = new Societe($this->db); + } + if ($reg[1] == 'use') + { + $objectemail = new User($this->db); + } + if ($reg[1] == 'tic') + { + $objectemail = new Ticket($this->db); + } + if ($reg[1] == 'recruitmentcandidature') + { + $objectemail = new RecruitmentCandidature($this->db); + } + } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) { + // This is an external reference, we check if we have it in our database + if (!is_object($objectemail)) { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket where email_msgid = '".$this->db->escape($reg[1])."'"; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $objectid = $obj->rowid; + $objectemail = new Ticket($this->db); + $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')'; + } + } else { + $errorforemail++; + } + } - //$actioncomm->extraparams = $extraparams; + if (!is_object($objectemail)) { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'"; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $objectid = $obj->rowid; + $objectemail = new Project($this->db); + $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')'; + } + } else { + $errorforemail++; + } + } - // Overwrite values with values extracted from source email - $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header); + if (!is_object($objectemail)) { + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'"; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $objectid = $obj->rowid; + $objectemail = new RecruitmentCandidature($this->db); + $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')'; + } + } else { + $errorforemail++; + } + } + } - if ($errorforthisaction) - { - $errorforactions++; - } else { - $result = $actioncomm->create($user); - if ($result <= 0) - { - $errorforactions++; - $this->errors = $actioncomm->errors; - } - } - } - } - // Create event - elseif ($operation['type'] == 'project') - { - $projecttocreate = new Project($this->db); - if ($thirdpartystatic->id > 0) - { - $projecttocreate->socid = $thirdpartystatic->id; - if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - if ($contactstatic->id > 0) - { - $projecttocreate->contact_id = $contactstatic->id; - if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } + // Load object linked to email + if (is_object($objectemail)) + { + $result = $objectemail->fetch($objectid); + if ($result > 0) + { + $fk_element_id = $objectemail->id; + $fk_element_type = $objectemail->element; + // Fix fk_element_type + if ($fk_element_type == 'facture') $fk_element_type = 'invoice'; - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); + if (get_class($objectemail) != 'Societe') $thirdpartyid = $objectemail->fk_soc; + else $thirdpartyid = $objectemail->id; - $descriptionfull = $description; - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); + if (get_class($objectemail) != 'Contact') $contactid = $objectemail->fk_socpeople; + else $contactid = $objectemail->id; - $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid'); - $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent'); + if (get_class($objectemail) != 'Project') $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet; + else $projectid = $objectemail->id; + } + } - $projecttocreate->title = $subject; - $projecttocreate->date_start = $date; - $projecttocreate->date_end = ''; - $projecttocreate->opp_status = $id_opp_status; - $projecttocreate->opp_percent = $percent_opp_status; - $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...'); - $projecttocreate->note_private = $descriptionfull; - $projecttocreate->entity = $conf->entity; + // Project + if ($projectid > 0) + { + $result = $projectstatic->fetch($projectid); + if ($result <= 0) $projectstatic->id = 0; + else { + $projectid = $projectstatic->id; + if ($trackid) $projectfoundby = 'trackid ('.$trackid.')'; + if (empty($contactid)) $contactid = $projectstatic->fk_contact; + if (empty($thirdpartyid)) $thirdpartyid = $projectstatic->fk_soc; + } + } + // Contact + if ($contactid > 0) + { + $result = $contactstatic->fetch($contactid); + if ($result <= 0) $contactstatic->id = 0; + else { + $contactid = $contactstatic->id; + if ($trackid) $contactfoundby = 'trackid ('.$trackid.')'; + if (empty($thirdpartyid)) $thirdpartyid = $contactstatic->fk_soc; + } + } + // Thirdparty + if ($thirdpartyid > 0) + { + $result = $thirdpartystatic->fetch($thirdpartyid); + if ($result <= 0) $thirdpartystatic->id = 0; + else { + $thirdpartyid = $thirdpartystatic->id; + if ($trackid) $thirdpartyfoundby = 'trackid ('.$trackid.')'; + } + } - // Overwrite values with values extracted from source email. - // This may overwrite any $projecttocreate->xxx properties. - $savesocid = $projecttocreate->socid; - $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header); + if (is_object($objectemail)) + { + break; // Exit loop of references. We already found an accurate reference + } + } + } - // Set project ref if not yet defined - if (empty($projecttocreate->ref)) - { - // Get next project Ref - $defaultref = ''; - $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; + if (empty($contactid)) // Try to find contact using email + { + $result = $contactstatic->fetch(0, null, '', $from); - // Search template files - $file = ''; $classname = ''; $filefound = 0; $reldir = ''; - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); - if (file_exists($file)) - { - $filefound = 1; - $classname = $modele; - break; - } - } + if ($result > 0) + { + $contactid = $contactstatic->id; + $contactfoundby = 'email of contact ('.$from.')'; + if (empty($thirdpartyid) && $contactstatic->socid > 0) + { + $result = $thirdpartystatic->fetch($contactstatic->socid); + if ($result > 0) + { + $thirdpartyid = $thirdpartystatic->id; + $thirdpartyfoundby = 'email of contact ('.$from.')'; + } + } + } + } - if ($filefound) - { - $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); - $modProject = new $classname; + if (empty($thirdpartyid)) // Try to find thirdparty using email + { + $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from); + if ($result > 0) $thirdpartyfoundby = 'email ('.$from.')'; + } - if ($savesocid > 0) - { - if ($savesocid != $projecttocreate->socid) - { - $errorforactions++; - setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$projecttocreate->socid.') by setting socid in operation with a different value', null, 'errors'); - } - } else { - if ($projecttocreate->socid > 0) - { - $thirdpartystatic->fetch($projecttocreate->socid); - } - } + // Do operations + foreach ($this->actions as $operation) + { + $errorforthisaction = 0; - $defaultref = $modProject->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate); - } - $projecttocreate->ref = $defaultref; - } + if ($errorforactions) break; + if (empty($operation['status'])) continue; - if ($errorforthisaction) - { - $errorforactions++; - } else { - if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) - { - $errorforactions++; - $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; - } else { - // Create project - $result = $projecttocreate->create($user); - if ($result <= 0) - { - $errorforactions++; - $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error); - $this->errors = $projecttocreate->errors; - } - } - } - } - // Create event - elseif ($operation['type'] == 'ticket') - { - $tickettocreate = new Ticket($this->db); - if ($thirdpartystatic->id > 0) - { - $tickettocreate->socid = $thirdpartystatic->id; - if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); - } - if ($contactstatic->id > 0) - { - $tickettocreate->contact_id = $contactstatic->id; - if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); - } + // Make Operation + dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id); + dol_syslog("Execute action fk_element_id=".$fk_element_id." fk_element_type=".$fk_element_type); - $description = $descriptiontitle; - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $descriptionmeta); - $description = dol_concatdesc($description, "-----"); - $description = dol_concatdesc($description, $messagetext); + $actioncode = 'EMAIL_IN'; + // If we scan the Sent box, we use the code for out email + if ($this->source_directory == 'Sent') $actioncode = 'EMAIL_OUT'; - $descriptionfull = $description; - $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); - $descriptionfull = dol_concatdesc($descriptionfull, $header); + $description = $descriptiontitle = $descriptionmeta = $descriptionfull = ''; - $tickettocreate->subject = $subject; - $tickettocreate->message = $description; - $tickettocreate->type_code = 0; - $tickettocreate->category_code = 0; - $tickettocreate->severity_code = 0; - $tickettocreate->origin_email = $from; - $tickettocreate->fk_user_create = $user->id; - $tickettocreate->datec = $date; - $tickettocreate->fk_project = $projectstatic->id; - $tickettocreate->fk_soc = $thirdpartystatic->id; - $tickettocreate->notify_tiers_at_create = 0; - $tickettocreate->note_private = $descriptionfull; - $tickettocreate->entity = $conf->entity; - //$tickettocreate->fk_contact = $contactstatic->id; + $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid); - // Overwrite values with values extracted from source email. - // This may overwrite any $projecttocreate->xxx properties. - $savesocid = $tickettocreate->socid; - $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header); + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject)); + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring)); + if ($sender) $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender)); + $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to)); + if ($sendtocc) $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc)); - // Set ticket ref if not yet defined - if (empty($tickettocreate->ref)) - { - // Get next project Ref - $defaultref = ''; - $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON; + // Search and create thirdparty + if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') + { + if (empty($operation['actionparam'])) + { + $errorforactions++; + $this->error = "Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data"; + $this->errors[] = $this->error; + } else { + $actionparam = $operation['actionparam']; + $nametouseforthirdparty = ''; - // Search template files - $file = ''; $classname = ''; $filefound = 0; $reldir = ''; - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { - $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); - if (file_exists($file)) - { - $filefound = 1; - $classname = $modele; - break; - } - } + // $this->actionparam = 'SET:aaa' or 'EXTRACT:BODY:....' + $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '='); + foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) + { + $sourcestring = ''; + $sourcefield = ''; + $regexstring = ''; + $regforregex = array(); - if ($filefound) - { - $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); - $modTicket = new $classname; + if (preg_match('/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex)) + { + $sourcefield = $regforregex[1]; + $regexstring = $regforregex[2]; + } - if ($savesocid > 0) - { - if ($savesocid != $tickettocreate->socid) - { - $errorforactions++; - setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$tickettocreate->socid.') by setting socid in operation with a different value', null, 'errors'); - } - } else { - if ($tickettocreate->socid > 0) - { - $thirdpartystatic->fetch($tickettocreate->socid); - } - } + if (!empty($sourcefield) && !empty($regexstring)) + { + if (strtolower($sourcefield) == 'body') $sourcestring = $messagetext; + elseif (strtolower($sourcefield) == 'subject') $sourcestring = $subject; + elseif (strtolower($sourcefield) == 'header') $sourcestring = $header; - $defaultref = $modTicket->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); - } - $tickettocreate->ref = $defaultref; - } - // Create event specific on hook - // this code action is hook..... for support this call - elseif (substr($operation['type'], 0, 4) == 'hook') { - global $hookmanager; + if ($sourcestring) + { + $regforval = array(); + //var_dump($regexstring);var_dump($sourcestring); + if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) + { + //var_dump($regforval[count($regforval)-1]);exit; + // Overwrite param $tmpproperty + $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null; + } else { + // Regex not found + $nametouseforthirdparty = null; + } + //var_dump($object->$tmpproperty);exit; + } else { + // Nothing can be done for this param + $errorforactions++; + $this->error = 'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)'; + $this->errors[] = $this->error; + } + } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) + { + //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1]; + //else $object->$tmpproperty = $reg[1]; + $nametouseforthirdparty = $reg[2]; + } else { + $errorforactions++; + $this->error = 'Bad syntax for description of action parameters: '.$actionparam; + $this->errors[] = $this->error; + break; + } + } - if (!is_object($hookmanager)) + if (!$errorforactions && $nametouseforthirdparty) + { + $result = $thirdpartystatic->fetch(0, $nametouseforthirdparty); + if ($result < 0) + { + $errorforactions++; + $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)'; + $this->errors[] = $this->error; + break; + } elseif ($result == 0) + { + if ($operation['type'] == 'loadthirdparty') + { + dol_syslog("Third party with name ".$nametouseforthirdparty." was not found"); + + $errorforactions++; + $this->error = 'ErrorFailedToLoadThirdParty'; + $this->errors[] = 'ErrorFailedToLoadThirdParty'; + } elseif ($operation['type'] == 'loadandcreatethirdparty') + { + dol_syslog("Third party with name ".$nametouseforthirdparty." was not found. We try to create it."); + + // Create thirdparty + $thirdpartystatic->name = $nametouseforthirdparty; + if ($fromtext != $nametouseforthirdparty) $thirdpartystatic->name_alias = $fromtext; + $thirdpartystatic->email = $from; + + // Overwrite values with values extracted from source email + $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header); + + if ($errorforthisaction) + { + $errorforactions++; + } else { + $result = $thirdpartystatic->create($user); + if ($result <= 0) + { + $errorforactions++; + $this->error = $thirdpartystatic->error; + $this->errors = $thirdpartystatic->errors; + } + } + } + } + } + } + } + // Create event + elseif ($operation['type'] == 'recordevent') + { + $actioncomm = new ActionComm($this->db); + + $alreadycreated = $actioncomm->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) + { + if ($projectstatic->id > 0) + { + if ($projectfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby); + } + if ($thirdpartystatic->id > 0) + { + if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + if ($contactstatic->id > 0) + { + if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + // Insert record of emails sent + $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) + $actioncomm->code = 'AC_'.$actioncode; + $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from; + $actioncomm->note_private = $descriptionfull; + $actioncomm->fk_project = $projectstatic->id; + $actioncomm->datep = $date; + $actioncomm->datef = $date; + $actioncomm->percentage = -1; // Not applicable + $actioncomm->socid = $thirdpartystatic->id; + $actioncomm->contact_id = $contactstatic->id; + $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array()); + $actioncomm->authorid = $user->id; // User saving action + $actioncomm->userownerid = $user->id; // Owner of action + // Fields when action is an email (content should be added into note) + $actioncomm->email_msgid = $msgid; + $actioncomm->email_from = $fromstring; + $actioncomm->email_sender = $sender; + $actioncomm->email_to = $to; + $actioncomm->email_tocc = $sendtocc; + $actioncomm->email_tobcc = $sendtobcc; + $actioncomm->email_subject = $subject; + $actioncomm->errors_to = ''; + + if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) + { + $actioncomm->fk_element = $fk_element_id; + $actioncomm->elementid = $fk_element_id; + $actioncomm->elementtype = $fk_element_type; + if (is_object($objectemail) && $objectemail->module) { + $actioncomm->elementtype .= '@'.$objectemail->module; + } + } + + //$actioncomm->extraparams = $extraparams; + + // Overwrite values with values extracted from source email + $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header); + + /*var_dump($fk_element_id); + var_dump($fk_element_type); + var_dump($alreadycreated); + var_dump($operation['type']); + var_dump($actioncomm); + exit;*/ + + if ($errorforthisaction) + { + $errorforactions++; + } else { + $result = $actioncomm->create($user); + if ($result <= 0) + { + $errorforactions++; + $this->errors = $actioncomm->errors; + } + } + } + } + // Create project / lead + elseif ($operation['type'] == 'project') + { + $projecttocreate = new Project($this->db); + + $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) + { + if ($thirdpartystatic->id > 0) + { + $projecttocreate->socid = $thirdpartystatic->id; + if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + if ($contactstatic->id > 0) + { + $projecttocreate->contact_id = $contactstatic->id; + if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid'); + $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent'); + + $projecttocreate->title = $subject; + $projecttocreate->date_start = $date; + $projecttocreate->date_end = ''; + $projecttocreate->opp_status = $id_opp_status; + $projecttocreate->opp_percent = $percent_opp_status; + $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...'); + $projecttocreate->note_private = $descriptionfull; + $projecttocreate->entity = $conf->entity; + $projecttocreate->email_msgid = $msgid; + + $savesocid = $projecttocreate->socid; + + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header); + + // Set project ref if not yet defined + if (empty($projecttocreate->ref)) + { + // Get next Ref + $defaultref = ''; + $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON; + + // Search template files + $file = ''; $classname = ''; $filefound = 0; $reldir = ''; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0); + if (file_exists($file)) + { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) + { + if ($savesocid > 0) + { + if ($savesocid != $projecttocreate->socid) + { + $errorforactions++; + setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$projecttocreate->socid.') by setting socid in operation with a different value', null, 'errors'); + } + } else { + if ($projecttocreate->socid > 0) + { + $thirdpartystatic->fetch($projecttocreate->socid); + } + } + + $result = dol_include_once($reldir."core/modules/project/".$modele.'.php'); + $modModuleToUseForNextValue = new $classname; + $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate); + } + $projecttocreate->ref = $defaultref; + } + + if ($errorforthisaction) + { + $errorforactions++; + } else { + if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) + { + $errorforactions++; + $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; + } else { + // Create project + $result = $projecttocreate->create($user); + if ($result <= 0) + { + $errorforactions++; + $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error); + $this->errors = $projecttocreate->errors; + } + } + } + } + } + // Create ticket + elseif ($operation['type'] == 'ticket') + { + $tickettocreate = new Ticket($this->db); + + $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid); + if ($alreadycreated == 0) + { + if ($thirdpartystatic->id > 0) + { + $tickettocreate->socid = $thirdpartystatic->id; + $tickettocreate->fk_soc = $thirdpartystatic->id; + if ($thirdpartyfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby); + } + if ($contactstatic->id > 0) + { + $tickettocreate->contact_id = $contactstatic->id; + if ($contactfoundby) $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby); + } + + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) { + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + } + + $tickettocreate->subject = $subject; + $tickettocreate->message = $description; + $tickettocreate->type_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_type', 'use_default', 'code', 1)); + $tickettocreate->category_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_category', 'use_default', 'code', 1)); + $tickettocreate->severity_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_severity', 'use_default', 'code', 1)); + $tickettocreate->origin_email = $from; + $tickettocreate->fk_user_create = $user->id; + $tickettocreate->datec = $date; + $tickettocreate->fk_project = $projectstatic->id; + $tickettocreate->notify_tiers_at_create = 0; + $tickettocreate->note_private = $descriptionfull; + $tickettocreate->entity = $conf->entity; + $tickettocreate->email_msgid = $msgid; + //$tickettocreate->fk_contact = $contactstatic->id; + + $savesocid = $tickettocreate->socid; + + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header); + + // Set ticket ref if not yet defined + if (empty($tickettocreate->ref)) + { + // Get next Ref + $defaultref = ''; + $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON; + + // Search template files + $file = ''; $classname = ''; $filefound = 0; $reldir = ''; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); + if (file_exists($file)) + { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) + { + if ($savesocid > 0) + { + if ($savesocid != $tickettocreate->socid) + { + $errorforactions++; + setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$tickettocreate->socid.') by setting socid in operation with a different value', null, 'errors'); + } + } else { + if ($tickettocreate->socid > 0) + { + $thirdpartystatic->fetch($tickettocreate->socid); + } + } + + $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); + $modModuleToUseForNextValue = new $classname; + $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); + } + $tickettocreate->ref = $defaultref; + } + + if ($errorforthisaction) + { + $errorforactions++; + } else { + if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) + { + $errorforactions++; + $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; + } else { + // Create project + $result = $tickettocreate->create($user); + if ($result <= 0) + { + $errorforactions++; + $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error); + $this->errors = $tickettocreate->errors; + } + } + } + } + } + // Create candidature + elseif ($operation['type'] == 'candidature') + { + $candidaturetocreate = new RecruitmentCandidature($this->db); + + $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid); + if ($alreadycreated == 0) + { + $description = $descriptiontitle; + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $descriptionmeta); + $description = dol_concatdesc($description, "-----"); + $description = dol_concatdesc($description, $messagetext); + + $descriptionfull = $description; + $descriptionfull = dol_concatdesc($descriptionfull, "----- Header"); + $descriptionfull = dol_concatdesc($descriptionfull, $header); + + $candidaturetocreate->subject = $subject; + $candidaturetocreate->message = $description; + $candidaturetocreate->type_code = 0; + $candidaturetocreate->category_code = null; + $candidaturetocreate->severity_code = null; + $candidaturetocreate->email = $from; + //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from; + $candidaturetocreate->fk_user_creat = $user->id; + $candidaturetocreate->date_creation = $date; + $candidaturetocreate->fk_project = $projectstatic->id; + $candidaturetocreate->description = $description; + $candidaturetocreate->note_private = $descriptionfull; + $candidaturetocreate->entity = $conf->entity; + $candidaturetocreate->email_msgid = $msgid; + $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT; + //$candidaturetocreate->fk_contact = $contactstatic->id; + + // Overwrite values with values extracted from source email. + // This may overwrite any $projecttocreate->xxx properties. + $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header); + + // Set candidature ref if not yet defined + /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status + { + // Get next Ref + $defaultref = ''; + $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON; + + // Search template files + $file = ''; $classname = ''; $filefound = 0; $reldir = ''; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0); + if (file_exists($file)) + { + $filefound = 1; + $classname = $modele; + break; + } + } + + if ($filefound) + { + if ($savesocid > 0) + { + if ($savesocid != $candidaturetocreate->socid) + { + $errorforactions++; + setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$candidaturetocreate->socid.') by setting socid in operation with a different value', null, 'errors'); + } + } else { + if ($candidaturetocreate->socid > 0) + { + $thirdpartystatic->fetch($candidaturetocreate->socid); + } + } + + $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php'); + $modModuleToUseForNextValue = new $classname; + $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate); + } + $candidaturetocreate->ref = $defaultref; + }*/ + + if ($errorforthisaction) + { + $errorforactions++; + } else { + // Create project + $result = $candidaturetocreate->create($user); + if ($result <= 0) + { + $errorforactions++; + $this->error = 'Failed to create ticket: '.join(', ', $candidaturetocreate->errors); + $this->errors = $candidaturetocreate->errors; + } + } + } + } + // Create event specific on hook + // this code action is hook..... for support this call + elseif (substr($operation['type'], 0, 4) == 'hook') { + global $hookmanager; + + if (!is_object($hookmanager)) { $hookmanager->initHooks(array('emailcollectorcard')); + } - $parameters = array( + $parameters = array( 'connection'=> $connection, 'imapemail'=>$imapemail, 'overview'=>$overview, @@ -1785,8 +2088,6 @@ class EmailCollector extends CommonObject 'actionparam'=> $operation['actionparam'], - - 'thirdpartyid' => $thirdpartyid, 'objectid'=> $objectid, 'objectemail'=> $objectemail, @@ -1794,152 +2095,137 @@ class EmailCollector extends CommonObject 'messagetext'=>$messagetext, 'subject'=>$subject, 'header'=>$header, - ); - $res = $hookmanager->executeHooks('doCollectOneCollector', $parameters, $this, $operation['type']); + ); + $res = $hookmanager->executeHooks('doCollectOneCollector', $parameters, $this, $operation['type']); - if ($res < 0) - $this->error = $hookmanager->resPrint; + if ($res < 0) { + $errorforthisaction++; + $this->error = $hookmanager->resPrint; } + if ($errorforthisaction) + { + $errorforactions++; + } + } - if ($errorforthisaction) - { - $errorforactions++; - } else { - if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) - { - $errorforactions++; - $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id; - } else { - // Create project - $result = $tickettocreate->create($user); - if ($result <= 0) - { - $errorforactions++; - $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error); - $this->errors = $tickettocreate->errors; - } - } - } - } + if (!$errorforactions) + { + $nbactiondoneforemail++; + } + } - if (!$errorforactions) - { - $nbactiondoneforemail++; - } - } + // Error for email or not ? + if (!$errorforactions) + { + if ($targetdir) + { + dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG); + $res = imap_mail_move($connection, $imapemail, $targetdir, 0); + if ($res == false) { + $errorforemail++; + $this->error = imap_last_error(); + $this->errors[] = $this->error; + dol_syslog(imap_last_error()); + } + } else { + dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG); + } + } else { + $errorforemail++; + } - // Error for email or not ? - if (!$errorforactions) - { - if ($targetdir) - { - dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG); - $res = imap_mail_move($connection, $imapemail, $targetdir, 0); - if ($res == false) { - $errorforemail++; - $this->error = imap_last_error(); - $this->errors[] = $this->error; - dol_syslog(imap_last_error()); - } - } else { - dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG); - } - } else { - $errorforemail++; - } + unset($objectemail); + unset($projectstatic); + unset($thirdpartystatic); + unset($contactstatic); - unset($objectemail); - unset($projectstatic); - unset($thirdpartystatic); - unset($contactstatic); + $nbemailprocessed++; - $nbemailprocessed++; + if (!$errorforemail) + { + $nbactiondone += $nbactiondoneforemail; + $nbemailok++; - if (!$errorforemail) - { - $nbactiondone += $nbactiondoneforemail; - $nbemailok++; + $this->db->commit(); - $this->db->commit(); + // Stop the loop to process email if we reach maximum collected per collect + if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) + { + dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now."); + break; + } + } else { + $error++; - // Stop the loop to process email if we reach maximum collected per collect - if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) - { - dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now."); - break; - } - } else { - $error++; + $this->db->rollback(); + } + } - $this->db->rollback(); - } - } + $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone); - $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone); + dol_syslog("End of loop on emails", LOG_INFO, -1); + } else { + $output = $langs->trans('NoNewEmailToProcess'); + } - dol_syslog("End of loop on emails", LOG_INFO, -1); - } else { - $output = $langs->trans('NoNewEmailToProcess'); - } + imap_expunge($connection); // To validate any move - imap_expunge($connection); // To validate any move + imap_close($connection); - imap_close($connection); + $this->datelastresult = $now; + $this->lastresult = $output; + $this->debuginfo = 'IMAP search string used : '.$search; + if ($searchhead) $this->debuginfo .= '
    Then search string into email header : '.$searchhead; - $this->datelastresult = $now; - $this->lastresult = $output; - $this->debuginfo = 'IMAP search string used : '.$search; - if ($searchhead) $this->debuginfo .= '
    Then search string into email header : '.$searchhead; + if (!$error) $this->datelastok = $now; - if (!$error) $this->datelastok = $now; + if (!empty($this->errors)) $this->lastresult .= " - ".join(" - ", $this->errors); + $this->codelastresult = ($error ? 'KO' : 'OK'); + $this->update($user); - if (!empty($this->errors)) $this->lastresult .= " - ".join(" - ", $this->errors); - $this->codelastresult = ($error ? 'KO' : 'OK'); - $this->update($user); + dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG); - dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG); - - return $error ?-1 : 1; - } + return $error ?-1 : 1; + } - // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation + // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation - /** - * getmsg - * - * @param Object $mbox Structure - * @param string $mid prefix - * @return array Array with number and object - */ - private function getmsg($mbox, $mid) - { - // input $mbox = IMAP stream, $mid = message id - // output all the following: - global $charset, $htmlmsg, $plainmsg, $attachments; - $htmlmsg = $plainmsg = $charset = ''; - $attachments = array(); + /** + * getmsg + * + * @param Object $mbox Structure + * @param string $mid prefix + * @return array Array with number and object + */ + private function getmsg($mbox, $mid) + { + // input $mbox = IMAP stream, $mid = message id + // output all the following: + global $charset, $htmlmsg, $plainmsg, $attachments; + $htmlmsg = $plainmsg = $charset = ''; + $attachments = array(); - // HEADER - //$h = imap_header($mbox,$mid); - // add code here to get date, from, to, cc, subject... + // HEADER + //$h = imap_header($mbox,$mid); + // add code here to get date, from, to, cc, subject... - // BODY - $s = imap_fetchstructure($mbox, $mid); + // BODY + $s = imap_fetchstructure($mbox, $mid); - if (!$s->parts) { - // simple - $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number - } else { - // multipart: cycle through each part - foreach ($s->parts as $partno0 => $p) { - $this->getpart($mbox, $mid, $p, $partno0 + 1); - } - } - } + if (!$s->parts) { + // simple + $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number + } else { + // multipart: cycle through each part + foreach ($s->parts as $partno0 => $p) { + $this->getpart($mbox, $mid, $p, $partno0 + 1); + } + } + } - /* partno string + /* partno string 0 multipart/mixed 1 multipart/alternative 1.1 text/plain @@ -1954,91 +2240,91 @@ class EmailCollector extends CommonObject 2.2.1 text/plain 2.2.2 text/html */ - /** - * Sub function for getpart(). Only called by createPartArray() and itself. - * - * @param Object $mbox Structure - * @param string $mid Part no - * @param Object $p Object p - * @param string $partno Partno - * @return void - */ - private function getpart($mbox, $mid, $p, $partno) - { - // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple - global $htmlmsg, $plainmsg, $charset, $attachments; + /** + * Sub function for getpart(). Only called by createPartArray() and itself. + * + * @param Object $mbox Structure + * @param string $mid Part no + * @param Object $p Object p + * @param string $partno Partno + * @return void + */ + private function getpart($mbox, $mid, $p, $partno) + { + // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple + global $htmlmsg, $plainmsg, $charset, $attachments; - // DECODE DATA - $data = ($partno) ? - imap_fetchbody($mbox, $mid, $partno) : // multipart - imap_body($mbox, $mid); // simple - // Any part may be encoded, even plain text messages, so check everything. - if ($p->encoding == 4) - $data = quoted_printable_decode($data); - elseif ($p->encoding == 3) - $data = base64_decode($data); + // DECODE DATA + $data = ($partno) ? + imap_fetchbody($mbox, $mid, $partno) : // multipart + imap_body($mbox, $mid); // simple + // Any part may be encoded, even plain text messages, so check everything. + if ($p->encoding == 4) + $data = quoted_printable_decode($data); + elseif ($p->encoding == 3) + $data = base64_decode($data); - // PARAMETERS - // get all parameters, like charset, filenames of attachments, etc. - $params = array(); - if ($p->parameters) - { - foreach ($p->parameters as $x) - { - $params[strtolower($x->attribute)] = $x->value; - } - } - if ($p->dparameters) - { - foreach ($p->dparameters as $x) - { - $params[strtolower($x->attribute)] = $x->value; - } - } + // PARAMETERS + // get all parameters, like charset, filenames of attachments, etc. + $params = array(); + if ($p->parameters) + { + foreach ($p->parameters as $x) + { + $params[strtolower($x->attribute)] = $x->value; + } + } + if ($p->dparameters) + { + foreach ($p->dparameters as $x) + { + $params[strtolower($x->attribute)] = $x->value; + } + } - // ATTACHMENT - // Any part with a filename is an attachment, - // so an attached text file (type 0) is not mistaken as the message. - if ($params['filename'] || $params['name']) { - // filename may be given as 'Filename' or 'Name' or both - $filename = ($params['filename']) ? $params['filename'] : $params['name']; - // filename may be encoded, so see imap_mime_header_decode() - $attachments[$filename] = $data; // this is a problem if two files have same name - } + // ATTACHMENT + // Any part with a filename is an attachment, + // so an attached text file (type 0) is not mistaken as the message. + if ($params['filename'] || $params['name']) { + // filename may be given as 'Filename' or 'Name' or both + $filename = ($params['filename']) ? $params['filename'] : $params['name']; + // filename may be encoded, so see imap_mime_header_decode() + $attachments[$filename] = $data; // this is a problem if two files have same name + } - // TEXT - if ($p->type == 0 && $data) { + // TEXT + if ($p->type == 0 && $data) { if (!empty($params['charset'])) { - $data = $this->convertStringEncoding($data, $params['charset']); - } - // Messages may be split in different parts because of inline attachments, - // so append parts together with blank row. - if (strtolower($p->subtype) == 'plain') - $plainmsg .= trim($data)."\n\n"; - else $htmlmsg .= $data."

    "; - $charset = $params['charset']; // assume all parts are same charset - } + $data = $this->convertStringEncoding($data, $params['charset']); + } + // Messages may be split in different parts because of inline attachments, + // so append parts together with blank row. + if (strtolower($p->subtype) == 'plain') + $plainmsg .= trim($data)."\n\n"; + else $htmlmsg .= $data."

    "; + $charset = $params['charset']; // assume all parts are same charset + } - // EMBEDDED MESSAGE - // Many bounce notifications embed the original message as type 2, - // but AOL uses type 1 (multipart), which is not handled here. - // There are no PHP functions to parse embedded messages, - // so this just appends the raw source to the main message. - elseif ($p->type == 2 && $data) { + // EMBEDDED MESSAGE + // Many bounce notifications embed the original message as type 2, + // but AOL uses type 1 (multipart), which is not handled here. + // There are no PHP functions to parse embedded messages, + // so this just appends the raw source to the main message. + elseif ($p->type == 2 && $data) { if (!empty($params['charset'])) { - $data = $this->convertStringEncoding($data, $params['charset']); - } - $plainmsg .= $data."\n\n"; - } + $data = $this->convertStringEncoding($data, $params['charset']); + } + $plainmsg .= $data."\n\n"; + } - // SUBPART RECURSION - if ($p->parts) { - foreach ($p->parts as $partno0=>$p2) - { - $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc. - } - } - } + // SUBPART RECURSION + if ($p->parts) { + foreach ($p->parts as $partno0=>$p2) + { + $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc. + } + } + } /** * Converts a string from one encoding to another. @@ -2063,4 +2349,40 @@ class EmailCollector extends CommonObject } return $convertedString; } + + /** + * Decode a subject string according to RFC2047 + * Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...' + * Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB' + * Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' => + * Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?=' + * + * @param string $subject Subject + * @return string Decoded subject (in UTF-8) + */ + protected function decodeSMTPSubject($subject) + { + // Decode $overview[0]->subject according to RFC2047 + // Can use also imap_mime_header_decode($str) + // Can use also mb_decode_mimeheader($str) + // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') + if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) { + $elements = imap_mime_header_decode($subject); + $newstring = ''; + if (!empty($elements)) { + $num = count($elements); + for ($i = 0; $i < $num; $i++) { + $stringinutf8 = (in_array(strtoupper($elements[$i]->charset), array('DEFAULT', 'UTF-8')) ? $elements[$i]->text : iconv_mime_decode($elements[$i]->text, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $elements[$i]->charset)); + $newstring .= $stringinutf8; + } + $subject = $newstring; + } + } elseif (!function_exists('mb_decode_mimeheader')) { + $subject = mb_decode_mimeheader($subject); + } elseif (function_exists('iconv_mime_decode')) { + $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'); + } + + return $subject; + } } diff --git a/htdocs/emailcollector/class/emailcollectorfilter.class.php b/htdocs/emailcollector/class/emailcollectorfilter.class.php index 8e4f5814db4..cb8db05fa34 100644 --- a/htdocs/emailcollector/class/emailcollectorfilter.class.php +++ b/htdocs/emailcollector/class/emailcollectorfilter.class.php @@ -165,11 +165,11 @@ class EmailCollectorFilter extends CommonObject $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); return -1; } - if (!in_array($this->type, array('seen', 'unseen', 'unanswered', 'answered', 'withtrackingid', 'withouttrackingid')) && empty($this->rulevalue)) + if (!in_array($this->type, array('seen', 'unseen', 'unanswered', 'answered', 'withtrackingidinmsgid', 'withouttrackingidinmsgid', 'withtrackingid', 'withouttrackingid', 'isanswer', 'isnotanswer')) && empty($this->rulevalue)) { $langs->load("errors"); $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SearchString")); - return -1; + return -2; } return $this->createCommon($user, $notrigger); diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 929e7ecafd0..86ec2ee5c38 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -50,8 +50,8 @@ if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) require 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'; + 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 @@ -116,11 +116,11 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($cancel) + if ($cancel) { $action = ''; $object->fetch($id); // show shipment also after canceling modification - } + } include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once @@ -132,31 +132,31 @@ if (empty($reshook)) // Reopen if ($action == 'reopen' && $user->rights->expedition->creer) { - $object->fetch($id); - $result = $object->reOpen(); + $object->fetch($id); + $result = $object->reOpen(); } // Set incoterm if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } if ($action == 'setref_customer') { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'SHIPMENT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editref_customer'; - } else { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } + $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'SHIPMENT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editref_customer'; + } else { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } } if ($action == 'update_extras') @@ -164,72 +164,72 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); - if ($ret < 0) $error++; + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); + if ($ret < 0) $error++; - if (!$error) - { - // Actions on extra fields - $result = $object->insertExtraFields('SHIPMENT_MODIFY'); + if (!$error) + { + // Actions on extra fields + $result = $object->insertExtraFields('SHIPMENT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } + } - if ($error) - $action = 'edit_extras'; + if ($error) + $action = 'edit_extras'; } // Create shipment if ($action == 'add' && $user->rights->expedition->creer) { - $error = 0; - $predef = ''; + $error = 0; + $predef = ''; - $db->begin(); + $db->begin(); - $object->note = GETPOST('note', 'alpha'); - $object->origin = $origin; - $object->origin_id = $origin_id; - $object->fk_project = GETPOST('projectid', 'int'); - $object->weight = GETPOST('weight', 'int') == '' ? "NULL" : GETPOST('weight', 'int'); - $object->sizeH = GETPOST('sizeH', 'int') == '' ? "NULL" : GETPOST('sizeH', 'int'); - $object->sizeW = GETPOST('sizeW', 'int') == '' ? "NULL" : GETPOST('sizeW', 'int'); - $object->sizeS = GETPOST('sizeS', 'int') == '' ? "NULL" : GETPOST('sizeS', 'int'); - $object->size_units = GETPOST('size_units', 'int'); - $object->weight_units = GETPOST('weight_units', 'int'); + $object->note = GETPOST('note', 'alpha'); + $object->origin = $origin; + $object->origin_id = $origin_id; + $object->fk_project = GETPOST('projectid', 'int'); + $object->weight = GETPOST('weight', 'int') == '' ? "NULL" : GETPOST('weight', 'int'); + $object->sizeH = GETPOST('sizeH', 'int') == '' ? "NULL" : GETPOST('sizeH', 'int'); + $object->sizeW = GETPOST('sizeW', 'int') == '' ? "NULL" : GETPOST('sizeW', 'int'); + $object->sizeS = GETPOST('sizeS', 'int') == '' ? "NULL" : GETPOST('sizeS', 'int'); + $object->size_units = GETPOST('size_units', 'int'); + $object->weight_units = GETPOST('weight_units', 'int'); - $date_delivery = dol_mktime(GETPOST('date_deliveryhour', 'int'), GETPOST('date_deliverymin', 'int'), 0, GETPOST('date_deliverymonth', 'int'), GETPOST('date_deliveryday', 'int'), GETPOST('date_deliveryyear', 'int')); + $date_delivery = dol_mktime(GETPOST('date_deliveryhour', 'int'), GETPOST('date_deliverymin', 'int'), 0, GETPOST('date_deliverymonth', 'int'), GETPOST('date_deliveryday', 'int'), GETPOST('date_deliveryyear', 'int')); - // We will loop on each line of the original document to complete the shipping object with various info and quantity to deliver - $classname = ucfirst($object->origin); - $objectsrc = new $classname($db); - $objectsrc->fetch($object->origin_id); + // We will loop on each line of the original document to complete the shipping object with various info and quantity to deliver + $classname = ucfirst($object->origin); + $objectsrc = new $classname($db); + $objectsrc->fetch($object->origin_id); - $object->socid = $objectsrc->socid; - $object->ref_customer = GETPOST('ref_customer', 'alpha'); - $object->model_pdf = GETPOST('model'); - $object->date_delivery = $date_delivery; // Date delivery planed - $object->fk_delivery_address = $objectsrc->fk_delivery_address; - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); - $object->tracking_number = GETPOST('tracking_number', 'alpha'); - $object->ref_int = GETPOST('ref_int', 'alpha'); - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); + $object->socid = $objectsrc->socid; + $object->ref_customer = GETPOST('ref_customer', 'alpha'); + $object->model_pdf = GETPOST('model'); + $object->date_delivery = $date_delivery; // Date delivery planed + $object->fk_delivery_address = $objectsrc->fk_delivery_address; + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->tracking_number = GETPOST('tracking_number', 'alpha'); + $object->ref_int = GETPOST('ref_int', 'alpha'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); - $batch_line = array(); + $batch_line = array(); $stockLine = array(); $array_options = array(); - $num = count($objectsrc->lines); - $totalqty = 0; + $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,62 +238,62 @@ if (empty($reshook)) $j = 0; $batch = "batchl".$i."_0"; $stockLocation = "ent1".$i."_0"; - $qty = "qtyl".$i; + $qty = "qtyl".$i; if ($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)) - { - // 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 - $subtotalqty += $sub_qty[$j]['q']; + if (GETPOSTISSET($batch)) + { + //shipment line with batch-enable product + $qty .= '_'.$j; + 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 + $subtotalqty += $sub_qty[$j]['q']; - //var_dump($qty);var_dump($batch);var_dump($sub_qty[$j]['q']);var_dump($sub_qty[$j]['id_batch']); + //var_dump($qty);var_dump($batch);var_dump($sub_qty[$j]['q']);var_dump($sub_qty[$j]['id_batch']); - $j++; - $batch = "batchl".$i."_".$j; - $qty = "qtyl".$i.'_'.$j; - } + $j++; + $batch = "batchl".$i."_".$j; + $qty = "qtyl".$i.'_'.$j; + } - $batch_line[$i]['detail'] = $sub_qty; // array of details - $batch_line[$i]['qty'] = $subtotalqty; - $batch_line[$i]['ix_l'] = GETPOST($idl, 'int'); + $batch_line[$i]['detail'] = $sub_qty; // array of details + $batch_line[$i]['qty'] = $subtotalqty; + $batch_line[$i]['ix_l'] = GETPOST($idl, 'int'); - $totalqty += $subtotalqty; - } else { - // No detail were provided for lots - 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 - setEventMessages($langs->trans("StockIsRequiredToChooseWhichLotToUse"), null, 'errors'); - } - } + $totalqty += $subtotalqty; + } else { + // No detail were provided for lots + 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 + setEventMessages($langs->trans("StockIsRequiredToChooseWhichLotToUse"), null, 'errors'); + } + } } elseif (GETPOSTISSET($stockLocation)) { - //shipment line from multiple stock locations - $qty .= '_'.$j; - while (GETPOSTISSET($stockLocation)) - { - // save sub line of warehouse - $stockLine[$i][$j]['qty'] = GETPOST($qty, 'int'); - $stockLine[$i][$j]['warehouse_id'] = GETPOST($stockLocation, 'int'); - $stockLine[$i][$j]['ix_l'] = GETPOST($idl, 'int'); + //shipment line from multiple stock locations + $qty .= '_'.$j; + while (GETPOSTISSET($stockLocation)) + { + // save sub line of warehouse + $stockLine[$i][$j]['qty'] = GETPOST($qty, 'int'); + $stockLine[$i][$j]['warehouse_id'] = GETPOST($stockLocation, 'int'); + $stockLine[$i][$j]['ix_l'] = GETPOST($idl, 'int'); - $totalqty += GETPOST($qty, 'int'); + $totalqty += GETPOST($qty, 'int'); - $j++; - $stockLocation = "ent1".$i."_".$j; - $qty = "qtyl".$i.'_'.$j; - } + $j++; + $stockLocation = "ent1".$i."_".$j; + $qty = "qtyl".$i.'_'.$j; + } } else { - //var_dump(GETPOST($qty,'int')); var_dump($_POST); var_dump($batch);exit; + //var_dump(GETPOST($qty,'int')); 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 += GETPOST($qty, 'int'); } @@ -307,35 +307,35 @@ if (empty($reshook)) unset($_POST["options_".$key]); } } - } + } - //var_dump($batch_line[2]); + //var_dump($batch_line[2]); - if ($totalqty > 0) // There is at least one thing to ship - { - //var_dump($_POST);exit; - for ($i = 0; $i < $num; $i++) - { - $qty = "qtyl".$i; + if ($totalqty > 0) // There is at least one thing to ship + { + //var_dump($_POST);exit; + for ($i = 0; $i < $num; $i++) + { + $qty = "qtyl".$i; if (!isset($batch_line[$i])) { // not batch mode 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) - { - $ret = $object->addline($stockLine[$i][$j]['warehouse_id'], $stockLine[$i][$j]['ix_l'], $stockLine[$i][$j]['qty'], $array_options[$i]); - if ($ret < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - } + //shipment from multiple stock locations + $nbstockline = count($stockLine[$i]); + 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) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + } } else { if (GETPOST($qty, 'int') > 0 || (GETPOST($qty, 'int') == 0 && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS)) { @@ -365,35 +365,35 @@ if (empty($reshook)) } } } - } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + } + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) $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) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - } else { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("QtyToShip").'/'.$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $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) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + } else { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("QtyToShip").'/'.$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $error++; + } - if (!$error) - { - $db->commit(); - header("Location: card.php?id=".$object->id); - exit; - } else { - $db->rollback(); - $_GET["commande_id"] = GETPOST('commande_id', 'int'); - $action = 'create'; - } + if (!$error) + { + $db->commit(); + header("Location: card.php?id=".$object->id); + exit; + } else { + $db->rollback(); + $_GET["commande_id"] = GETPOST('commande_id', 'int'); + $action = 'create'; + } } /* @@ -401,67 +401,67 @@ if (empty($reshook)) */ elseif ($action == 'create_delivery' && $conf->livraison_bon->enabled && $user->rights->expedition->livraison->creer) { - $result = $object->create_delivery($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT.'/livraison/card.php?action=create_delivery&id='.$result); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->create_delivery($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT.'/livraison/card.php?action=create_delivery&id='.$result); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } 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->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))) ) { - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $result = $object->valid($user); + $result = $object->valid($user); - if ($result < 0) - { + if ($result < 0) + { $langs->load("errors"); setEventMessages($langs->trans($object->error), $object->errors, 'errors'); - } else { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + } else { + // 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 = $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) dol_print_error($db, $result); - } - } + $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db, $result); + } + } } 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) - { - $result = $object->setStatut(-1); - } else { + $result = $object->cancel(0, $also_update_stock); + if ($result > 0) + { + $result = $object->setStatut(-1); + } else { setEventMessages($object->error, $object->errors, 'errors'); - } + } } 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) - { - header("Location: ".DOL_URL_ROOT.'/expedition/index.php'); - exit; - } else { + $also_update_stock = (GETPOST('alsoUpdateStock', 'alpha') ? 1 : 0); + $result = $object->delete(0, $also_update_stock); + 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))) @@ -475,15 +475,15 @@ if (empty($reshook)) 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')); + //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->set_date_livraison($user, $datedelivery); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result = $object->set_date_livraison($user, $datedelivery); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Action update @@ -498,50 +498,50 @@ if (empty($reshook)) && $user->rights->expedition->creer ) { - $error = 0; + $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 == 'settrueWeight') { - $object->trueWeight = trim(GETPOST('trueWeight', '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 == 'settrueHeight') { - $object->trueHeight = trim(GETPOST('trueHeight', '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) - { - header("Location: card.php?id=".$object->id); - exit; - } - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$error) + { + if ($object->update($user) >= 0) + { + header("Location: card.php?id=".$object->id); + exit; + } + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ""; + $action = ""; } elseif ($action == 'classifybilled') { - $object->fetch($id); - $result = $object->set_billed(); - if ($result >= 0) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit(); - } + $object->fetch($id); + $result = $object->set_billed(); + if ($result >= 0) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit(); + } setEventMessages($object->error, $object->errors, 'errors'); } elseif ($action == 'classifyclosed') { - $object->fetch($id); - $result = $object->setClosed(); - if ($result >= 0) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit(); - } + $object->fetch($id); + $result = $object->setClosed(); + if ($result >= 0) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit(); + } setEventMessages($object->error, $object->errors, 'errors'); } @@ -766,7 +766,7 @@ if (empty($reshook)) } } } else { - // Product no predefined + // Product no predefined $qty = "qtyl".$line_id; $line->id = $line_id; $line->qty = GETPOST($qty, 'int'); @@ -798,7 +798,7 @@ if (empty($reshook)) } $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } else { header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // To redisplay the form being edited @@ -838,163 +838,163 @@ $warehousestatic = new Entrepot($db); if ($action == 'create2') { - print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); + print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); - print '
    '.$langs->trans("ShipmentCreationIsDoneFromOrder"); - $action = ''; $id = ''; $ref = ''; + print '
    '.$langs->trans("ShipmentCreationIsDoneFromOrder"); + $action = ''; $id = ''; $ref = ''; } // Mode creation. if ($action == 'create') { - $expe = new Expedition($db); + $expe = new Expedition($db); - print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); + print load_fiche_titre($langs->trans("CreateShipment"), '', 'dolly'); - if (!$origin) - { - setEventMessages($langs->trans("ErrorBadParameters"), null, 'errors'); - } + if (!$origin) + { + setEventMessages($langs->trans("ErrorBadParameters"), null, 'errors'); + } - if ($origin) - { - $classname = ucfirst($origin); + if ($origin) + { + $classname = ucfirst($origin); - $object = new $classname($db); - if ($object->fetch($origin_id)) // This include the fetch_lines - { - $soc = new Societe($db); - $soc->fetch($object->socid); + $object = new $classname($db); + 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); + $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 ''; - print ''; - print ''; - print ''; - print ''; - if (GETPOST('entrepot_id', 'int')) - { - print ''; - } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (GETPOST('entrepot_id', 'int')) + { + print ''; + } - dol_fiche_head(''); + dol_fiche_head(''); - print ''; + print '
    '; - // Ref - print ''; - print "\n"; + // Ref + print ''; + print "\n"; - // Ref client - print ''; - print ''; + // Ref client + print ''; + print ''; - // Tiers - print ''; - print ''; - print ''; + // Tiers + print ''; + print ''; + print ''; - // Project - 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); + // Project + 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); - $langs->load("projects"); - print ''; - print ''; - print ''; - } + $langs->load("projects"); + print ''; + print ''; + print ''; + } - // Date delivery planned - print ''; - print '\n"; - print ''; + // Date delivery planned + print ''; + print '\n"; + print ''; - // Note Public - print ''; - print '"; + // Note Public + print ''; + print '"; - // Note Private - if ($object->note_private && !$user->socid) - { - print ''; - print '"; - } + // Note Private + if ($object->note_private && !$user->socid) + { + print ''; + print '"; + } - // Weight - print ''; - // Dim - print ''; + // Weight + print ''; + // Dim + print ''; - // Delivery method - print ""; - print '\n"; + // Delivery method + print ""; + print '\n"; - // Tracking number - print ""; - print '\n"; + // Tracking number + print ""; + print '\n"; - // Other attributes - $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3', 'socid' => $socid); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $expe, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Other attributes + $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3', 'socid' => $socid); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $expe, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (empty($reshook)) { // copy from order @@ -1005,186 +1005,191 @@ if ($action == 'create') } - // Incoterms + // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; print ''; - print ''; } - // Document model + // Document model include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; $liste = ModelePdfExpedition::liste_modeles($db); if (count($liste) > 1) { - print ""; - print '\n"; + print ""; + print '\n"; } - print "
    '; - if ($origin == 'commande' && !empty($conf->commande->enabled)) - { - print $langs->trans("RefOrder").''.img_object($langs->trans("ShowOrder"), 'order').' '.$object->ref; - } - if ($origin == 'propal' && !empty($conf->propal->enabled)) - { - print $langs->trans("RefProposal").''.img_object($langs->trans("ShowProposal"), 'propal').' '.$object->ref; - } - print '
    '; + if ($origin == 'commande' && !empty($conf->commande->enabled)) + { + print $langs->trans("RefOrder").''.img_object($langs->trans("ShowOrder"), 'order').' '.$object->ref; + } + if ($origin == 'propal' && !empty($conf->propal->enabled)) + { + print $langs->trans("RefProposal").''.img_object($langs->trans("ShowProposal"), 'propal').' '.$object->ref; + } + print '
    '; - if ($origin == 'commande') print $langs->trans('RefCustomerOrder'); - elseif ($origin == 'propal') print $langs->trans('RefCustomerOrder'); - else print $langs->trans('RefCustomer'); - print ''; - print ''; - print '
    '; + if ($origin == 'commande') print $langs->trans('RefCustomerOrder'); + elseif ($origin == 'propal') print $langs->trans('RefCustomerOrder'); + else print $langs->trans('RefCustomer'); + print ''; + print ''; + print '
    '.$langs->trans('Company').''.$soc->getNomUrl(1).'
    '.$langs->trans('Company').''.$soc->getNomUrl(1).'
    '.$langs->trans("Project").''; - print img_picto('', 'project'); - $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid', 0); - print ' id).'">'; - print '
    '.$langs->trans("Project").''; + print img_picto('', 'project'); + $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid', 0); + print ' id).'">'; + print '
    '.$langs->trans("DateDeliveryPlanned").''; - //print dol_print_date($object->date_livraison, "day"); // date_livraison come from order and will be stored into date_delivery planed. - $date_delivery = ($date_delivery ? $date_delivery : $object->date_livraison); // $date_delivery comes from GETPOST - print $form->selectDate($date_delivery ? $date_delivery : -1, 'date_delivery', 1, 1, 1); - print "
    '.$langs->trans("DateDeliveryPlanned").''; + //print dol_print_date($object->date_livraison, "day"); // date_livraison come from order and will be stored into date_delivery planed. + $date_delivery = ($date_delivery ? $date_delivery : $object->date_livraison); // $date_delivery comes from GETPOST + print $form->selectDate($date_delivery ? $date_delivery : -1, 'date_delivery', 1, 1, 1); + print "
    '.$langs->trans("NotePublic").''; - $doleditor = new DolEditor('note_public', $object->note_public, '', 60, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print "
    '.$langs->trans("NotePublic").''; + $doleditor = new DolEditor('note_public', $object->note_public, '', 60, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print "
    '.$langs->trans("NotePrivate").''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 60, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print "
    '.$langs->trans("NotePrivate").''; + $doleditor = new DolEditor('note_private', $object->note_private, '', 60, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print "
    '; - print $langs->trans("Weight"); - print ' '; - $text = $formproduct->selectMeasuringUnits("weight_units", "weight", GETPOST('weight_units', 'int'), 0, 2); - $htmltext = $langs->trans("KeepEmptyForAutoCalculation"); - print $form->textwithpicto($text, $htmltext); - print '
    '; - print $langs->trans("Width").' x '.$langs->trans("Height").' x '.$langs->trans("Depth"); - print ' '; - print ' x '; - print ' x '; - print ' '; - $text = $formproduct->selectMeasuringUnits("size_units", "size", GETPOST('size_units', 'int'), 0, 2); - $htmltext = $langs->trans("KeepEmptyForAutoCalculation"); - print $form->textwithpicto($text, $htmltext); - print '
    '; + print $langs->trans("Weight"); + print ' '; + $text = $formproduct->selectMeasuringUnits("weight_units", "weight", GETPOST('weight_units', 'int'), 0, 2); + $htmltext = $langs->trans("KeepEmptyForAutoCalculation"); + print $form->textwithpicto($text, $htmltext); + print '
    '; + print $langs->trans("Width").' x '.$langs->trans("Height").' x '.$langs->trans("Depth"); + print ' '; + print ' x '; + print ' x '; + print ' '; + $text = $formproduct->selectMeasuringUnits("size_units", "size", GETPOST('size_units', 'int'), 0, 2); + $htmltext = $langs->trans("KeepEmptyForAutoCalculation"); + print $form->textwithpicto($text, $htmltext); + print '
    ".$langs->trans("DeliveryMethod")."'; - $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); - print "
    ".$langs->trans("DeliveryMethod")."'; + $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); + print "
    ".$langs->trans("TrackingNumber")."'; - print ''; - print "
    ".$langs->trans("TrackingNumber")."'; + print ''; + print "
    '; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); + print ''; + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '
    ".$langs->trans("DefaultModel")."'; - print $form->selectarray('model', $liste, $conf->global->EXPEDITION_ADDON_PDF); - print "
    ".$langs->trans("DefaultModel")."'; + print $form->selectarray('model', $liste, $conf->global->EXPEDITION_ADDON_PDF); + print "
    "; + print ""; - dol_fiche_end(); + dol_fiche_end(); - // Shipment lines + // Shipment lines - $numAsked = count($object->lines); + $numAsked = count($object->lines); - print ''; - print '
    '; + print '
    '; - print ''; + print '
    '; - // Load shipments already done for same order - $object->loadExpeditions(); + // Load shipments already done for same order + $object->loadExpeditions(); - if ($numAsked) - { - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - if (!empty($conf->stock->enabled)) - { + print ''.$langs->trans("Reset").''; + print ''; + if (!empty($conf->stock->enabled)) + { if (empty($conf->productbatch->enabled)) { - print ''; + print ''; } else { print ''; } - } - print "\n"; - } + } + print "\n"; + } - $indiceAsked = 0; - while ($indiceAsked < $numAsked) - { - $product = new Product($db); + $indiceAsked = 0; + while ($indiceAsked < $numAsked) + { + $product = new Product($db); - $line = $object->lines[$indiceAsked]; + $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'); + $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 (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($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; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Product label - 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]); + // Product label + 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]); - print ''; - } else { - print "'; + } else { + print "\n"; - } + // Show range + print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); + print "\n"; + } - // Qty - print ''; - $qtyProdCom = $line->qty; + // Qty + print ''; + $qtyProdCom = $line->qty; - // Qty already shipped - print ''; + // Qty already shipped + print ''; - // Qty to ship - $quantityAsked = $line->qty; + // Qty to ship + $quantityAsked = $line->qty; if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $quantityToBeDelivered = 0; } else { $quantityToBeDelivered = $quantityAsked - $quantityDelivered; } - $warehouse_id = GETPOST('entrepot_id', 'int'); + $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 { - print ''; + print ''; //ship from preselected location $stock = + $product->stock_warehouse[$warehouse_id]->real; // Convert to number $deliverableQty = min($quantityToBeDelivered, $stock); @@ -1195,8 +1200,8 @@ if ($action == 'create') print ''; @@ -1213,13 +1218,13 @@ if ($action == 'create') $tmpentrepot_id = is_numeric(GETPOST($ent, 'int')) ?GETPOST($ent, 'int') : $warehouse_id; if ($line->fk_product > 0) { - print ''; + print ''; - $stockMin = false; - if (empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) { - $stockMin = 0; - } - print $formproduct->selectWarehouses($tmpentrepot_id, 'entl'.$indiceAsked, '', 1, 0, $line->fk_product, '', 1, 0, array(), 'minwidth200', '', 1, $stockMin, 'stock DESC, e.ref'); + $stockMin = false; + if (empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) { + $stockMin = 0; + } + 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) { @@ -1261,7 +1266,7 @@ if ($action == 'create') } } } else { - // Product need lot + // Product need lot print ''; // end line and start a new one for lot/serial print ''; @@ -1273,11 +1278,11 @@ if ($action == 'create') $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) - { - $nbofsuggested++; - } - } + 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)) { @@ -1300,8 +1305,12 @@ if ($action == 'create') $detail = ''; $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"); + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + $detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby, "day"); + } + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + $detail .= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby, "day"); + } $detail .= ' - '.$langs->trans("Qty").': '.$dbatch->qty; $detail .= '
    '; print $detail; @@ -1315,33 +1324,33 @@ if ($action == 'create') print ''; } } else { - print ''; - print ''; + print ''; + print ''; - print ''; + print ''; } } } else { // ship from multiple locations if (empty($conf->productbatch->enabled) || !$product->hasbatch()) { - print ''; - print ''."\n"; // end line and start a new one for each warehouse + print ''; + print ''."\n"; // end line and start a new one for each warehouse print ''; $subj = 0; - // Define nb of lines suggested for this order line + // 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) { - $nbofsuggested++; - } + $nbofsuggested++; + } } $tmpwarehouseObject = new Entrepot($db); foreach ($product->stock_warehouse as $warehouse_id=>$stock_warehouse) // $stock_warehouse is product_stock @@ -1411,8 +1420,8 @@ if ($action == 'create') } } } else { - print ''; - print ''; // end line and start a new one for lot/serial + print ''; + print ''; // end line and start a new one for lot/serial $subj = 0; print ''; @@ -1423,18 +1432,18 @@ if ($action == 'create') $nbofsuggested = 0; 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) + if (($stock_warehouse->real > 0) && (count($stock_warehouse->detail_batch))) { + foreach ($stock_warehouse->detail_batch as $dbatch) { - $nbofsuggested++; + $nbofsuggested++; } - } + } } 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 @@ -1478,34 +1487,34 @@ if ($action == 'create') if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - $disabled = ''; - 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 ' '; + $disabled = ''; + 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 ' '; } else { - print $langs->trans("NA"); + print $langs->trans("NA"); } print ''; print ''; print ''; @@ -1526,28 +1535,28 @@ if ($action == 'create') print $expLine->showOptionals($extrafields, 'edit', array('style'=>'class="drag drop oddeven"', 'colspan'=>$colspan), $indiceAsked, '', 1); } - } + } - $indiceAsked++; - } + $indiceAsked++; + } - print "
    '.$langs->trans("Description").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyShipped").''.$langs->trans("QtyToShip"); + if ($numAsked) + { + print '
    '.$langs->trans("Description").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyShipped").''.$langs->trans("QtyToShip"); if (empty($conf->productbatch->enabled)) { - print '
    ('.$langs->trans("Fill").''; - print ' / '.$langs->trans("Reset").')'; + print '
    '.$langs->trans("Fill").''; + print ' / '; + } else { + print '
    '; } - print '
    '.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' ('.$langs->trans("Stock").')
    '; - print ''; // ancre pour retourner sur la ligne + print ''; + print ''; // ancre pour retourner sur la ligne - // Show product and description - $product_static->type = $line->fk_product_type; - $product_static->id = $line->fk_product; - $product_static->ref = $line->ref; - $product_static->status_batch = $line->product_tobatch; - $text = $product_static->getNomUrl(1); - $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label); - $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc)); - print $form->textwithtooltip($text, $description, 3, '', '', $i); + // Show product and description + $product_static->type = $line->fk_product_type; + $product_static->id = $line->fk_product; + $product_static->ref = $line->ref; + $product_static->status_batch = $line->product_tobatch; + $text = $product_static->getNomUrl(1); + $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label); + $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc)); + print $form->textwithtooltip($text, $description, 3, '', '', $i); - // Show range - print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); + // Show range + 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)) - { - print ($line->desc && $line->desc != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->desc) : ''; - } + // Add description in form + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) + { + print ($line->desc && $line->desc != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->desc) : ''; + } - print '
    "; - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + print '"; + 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, $line->desc, 3, '', '', $i); - } else { - print $text.' '.nl2br($line->desc); - } + if (!empty($line->label)) { + $text .= ' '.$line->label.''; + print $form->textwithtooltip($text, $line->desc, 3, '', '', $i); + } else { + print $text.' '.nl2br($line->desc); + } - // Show range - print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end)); - print "'.$line->qty; - print ''; - print ''.$line->qty; + print ''; + print ''; - $quantityDelivered = $object->expeditions[$line->id]; - print $quantityDelivered; - print ''; - print ''; + $quantityDelivered = $object->expeditions[$line->id]; + print $quantityDelivered; + print ''; + print ''; if ($line->product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { - if (GETPOST('qtyl'.$indiceAsked, 'int')) $deliverableQty = GETPOST('qtyl'.$indiceAsked, 'int'); - print ''; + if (GETPOST('qtyl'.$indiceAsked, 'int')) $deliverableQty = GETPOST('qtyl'.$indiceAsked, 'int'); + print ''; print ''; } else print $langs->trans("NA"); print '
    '; - print ' '; - print '
    '; + print ' '; + print ''; - print img_warning().' '.$langs->trans("NoProductToShipFoundIntoStock", $staticwarehouse->label); - print '
    '; + print img_warning().' '.$langs->trans("NoProductToShipFoundIntoStock", $staticwarehouse->label); + print '
    '; 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 ($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 ''; + } } else { - print $langs->trans("Service"); + print $langs->trans("Service"); } print '
    "; + print ""; - print '
    '; + print '
    '; - print '
    '; - print ''; - print '  '; - print ''; // Cancel for create does not post form if we don't know the backtopage - print '
    '; + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
    '; - print '
    '; + print ''; - print '
    '; - } else { - dol_print_error($db); - } - } + print '
    '; + } else { + dol_print_error($db); + } + } } elseif ($id || $ref) /* *************************************************************************** */ /* */ @@ -1582,26 +1591,26 @@ if ($action == 'create') // Confirm deleteion if ($action == 'delete') { - $formquestion = array(); - if ($object->statut == Expedition::STATUS_CLOSED && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { - $formquestion = array( - array( - 'label' => $langs->trans('ShipmentIncrementStockOnDelete'), - 'name' => 'alsoUpdateStock', - 'type' => 'checkbox', - 'value' => 0 - ), - ); - } - $formconfirm = $form->formconfirm( - $_SERVER['PHP_SELF'].'?id='.$object->id, - $langs->trans('DeleteSending'), - $langs->trans("ConfirmDeleteSending", $object->ref), - 'confirm_delete', - $formquestion, - 0, - 1 - ); + $formquestion = array(); + if ($object->statut == Expedition::STATUS_CLOSED && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) { + $formquestion = array( + array( + 'label' => $langs->trans('ShipmentIncrementStockOnDelete'), + 'name' => 'alsoUpdateStock', + 'type' => 'checkbox', + 'value' => 0 + ), + ); + } + $formconfirm = $form->formconfirm( + $_SERVER['PHP_SELF'].'?id='.$object->id, + $langs->trans('DeleteSending'), + $langs->trans("ConfirmDeleteSending", $object->ref), + 'confirm_delete', + $formquestion, + 0, + 1 + ); } // Confirmation validation @@ -1651,13 +1660,13 @@ if ($action == 'create') if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { - $objectsrc = new Commande($db); - $objectsrc->fetch($object->$typeobject->id); + $objectsrc = new Commande($db); + $objectsrc->fetch($object->$typeobject->id); } if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { - $objectsrc = new Propal($db); - $objectsrc->fetch($object->$typeobject->id); + $objectsrc = new Propal($db); + $objectsrc->fetch($object->$typeobject->id); } // Shipment card @@ -1667,52 +1676,52 @@ if ($action == 'create') $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->expedition->creer, 'string', '', 0, 1); $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->expedition->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - // Project - if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if (0) { // Do not change on shipment - 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 { - // We don't have project on shipment, so we will use the project or source object instead - // TODO Add project on shipment - $morehtmlref .= ' : '; - if (!empty($objectsrc->fk_project)) { - $proj = new Project($db); - $proj->fetch($objectsrc->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + // Project + if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if (0) { // Do not change on shipment + 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 { + // We don't have project on shipment, so we will use the project or source object instead + // TODO Add project on shipment + $morehtmlref .= ' : '; + if (!empty($objectsrc->fk_project)) { + $proj = new Project($db); + $proj->fetch($objectsrc->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } $morehtmlref .= '
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; // Linked documents if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) @@ -1783,7 +1792,7 @@ if ($action == 'create') print ($object->trueWeight && $object->weight_units != '') ? ' '.measuringUnitString(0, "weight", $object->weight_units) : ''; } - // Calculated + // Calculated if ($totalWeight > 0) { if (!empty($object->trueWeight)) print ' ('.$langs->trans("SumOfProductWeights").': '; @@ -1833,15 +1842,15 @@ if ($action == 'create') $volumeUnit = 0; if ($object->trueWidth && $object->trueHeight && $object->trueDepth) { - $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); - $volumeUnit = $object->size_units * 3; + $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) { - 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'); + 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); } if ($totalVolume > 0) @@ -1906,21 +1915,21 @@ if ($action == 'create') if (!empty($conf->incoterm->enabled)) { print ''; - print ''; + print ''; + print ''; } // Other attributes @@ -1950,7 +1959,7 @@ if ($action == 'create') } print '
    '; - print '
    '; + print '
    '; print '
    '; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->expedition->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print '
    '; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->expedition->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + 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); } - print '
    '; print ''; print ''; @@ -2034,43 +2043,43 @@ if ($action == 'create') $alreadysent = array(); 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"; - //if ($conf->livraison_bon->enabled) $sql .= ", l.rowid as livraison_id, l.ref as livraison_ref, l.date_delivery, ld.qty as qty_received"; - $sql .= ', p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.tobatch as product_tobatch'; - $sql .= ', p.description as product_desc'; - $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed"; - $sql .= ", ".MAIN_DB_PREFIX."expedition as e"; - $sql .= ", ".MAIN_DB_PREFIX.$origin."det as obj"; - //if ($conf->livraison_bon->enabled) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."livraison as l ON l.fk_expedition = e.rowid LEFT JOIN ".MAIN_DB_PREFIX."livraisondet as ld ON ld.fk_livraison = l.rowid AND obj.rowid = ld.fk_origin_line"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON obj.fk_product = p.rowid"; - $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; - $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; - $sql .= " ORDER BY obj.fk_product"; + $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"; + //if ($conf->livraison_bon->enabled) $sql .= ", l.rowid as livraison_id, l.ref as livraison_ref, l.date_delivery, ld.qty as qty_received"; + $sql .= ', p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.tobatch as product_tobatch'; + $sql .= ', p.description as product_desc'; + $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed"; + $sql .= ", ".MAIN_DB_PREFIX."expedition as e"; + $sql .= ", ".MAIN_DB_PREFIX.$origin."det as obj"; + //if ($conf->livraison_bon->enabled) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."livraison as l ON l.fk_expedition = e.rowid LEFT JOIN ".MAIN_DB_PREFIX."livraisondet as ld ON ld.fk_livraison = l.rowid AND obj.rowid = ld.fk_origin_line"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON obj.fk_product = p.rowid"; + $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; + $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; + $sql .= " ORDER BY obj.fk_product"; - dol_syslog("get list of shipment lines", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; + dol_syslog("get list of shipment lines", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - 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, 'date_valid'=>$db->jdate($obj->date_valid), 'date_delivery'=>$db->jdate($obj->date_delivery)); - } - $i++; - } - } - //var_dump($alreadysent); + while ($i < $num) + { + $obj = $db->fetch_object($resql); + 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, 'date_valid'=>$db->jdate($obj->date_valid), 'date_delivery'=>$db->jdate($obj->date_delivery)); + } + $i++; + } + } + //var_dump($alreadysent); } print ''; @@ -2083,7 +2092,7 @@ if ($action == 'create') if (empty($reshook)) { - print ''; // id of order line + print ''; // id of order line print ''; // # @@ -2154,35 +2163,35 @@ if ($action == 'create') print ''; // Qty in other shipments (with shipment and warehouse used) - if ($origin && $origin_id > 0) - { - print ''; - } + $j++; + 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) + { + $warehousestatic->fetch($shipmentline_var['warehouse']); + $htmltext .= '
    '.$langs->trans("FromLocation").' : '.$warehousestatic->getNomUrl(1, '', 0, 1); + } + print ' '.$form->textwithpicto('', $htmltext, 1); + } + } + } + print ''; + } if ($action == 'editline' && $lines[$i]->id == $line_id) { @@ -2303,8 +2312,12 @@ if ($action == 'create') foreach ($lines[$i]->detail_batch as $dbatch) // $dbatch is instance of ExpeditionLineBatch { $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"); + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + $detail .= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby, "day"); + } + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + $detail .= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby, "day"); + } $detail .= ' - '.$langs->trans("Qty").': '.$dbatch->qty; $detail .= '
    '; } @@ -2347,7 +2360,7 @@ if ($action == 'create') print 'id.'">'.img_edit().''; print ''; print ''; // Display lines extrafields @@ -2404,13 +2417,13 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook 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 { @@ -2426,7 +2439,7 @@ if ($action == 'create') { print ''.$langs->trans("ClassifyUnbilled").''; } else { - print ''.$langs->trans("ReOpen").''; + print ''.$langs->trans("ReOpen").''; } } @@ -2467,8 +2480,8 @@ if ($action == 'create') // 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 ? { - $label = "ClassifyBilled"; - $paramaction = 'classifybilled'; + $label = "ClassifyBilled"; + $paramaction = 'classifybilled'; } print ''.$langs->trans($label).''; } @@ -2477,16 +2490,16 @@ if ($action == 'create') // Cancel if ($object->statut == Expedition::STATUS_VALIDATED) { - if ($user->rights->expedition->supprimer) - { - print ''.$langs->trans("Cancel").''; - } + if ($user->rights->expedition->supprimer) + { + print ''.$langs->trans("Cancel").''; + } } // Delete if ($user->rights->expedition->supprimer) { - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; } } @@ -2500,9 +2513,9 @@ if ($action == 'create') if ($action != 'presend' && $action != 'editline') { - print '
    '; + print '
    '; - $objectref = dol_sanitizeFileName($object->ref); + $objectref = dol_sanitizeFileName($object->ref); $filedir = $conf->expedition->dir_output."/sending/".$objectref; $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; @@ -2510,7 +2523,7 @@ if ($action == 'create') $genallowed = $user->rights->expedition->lire; $delallowed = $user->rights->expedition->creer; - print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements diff --git a/htdocs/expedition/class/api_shipments.class.php b/htdocs/expedition/class/api_shipments.class.php index 7bc4db0a511..1f85ade883b 100644 --- a/htdocs/expedition/class/api_shipments.class.php +++ b/htdocs/expedition/class/api_shipments.class.php @@ -138,7 +138,7 @@ class Shipments extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -146,28 +146,28 @@ class Shipments extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; while ($i < $min) { - $obj = $db->fetch_object($result); - $shipment_static = new Expedition($db); + $obj = $this->db->fetch_object($result); + $shipment_static = new Expedition($this->db); if ($shipment_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($shipment_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve commande list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No shipment found'); diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index e6dbf827fce..bdf79081fe2 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -3,7 +3,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2006-2012 Laurent Destailleur - * Copyright (C) 2011-2017 Juanjo Menent + * Copyright (C) 2011-2020 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2014-2015 Marcos García @@ -11,7 +11,7 @@ * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2018 Nicolas ZABOURI - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2020 Frédéric France * Copyright (C) 2020 Lenin Rivas * * This program is free software; you can redistribute it and/or modify @@ -36,6 +36,7 @@ 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'; @@ -46,6 +47,8 @@ if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/exped */ class Expedition extends CommonObject { + use CommonIncoterm; + /** * @var string ID to identify managed object */ @@ -79,6 +82,13 @@ class Expedition extends CommonObject public $socid; + /** + * @var string Customer ref + * @deprecated + * @see $ref_customer + */ + public $ref_client; + /** * @var string Customer ref */ @@ -570,6 +580,7 @@ class Expedition extends CommonObject $this->date_shipping = $this->db->jdate($obj->date_expedition); // Date real $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed $this->fk_delivery_address = $obj->fk_address; + $this->model_pdf = $obj->model_pdf; $this->modelpdf = $obj->model_pdf; $this->shipping_method_id = $obj->fk_shipping_method; $this->shipping_method = $obj->shipping_method; @@ -698,7 +709,7 @@ class Expedition extends CommonObject // Validate $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; - $sql .= " ref='".$numref."'"; + $sql .= " ref='".$this->db->escape($numref)."'"; $sql .= ", fk_statut = 1"; $sql .= ", date_valid = '".$this->db->idate($now)."'"; $sql .= ", fk_user_valid = ".$user->id; @@ -1066,7 +1077,7 @@ class Expedition extends CommonObject if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight); 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->modelpdf)) $this->modelpdf = trim($this->modelpdf); + if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); @@ -1507,6 +1518,9 @@ class Expedition extends CommonObject { $this->db->commit(); + // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive + $this->deleteEcmFiles(); + // We delete PDFs $ref = dol_sanitizeFileName($this->ref); if (!empty($conf->expedition->dir_output)) diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php index c20e2bb4088..69c5080ea83 100644 --- a/htdocs/expedition/contact.php +++ b/htdocs/expedition/contact.php @@ -39,7 +39,7 @@ $langs->loadLangs(array('orders', 'sendings', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/expedition/index.php b/htdocs/expedition/index.php index 849e2054cd6..6f21683cc69 100644 --- a/htdocs/expedition/index.php +++ b/htdocs/expedition/index.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2020 Tobias Sekan * * 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 @@ -84,7 +85,7 @@ if (!$user->rights->societe->client->voir && !$socid) $sql .= $clause." sc.fk_user = ".$user->id; $clause = " AND "; } -$sql .= $clause." e.fk_statut = 0"; +$sql .= $clause." e.fk_statut = ".Expedition::STATUS_DRAFT; $sql .= " AND e.entity IN (".getEntity('expedition').")"; if ($socid) $sql .= " AND c.fk_soc = ".$socid; @@ -96,7 +97,13 @@ if ($resql) print '
    '; print '
    '.$lines[$i]->qty_asked.''; - 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" + if ($origin && $origin_id > 0) + { + print ''; + 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" - $j++; - 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) - { - $warehousestatic->fetch($shipmentline_var['warehouse']); - $htmltext .= '
    '.$langs->trans("FromLocation").' : '.$warehousestatic->getNomUrl(1, '', 0, 1); - } - print ' '.$form->textwithpicto('', $htmltext, 1); - } - } - } - print '
    '; - print 'id.'">'.img_delete().''; + print 'id.'">'.img_delete().''; print '
    '; print ''; - print ''; + print ''; + print ''; if ($num) { @@ -156,13 +163,21 @@ $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); + + print '
    '; + print '
    '.$langs->trans("SendingsToValidate").'
    '; + print $langs->trans("SendingsToValidate").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; + print ''; + print ''; + print ''; + if ($num) { $i = 0; - print '
    '; - print '
    '; + print $langs->trans("LastSendings").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; - print ''; - print ''; while ($i < $num) { $obj = $db->fetch_object($resql); @@ -189,8 +204,10 @@ if ($resql) print ''; $i++; } - print "
    '.$langs->trans("LastSendings", $num).'

    "; + } else { + print ''.$langs->trans("None").''; } + print "

    "; $db->free($resql); } else dol_print_error($db); @@ -214,13 +231,21 @@ if ($resql) $langs->load("orders"); $num = $db->num_rows($resql); + + print '
    '; + print ''; + + print ''; + print ''; + print ''; + if ($num) { $i = 0; - print '
    '; - print '
    '.$langs->trans("OrdersToProcess").' '; + print ''; + print ''.$num.''; + print ''; + print '
    '; - print ''; - print ''; while ($i < $num && $i < 10) { $obj = $db->fetch_object($resql); @@ -254,9 +279,11 @@ if ($resql) print ''; print ''; } - - print "
    '.$langs->trans("OrdersToProcess").' '.$num.'

    "; + } else { + print ''.$langs->trans("None").''; } + + print "

    "; } else dol_print_error($db); diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index 74efaaeb27a..37bee98d73f 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -59,7 +59,7 @@ $search_company = GETPOST("search_company", 'alpha'); $search_tracking = GETPOST("search_tracking", 'alpha'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); -$search_state = trim(GETPOST("search_state")); +$search_state = GETPOST("search_state"); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_billed = GETPOST("search_billed", 'int'); @@ -71,13 +71,13 @@ $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', $socid = GETPOST('socid', 'int'); $search_user = GETPOST('search_user', 'int'); $search_sale = GETPOST('search_sale', 'int'); -$search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); +$search_categ_cus = GETPOST("search_categ_cus", 'int'); $search_product_category = GETPOST('search_product_category', 'int'); $optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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"; @@ -359,11 +359,11 @@ if ($resql) if (in_array($massaction, array('presend'))) $arrayofmassactions = array(); $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton = ''; - if ($user->rights->expedition->creer) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewSending'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expedition/card.php?action=create2'); - } + // 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); $i = 0; print '
    '."\n"; @@ -408,7 +408,7 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($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 .= '
    '; @@ -417,7 +417,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)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; @@ -800,7 +800,7 @@ if ($resql) } $db->free($resql); - $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $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; diff --git a/htdocs/expedition/note.php b/htdocs/expedition/note.php index 3c029463e16..199782398a6 100644 --- a/htdocs/expedition/note.php +++ b/htdocs/expedition/note.php @@ -37,7 +37,7 @@ $langs->loadLangs(array('sendings', 'companies', 'bills', 'deliveries', 'orders' $id = (GETPOST('id', 'int') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check $socid = ''; @@ -115,7 +115,7 @@ if ($id > 0 || !empty($ref)) // $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= ''; $morehtmlref .= ''; - $morehtmlref .= ''; + $morehtmlref .= ''; $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref .= ''; $morehtmlref .= ''; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index f494ef563fb..152dee7cd36 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -46,7 +46,7 @@ $langs->loadLangs(array('orders', "companies", "bills", 'propal', 'deliveries', $id = GETPOST('id', 'int'); // id of order $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $hookmanager->initHooks(array('ordershipmentcard')); @@ -190,7 +190,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) diff --git a/htdocs/expedition/stats/index.php b/htdocs/expedition/stats/index.php index fcccb545a33..9521cd46d10 100644 --- a/htdocs/expedition/stats/index.php +++ b/htdocs/expedition/stats/index.php @@ -269,8 +269,12 @@ foreach ($data as $val) print ''; print ''; - if ($year) print ''.$year.''; - else print $langs->trans("ValidationDateNotDefinedEvenIfShipmentValidated"); + if ($year) { + print ''.$year.''; + } else { + // Technical error that should not happen + print 'Error: validation date of shipment is not defined. This looks strange because shipment is validated. Try to run /install/repair.php?standard=confirmed'; + } print ''; print ''.$val['nb'].''; /*print ''.price(price2num($val['total'],'MT'),1).''; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index f5348bb4261..2e826cb4080 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2019 Laurent Destailleur + * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015-2017 Alexandre Spangaro * Copyright (C) 2017 Ferran Marcet @@ -27,10 +27,11 @@ */ require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formexpensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -60,7 +61,7 @@ $date = dol_mktime(0, 0, 0, GETPOST('datemonth', 'int'), GETPOST('dateday', 'int $fk_project = GETPOST('fk_project', 'int'); $vatrate = GETPOST('vatrate', 'alpha'); $ref = GETPOST("ref", 'alpha'); -$comments = GETPOST('comments', 'none'); +$comments = GETPOST('comments', 'restricthtml'); $fk_c_type_fees = GETPOST('fk_c_type_fees', 'int'); $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('socid_id', 'int'); @@ -115,14 +116,14 @@ $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object- 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) - { - accessforbidden(); - } + // 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) + { + accessforbidden(); + } } @@ -145,243 +146,243 @@ if (empty($reshook)) } $action = ''; - $fk_project = ''; - $date_start = ''; - $date_end = ''; - $date = ''; - $comments = ''; - $vatrate = ''; - $value_unit_ht = ''; - $value_unit = ''; - $qty = 1; - $fk_c_type_fees = -1; + $fk_project = ''; + $date_start = ''; + $date_end = ''; + $date = ''; + $comments = ''; + $vatrate = ''; + $value_unit_ht = ''; + $value_unit = ''; + $qty = 1; + $fk_c_type_fees = -1; } 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 ($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 + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + 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')) - { - setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); - } else { - 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; + // Action clone object + 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) + { + // 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) - { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $object = $orig; - $action = ''; - } - } - } - } + $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int')); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $object = $orig; + $action = ''; + } + } + } + } - 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) - { - header("Location: index.php"); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + 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) + { + header("Location: index.php"); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == 'add' && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); + if ($action == 'add' && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); - $object->date_debut = $date_start; - $object->date_fin = $date_end; + $object->date_debut = $date_start; + $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; + $object->fk_user_author = GETPOST('fk_user_author', 'int'); + if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id; - $fuser = new User($db); - $fuser->fetch($object->fk_user_author); + $fuser = new User($db); + $fuser->fetch($object->fk_user_author); - $object->fk_statut = 1; - $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); - $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); - // Fill array 'array_options' with data from add form - if (!$error) - { - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - } + $object->status = 1; + $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); + $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); + $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) + { + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) $error++; + } - 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 && 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) - { - $db->begin(); + if (!$error) + { + $db->begin(); - $id = $object->create($user); - if ($id <= 0) - { - $error++; - } + $id = $object->create($user); + if ($id <= 0) + { + $error++; + } - if (!$error) - { - $db->commit(); - Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - $action = 'create'; - } - } - } + if (!$error) + { + $db->commit(); + Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + $action = 'create'; + } + } + } - if ($action == 'update' && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'update' && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $object->date_debut = $date_start; - $object->date_fin = $date_end; + $object->date_debut = $date_start; + $object->date_fin = $date_end; - if ($object->fk_statut < 3) - { - $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); - } + if ($object->status < 3) + { + $object->fk_user_validator = GETPOST('fk_user_validator', 'int'); + } - $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); - $object->fk_user_modif = $user->id; + $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int'); + $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->fk_user_modif = $user->id; - $result = $object->update($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->update($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".GETPOST('id', 'int')); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == 'update_extras') - { - $object->oldcopy = dol_clone($object); + 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', 'none')); - if ($ret < 0) $error++; + // Fill array 'array_options' with data from update form + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); + if ($ret < 0) $error++; - if (!$error) - { - // Actions on extra fields - $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); + if (!$error) + { + // Actions on extra fields + $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } + } - if ($error) - $action = 'edit_extras'; - } + if ($error) + $action = 'edit_extras'; + } - if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) - { - $error = 0; + if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer) + { + $error = 0; - $db->begin(); + $db->begin(); - $object = new ExpenseReport($db); - $object->fetch($id); + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->setValidate($user); + $result = $object->setValidate($user); - if ($result >= 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result >= 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } - if (!$error && $result > 0 && $object->fk_user_validator > 0) - { - $langs->load("mails"); + if (!$error && $result > 0 && $object->fk_user_validator > 0) + { + $langs->load("mails"); - // 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; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_author); + $emailFrom = $expediteur->email; - if ($emailTo && $emailFrom) - { - $filename = array(); $filedir = array(); $mimetype = array(); + 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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link); + $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link); - // Rebuild pdf - /* + // Rebuild pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$id,'',"",$langs); @@ -392,38 +393,38 @@ if (empty($reshook)) array_push($mimetype,"application/pdf"); */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $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'); - } 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 = ''; - } - } + if ($mailfile) + { + // SEND + $result = $mailfile->sendfile(); + 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) + { + $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 = ''; + } + } if (!$error) { @@ -433,37 +434,37 @@ if (empty($reshook)) } else { $db->rollback(); } - } + } - 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 ($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) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail // TO $destinataire = new User($db); @@ -477,19 +478,19 @@ if (empty($reshook)) if ($emailFrom && $emailTo) { - $filename = array(); $filedir = array(); $mimetype = array(); + $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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; $dateRefusEx = explode(" ", $object->date_refuse); - $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); // Rebuild pdf /* @@ -507,75 +508,75 @@ if (empty($reshook)) */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $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 { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + 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($object->error, $object->errors, 'errors'); + } + } - // Approve - if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { - $object = new ExpenseReport($db); - $object->fetch($id); + // 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); + $result = $object->setApproved($user); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + if ($result > 0) + { + // Send mail // TO $destinataire = new User($db); @@ -584,7 +585,7 @@ if (empty($reshook)) // CC $emailCC = $conf->global->NDF_CC_EMAILS; - if (empty($emailTo)) $emailTo = $emailCC; + if (empty($emailTo)) $emailTo = $emailCC; // FROM $expediteur = new User($db); @@ -593,21 +594,21 @@ if (empty($reshook)) if ($emailFrom && $emailTo) { - $filename = array(); $filedir = array(); $mimetype = array(); + $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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved"); + $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); @@ -621,103 +622,103 @@ if (empty($reshook)) } */ - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + $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 = ''; - } + 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("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); + $action = ''; + } + } else { setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings'); $action = ''; } } - if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve) - { - $object = new ExpenseReport($db); - $object->fetch($id); + 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); + $result = $object->setDeny($user, $detailRefuse); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + 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; - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_refuse); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_refuse); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + 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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused"); + $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); + $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); @@ -731,111 +732,111 @@ if (empty($reshook)) } */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $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 { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings'); - $action = ''; - } - } + 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("FailedtoSetToDeny"), null, 'warnings'); + $action = ''; + } + } - //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')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors'); - } else { - $object = new ExpenseReport($db); - $object->fetch($id); + //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')) + { + 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); + $result = $object->set_cancel($user, $detailCancel); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + 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; - // FROM - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_cancel); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_cancel); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + 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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link); + $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link); - // Rebuilt pdf - /* + // Rebuilt pdf + /* $object->setDocModel($user,""); $resultPDF = expensereport_pdf_create($db,$object,'',"",$langs); @@ -849,318 +850,318 @@ if (empty($reshook)) } */ - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $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 { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + 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("FailedToSetToCancel"), null, 'warnings'); + $action = ''; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } - 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) - { - $result = $object->setStatut(0); + 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) + { + $result = $object->setStatut(0); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - setEventMessages("NOT_AUTHOR", '', 'errors'); - } - } + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + setEventMessages("NOT_AUTHOR", '', 'errors'); + } + } - if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_unpaid($user); + $result = $object->set_unpaid($user); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + } - if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_unpaid($user); + $result = $object->set_unpaid($user); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + } - if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $result = $object->set_paid($id, $user); + $result = $object->set_paid($id, $user); - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - if ($result > 0) - { - // Send mail + 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; - // FROM - $expediteur = new User($db); - $expediteur->fetch($user->id); - $emailFrom = $expediteur->email; + // FROM + $expediteur = new User($db); + $expediteur->fetch($user->id); + $emailFrom = $expediteur->email; - if ($emailFrom && $emailTo) - { - $filename = array(); $filedir = array(); $mimetype = array(); + 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; + // SUBJECT + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid"); + $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid"); - // CONTENT - $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; + // CONTENT + $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; $link = ''.$link.''; - $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); + $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); - // Generate pdf before attachment - $object->setDocModel($user, ""); - $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs); + // Generate pdf before attachment + $object->setDocModel($user, ""); + $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs); - // PREPARE SEND - $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1); + // PREPARE SEND + $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 { - setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings'); - $action = ''; - } - } else { - setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings'); - $action = ''; - } - } + 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("FailedToSetPaid"), null, 'warnings'); + $action = ''; + } + } - if ($action == "addline" && $user->rights->expensereport->creer) - { - $error = 0; + if ($action == "addline" && $user->rights->expensereport->creer) + { + $error = 0; - // First save uploaded file - $fk_ecm_files = 0; - if (GETPOSTISSET('attachfile')) - { - $arrayoffiles = GETPOST('attachfile', 'array'); - 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); - $ecmfiles->fetch(0, '', $relativepath); - $fk_ecm_files = $ecmfiles->id; - } - } + // First save uploaded file + $fk_ecm_files = 0; + if (GETPOSTISSET('attachfile')) + { + $arrayoffiles = GETPOST('attachfile', 'array'); + 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); + $ecmfiles->fetch(0, '', $relativepath); + $fk_ecm_files = $ecmfiles->id; + } + } // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. - if (empty($vatrate)) $vatrate = "0.000"; - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); + 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)) { - $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); + $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; + $qty = GETPOST('qty', 'int'); + if (empty($qty)) $qty = 1; - if (!($fk_c_type_fees > 0)) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $action = ''; - } + if (!($fk_c_type_fees > 0)) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $action = ''; + } - if ((int) $tmpvat < 0 || $tmpvat == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors'); - $action = ''; - } + 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 == "--") - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - } - // Si aucun prix n'est rentré - 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))) - { - $langs->load("errors"); - setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); - } + // Si aucune date n'est rentrée + if (empty($date) || $date == "--") + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + } + // Si aucun prix n'est rentré + 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))) + { + $langs->load("errors"); + setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); + } - 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 + 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); + $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) { $ret = $object->fetch($object->id); // Reload to get new records @@ -1176,7 +1177,7 @@ if (empty($reshook)) $outputlangs->setDefaultLang($newlang); } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } unset($qty); @@ -1191,159 +1192,159 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } + } - $action = ''; - } + $action = ''; + } - if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer) + { + $object = new ExpenseReport($db); + $object->fetch($id); - $object_ligne = new ExpenseReportLine($db); - $object_ligne->fetch(GETPOST("rowid", 'int')); - $total_ht = $object_ligne->total_ht; - $total_tva = $object_ligne->total_tva; + $object_ligne = new ExpenseReportLine($db); + $object_ligne->fetch(GETPOST("rowid", 'int')); + $total_ht = $object_ligne->total_ht; + $total_tva = $object_ligne->total_tva; - $result = $object->deleteline(GETPOST("rowid", 'int'), $user); - if ($result >= 0) - { - if ($result > 0) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + $result = $object->deleteline(GETPOST("rowid", 'int'), $user); + if ($result >= 0) + { + if ($result > 0) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva); - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($action == "updateline" && $user->rights->expensereport->creer) - { - $object = new ExpenseReport($db); - $object->fetch($id); + 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')) - { - $arrayoffiles = GETPOST('attachfile', 'array'); - 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); - $ecmfiles->fetch(0, '', $relativepath); - $fk_ecm_files = $ecmfiles->id; - } - } + // First save uploaded file + $fk_ecm_files = 0; + if (GETPOSTISSET('attachfile')) + { + $arrayoffiles = GETPOST('attachfile', 'array'); + 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); + $ecmfiles->fetch(0, '', $relativepath); + $fk_ecm_files = $ecmfiles->id; + } + } - $rowid = $_POST['rowid']; - $type_fees_id = GETPOST('fk_c_type_fees', 'int'); + $rowid = $_POST['rowid']; + $type_fees_id = GETPOST('fk_c_type_fees', 'int'); $fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int'); - $projet_id = $fk_project; - $comments = GETPOST('comments', 'none'); - $qty = GETPOST('qty', 'int'); - $vatrate = GETPOST('vatrate', 'alpha'); + $projet_id = $fk_project; + $comments = GETPOST('comments', 'restricthtml'); + $qty = GETPOST('qty', 'int'); + $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"; - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate)); + // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary. + 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)) - { - $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); - } + $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU'); + $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU'); + if (empty($value_unit)) + { + $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU'); + } - if (!GETPOST('fk_c_type_fees', 'int') > 0) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $action = ''; - } - if ((int) $tmpvat < 0 || $tmpvat == '') - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors'); - $action = ''; - } - // Warning if date out of range + if (!GETPOST('fk_c_type_fees', 'int') > 0) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $action = ''; + } + 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))) - { - $langs->load("errors"); - setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); - } + { + $langs->load("errors"); + setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings'); + } - 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) - { - // 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 = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + 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) + { + // 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 = $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 - $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } - $result = $object->recalculer($id); + $result = $object->recalculer($id); - //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - //exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + //exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } // Actions when printing a doc from card - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - // Actions to send emails - $triggersendname = 'EXPENSEREPORT_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO'; - $trackid = 'exp'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $triggersendname = 'EXPENSEREPORT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO'; + $trackid = 'exp'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Actions to build doc - $upload_dir = $conf->expensereport->dir_output; - $permissiontoadd = $user->rights->expensereport->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->expensereport->dir_output; + $permissiontoadd = $user->rights->expensereport->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -1362,6 +1363,7 @@ $projecttmp = new Project($db); $paymentexpensereportstatic = new PaymentExpenseReport($db); $bankaccountstatic = new Account($db); $ecmfilesstatic = new EcmFiles($db); +$formexpensereport = new FormExpenseReport($db); // Create if ($action == 'create') @@ -1399,8 +1401,8 @@ if ($action == 'create') print ''; $defaultselectuser = $user->id; 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(); + $include_users = 'hierarchyme'; + 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 ''; @@ -1414,11 +1416,11 @@ if ($action == 'create') $include_users = $object->fetch_users_approver_expensereport(); 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'); - $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")); + $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'); + $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")); } print ''; print ''; @@ -1457,9 +1459,9 @@ if ($action == 'create') // Other attributes $parameters = array('colspan' => ' colspan="3"', 'cols' => 3); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook)) { - print $object->showOptionals($extrafields, 'edit', $parameters); + print $object->showOptionals($extrafields, 'edit', $parameters); } print ''; @@ -1485,7 +1487,7 @@ if ($action == 'create') 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'); @@ -1494,8 +1496,8 @@ if ($action == 'create') print '
    '; // End of page - llxFooter(); - $db->close(); + llxFooter(); + $db->close(); exit; } @@ -1503,7 +1505,7 @@ if ($action == 'create') $head = expensereport_prepare_head($object); - if ($action == 'edit' && ($object->fk_statut < 3 || $object->fk_statut == 99)) + if ($action == 'edit' && ($object->status < 3 || $object->status == 99)) { print "
    \n"; print ''; @@ -1511,7 +1513,7 @@ if ($action == 'create') dol_fiche_head($head, 'card', $langs->trans("ExpenseReport"), 0, 'trip'); - if ($object->fk_statut == 99) + if ($object->status == 99) { print ''; } else { @@ -1528,15 +1530,15 @@ if ($action == 'create') $userfee = new User($db); if ($object->fk_user_author > 0) { - $userfee->fetch($object->fk_user_author); - print $userfee->getNomUrl(-1); + $userfee->fetch($object->fk_user_author); + print $userfee->getNomUrl(-1); } print ''; - // Ref - print ''.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); - print ''; + // Ref + print ''.$langs->trans("Ref").''; + print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); + print ''; print ''; print ''.$langs->trans("DateStart").''; @@ -1561,7 +1563,7 @@ if ($action == 'create') print ''; } - if ($object->fk_statut < 3) + if ($object->status < 3) { print ''; print ''.$langs->trans("VALIDATOR").''; // Approbator @@ -1581,7 +1583,7 @@ if ($action == 'create') print ''; } - if ($object->fk_statut == 6) + if ($object->status == 6) { print ''; print ''.$langs->trans("AUTHORPAIEMENT").''; @@ -1611,15 +1613,15 @@ if ($action == 'create') // Clone confirmation if ($action == 'clone') { - // Create an array for form - $criteriaforfilter = 'hierarchyme'; - 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)) - ); - // Paiement incomplet. On demande si motif = escompte ou autre - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + // Create an array for form + $criteriaforfilter = 'hierarchyme'; + 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')) + ); + // Paiement incomplet. On demande si motif = escompte ou autre + $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') @@ -1655,7 +1657,7 @@ if ($action == 'create') if ($action == 'setdraft') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1); } if ($action == 'refuse') // Deny @@ -1730,10 +1732,10 @@ if ($action == 'create') print ''; 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); + $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); } print ''; @@ -1761,7 +1763,7 @@ if ($action == 'create') print ''; // User to inform for approval - if ($object->fk_statut <= ExpenseReport::STATUS_VALIDATED) // informed + if ($object->status <= ExpenseReport::STATUS_VALIDATED) // informed { print ''; print ''.$langs->trans("VALIDATOR").''; // approver @@ -1773,12 +1775,12 @@ if ($action == 'create') 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)); + $langs->load("errors"); + print img_warning($langs->trans("ErrorBadEMail", $userfee->email)); } } print ''; - } elseif ($object->fk_statut == ExpenseReport::STATUS_CANCELED) + } elseif ($object->status == ExpenseReport::STATUS_CANCELED) { print ''; print ''.$langs->trans("CANCEL_USER").''; @@ -1817,7 +1819,7 @@ if ($action == 'create') print ''; } - if ($object->fk_statut == 99 || !empty($object->detail_refuse)) + if ($object->status == 99 || !empty($object->detail_refuse)) { print ''; print ''.$langs->trans("REFUSEUR").''; @@ -1835,7 +1837,7 @@ if ($action == 'create') print ''; } - if ($object->fk_statut == 6) + if ($object->status == $object::STATUS_CLOSED) { /* TODO this fields are not yet filled print ''; @@ -1870,11 +1872,11 @@ if ($action == 'create') print ''.$langs->trans("AmountHT").''; print ''.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).''; $rowspan = 5; - if ($object->fk_statut <= ExpenseReport::STATUS_VALIDATED) $rowspan++; - elseif ($object->fk_statut == ExpenseReport::STATUS_CANCELED) $rowspan += 2; + if ($object->status <= ExpenseReport::STATUS_VALIDATED) $rowspan++; + elseif ($object->status == ExpenseReport::STATUS_CANCELED) $rowspan += 2; else $rowspan += 2; - if ($object->fk_statut == ExpenseReport::STATUS_REFUSED || !empty($object->detail_refuse)) $rowspan += 2; - if ($object->fk_statut == ExpenseReport::STATUS_CLOSED) $rowspan += 2; + if ($object->status == ExpenseReport::STATUS_REFUSED || !empty($object->detail_refuse)) $rowspan += 2; + if ($object->status == ExpenseReport::STATUS_CLOSED) $rowspan += 2; print ""; print ''; @@ -1924,26 +1926,25 @@ if ($action == 'create') $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; $totalpaid = 0; - while ($i < $num) - { - $objp = $db->fetch_object($resql); + $num = $db->num_rows($resql); + $i = 0; $totalpaid = 0; + while ($i < $num) + { + $objp = $db->fetch_object($resql); - $paymentexpensereportstatic->id = $objp->rowid; - $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp); - $paymentexpensereportstatic->ref = $objp->rowid; - $paymentexpensereportstatic->num_paiement = $objp->num_payment; - $paymentexpensereportstatic->num_payment = $objp->num_payment; - $paymentexpensereportstatic->payment_code = $objp->payment_code; + $paymentexpensereportstatic->id = $objp->rowid; + $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp); + $paymentexpensereportstatic->ref = $objp->rowid; + $paymentexpensereportstatic->num_payment = $objp->num_payment; + $paymentexpensereportstatic->payment_code = $objp->payment_code; - print ''; - print ''; + print ''; + print ''; print $paymentexpensereportstatic->getNomUrl(1); print ''; - 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"; + 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)) { $bankaccountstatic->id = $objp->baid; @@ -1964,39 +1965,39 @@ if ($action == 'create') print $bankaccountstatic->getNomUrl(1, 'transactions'); print ''; } - print ''.price($objp->amount).""; - print ''; - print ""; - $totalpaid += $objp->amount; - $i++; - } + print ''.price($objp->amount).""; + print ''; + print ""; + $totalpaid += $objp->amount; + $i++; + } if (!is_null($totalpaid)) { - $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop + $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop } - $remaintopay = price2num($object->total_ttc - $totalpaid); - $resteapayeraffiche = $remaintopay; + $remaintopay = price2num($object->total_ttc - $totalpaid); + $resteapayeraffiche = $remaintopay; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - if ($object->status == ExpenseReport::STATUS_REFUSED) - { - $cssforamountpaymentcomplete = 'amountpaymentneutral'; - $resteapayeraffiche = 0; - } elseif ($object->paid == 0) - { - $cssforamountpaymentcomplete = 'amountpaymentneutral'; - } - print ''.$langs->trans("AlreadyPaid").':'.price($totalpaid).''; - print ''.$langs->trans("AmountExpected").':'.price($object->total_ttc).''; + if ($object->status == ExpenseReport::STATUS_REFUSED) + { + $cssforamountpaymentcomplete = 'amountpaymentneutral'; + $resteapayeraffiche = 0; + } elseif ($object->paid == 0) + { + $cssforamountpaymentcomplete = 'amountpaymentneutral'; + } + print ''.$langs->trans("AlreadyPaid").':'.price($totalpaid).''; + print ''.$langs->trans("AmountExpected").':'.price($object->total_ttc).''; - print ''.$langs->trans("RemainderToPay").':'; - print ''.price($resteapayeraffiche).''; + print ''.$langs->trans("RemainderToPay").':'; + print ''.price($resteapayeraffiche).''; - $db->free($resql); + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } print ""; @@ -2009,7 +2010,7 @@ if ($action == 'create') print '
    '; $actiontouse = 'updateline'; - if (($object->fk_statut == 0 || $object->fk_statut == 99) && $action != 'editline') $actiontouse = 'addline'; + if (($object->status == 0 || $object->status == 99) && $action != 'editline') $actiontouse = 'addline'; print ''; print ''; @@ -2029,8 +2030,8 @@ if ($action == 'create') //print ''.$langs->trans('Piece').''; print ''.$langs->trans('Date').''; if (!empty($conf->projet->enabled)) print ''.$langs->trans('Project').''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; print ''.$langs->trans('Type').''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; print ''.$langs->trans('Description').''; print ''.$langs->trans('VAT').''; print ''.$langs->trans('PriceUHT').''; @@ -2041,11 +2042,11 @@ if ($action == 'create') print ''.$langs->trans('AmountHT').''; print ''.$langs->trans('AmountTTC').''; } - // Picture + // Picture print ''; print ''; // Ajout des boutons de modification/suppression - if (($object->fk_statut < 2 || $object->fk_statut == 99) && $user->rights->expensereport->creer) + if (($object->status < 2 || $object->status == 99) && $user->rights->expensereport->creer) { print ''; } @@ -2080,6 +2081,13 @@ if ($action == 'create') } print ''; } + + // Type of fee + print ''; + $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code)); + print $labeltype; + print ''; + // IK if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { @@ -2087,24 +2095,20 @@ if ($action == 'create') print dol_getIdFromCode($db, $line->fk_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label'); print ''; } - // Type of fee - print ''; - $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code)); - print $labeltype; - print ''; + // Comment print ''.dol_nl2br($line->comments).''; // VAT rate print ''.vatrate($line->vatrate, true).''; - // Unit price HT + // Unit price HT print ''; if (!empty($line->value_unit_ht)) { - print price($line->value_unit_ht); + print price($line->value_unit_ht); } else { - $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate)); - $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU'); - print $pricenettoshow; + $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate)); + $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU'); + print $pricenettoshow; } print ''; @@ -2122,83 +2126,83 @@ if ($action == 'create') print ''; if ($line->fk_ecm_files > 0) { - $modulepart = 'expensereport'; - $maxheightmini = 32; + $modulepart = 'expensereport'; + $maxheightmini = 32; - $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { - $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath); - $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename); - 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 - //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)) { - $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); - print ''; - } else { - print ''; - } - print ''; - print ''; - } else { - $modulepart = 'expensereport'; - $thumbshown = 0; - 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'; + $result = $ecmfilesstatic->fetch($line->fk_ecm_files); + if ($result > 0) + { + $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath); + $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename); + 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 + //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)) { + $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); + print ''; + } else { + print ''; + } + print ''; + print ''; + } else { + $modulepart = 'expensereport'; + $thumbshown = 0; + 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) - { - // 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. - { - 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++; - } - } - } + $pdfexists = file_exists($filepdf); + 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. + { + 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 ($pdfexists && !$error) - { - $heightforphotref = 70; - if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; - // If the preview file is found - if (file_exists($fileimage)) - { - $thumbshown = 1; - print ''; - } - } - } + if ($pdfexists && !$error) + { + $heightforphotref = 70; + if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; + // If the preview file is found + if (file_exists($fileimage)) + { + $thumbshown = 1; + print ''; + } + } + } - if (!$thumbshown) - { - print img_mime($ecmfilesstatic->filename); - } - } - } + if (!$thumbshown) + { + print img_mime($ecmfilesstatic->filename); + } + } + } } print ''; // Ajout des boutons de modification/suppression - if (($object->fk_statut < ExpenseReport::STATUS_VALIDATED || $object->fk_statut == ExpenseReport::STATUS_REFUSED) && $user->rights->expensereport->creer) + if (($object->status < ExpenseReport::STATUS_VALIDATED || $object->status == ExpenseReport::STATUS_REFUSED) && $user->rights->expensereport->creer) { print ''; - print 'rowid.'">'; + print 'rowid.'">'; print img_edit(); print '   '; - print 'rowid.'">'; + print 'rowid.'">'; print img_delete(); print ''; @@ -2210,30 +2214,30 @@ if ($action == 'create') 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++; + // 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++; - print ''; + print ''; - print ''; - print $numline; - print ''; + print ''; + print $numline; + print ''; - print ''; - 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)) - { - print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); - print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - } + print ''; + 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)) + { + print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); + print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + } - print ''."\n"; - print ''; + print ''."\n"; + print ''; - $filenamelinked = ''; - if ($line->fk_ecm_files > 0) - { - $result = $ecmfilesstatic->fetch($line->fk_ecm_files); - if ($result > 0) - { - $filenamelinked = $ecmfilesstatic->filename; - } - } + $filenamelinked = ''; + if ($line->fk_ecm_files > 0) + { + $result = $ecmfilesstatic->fetch($line->fk_ecm_files); + if ($result > 0) + { + $filenamelinked = $ecmfilesstatic->filename; + } + } - $tredited = 'tredited'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; + $tredited = 'tredited'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; print ''; @@ -2285,6 +2289,11 @@ if ($action == 'create') print ''; } + // Select type + print ''; + print $formexpensereport->selectTypeExpenseReport($line->fk_c_type_fees, 'fk_c_type_fees'); + print ''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { print ''; @@ -2293,11 +2302,6 @@ if ($action == 'create') print ''; } - // Select type - print ''; - select_type_fees_id($line->fk_c_type_fees, 'fk_c_type_fees'); - print ''; - // Add comments print ''; print ''; @@ -2344,44 +2348,44 @@ if ($action == 'create') } } - // Add a line - if (($object->fk_statut == ExpenseReport::STATUS_DRAFT || $object->fk_statut == ExpenseReport::STATUS_REFUSED) - && $action != 'editline' - && $user->rights->expensereport->creer) + // Add a new line + if (($object->status == ExpenseReport::STATUS_DRAFT || $object->status == ExpenseReport::STATUS_REFUSED) + && $action != 'editline' + && $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++; + $colspan = 11; + 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)) - { - 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'; - $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); - $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); - $nbFiles = count($arrayoffiles); - $nbLinks = Link::count($db, $object->element, $object->id); - } + $nbFiles = $nbLinks = 0; + $arrayoffiles = array(); + 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'; + $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); + $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$'); + $nbFiles = count($arrayoffiles); + $nbLinks = Link::count($db, $object->element, $object->id); + } - // Add line with link to add new file or attach to an existing file - print ''; - print ''; - 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)) - { - print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); - print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); - print ''; - } + // Add line with link to add new file or attach to an existing file + print ''; + print ''; + 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)) + { + print '   -   '.$langs->trans("AttachTheNewLineToTheDocument"); + print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly'); + print ''; + } - print ''."\n"; - print ''; + print ''."\n"; + print ''; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; - include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php'; + include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php'; print ''; print ''; print ''.$langs->trans('Date').''; - if (!empty($conf->projet->enabled)) print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').''; + if (!empty($conf->projet->enabled)) { + print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).''; + } print ''.$langs->trans('Type').''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { + print ''.$langs->trans('CarCategory').''; + } print ''.$langs->trans('Description').''; print ''.$langs->trans('VAT').''; print ''.$langs->trans('PriceUHT').''; @@ -2440,19 +2448,19 @@ if ($action == 'create') print ''; } + // Select type + print ''; + print $formexpensereport->selectTypeExpenseReport($fk_c_type_fees, 'fk_c_type_fees', 1); + print ''; + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) { 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); + print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params, 0); print ''; } - // Select type - print ''; - select_type_fees_id($fk_c_type_fees, 'fk_c_type_fees', 1); - print ''; - // Add comments print ''; print ''; @@ -2541,7 +2549,7 @@ if ($action != 'create' && $action != 'edit') // Send if (empty($user->socid)) { - if ($object->fk_statut > ExpenseReport::STATUS_DRAFT) { + if ($object->status > ExpenseReport::STATUS_DRAFT) { //if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->expensereport->expensereport_advance->send)) { print ''; //} else @@ -2554,7 +2562,7 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->fk_statut == ExpenseReport::STATUS_DRAFT) + 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)) { @@ -2574,7 +2582,7 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->fk_statut == ExpenseReport::STATUS_REFUSED) + if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED) { if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { @@ -2588,12 +2596,12 @@ if ($action != 'create' && $action != 'edit') } } - if ($user->rights->expensereport->to_paid && $object->fk_statut == ExpenseReport::STATUS_APPROVED) + 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 ''; + print ''; } } @@ -2602,16 +2610,16 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_validator == user courant * Afficher : "Valider" / "Refuser" / "Supprimer" */ - if ($object->fk_statut == ExpenseReport::STATUS_VALIDATED) + if ($object->status == ExpenseReport::STATUS_VALIDATED) { if (in_array($object->fk_user_author, $user->getAllChildIds(1))) { // set draft - print ''; + print ''; } } - if ($user->rights->expensereport->approve && $object->fk_statut == ExpenseReport::STATUS_VALIDATED) + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED) { //if($object->fk_user_validator==$user->id) //{ @@ -2632,13 +2640,13 @@ if ($action != 'create' && $action != 'edit') // If status is Approved // --------------------- - if ($user->rights->expensereport->approve && $object->fk_statut == ExpenseReport::STATUS_APPROVED) + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED) { - print ''; + print ''; } // If bank module is used - if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->fk_statut == ExpenseReport::STATUS_APPROVED) + if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED) { // Pay if ($remaintopay == 0) @@ -2650,48 +2658,48 @@ if ($action != 'create' && $action != 'edit') } // If bank module is not used - if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->fk_statut == 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) { - print '"; + print '"; } } - if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->fk_statut == ExpenseReport::STATUS_APPROVED) + if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED) { - // Cancel - print ''; + // 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->fk_statut == 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 ''; + // Cancel + print ''; } - if ($user->rights->expensereport->to_paid && $object->paid && $object->fk_statut == ExpenseReport::STATUS_CLOSED) + if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED) { // Set unpaid - print ''; + print ''; } // Clone if ($user->rights->expensereport->creer) { - print ''; + print ''; } /* 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->fk_statut < 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->fk_statut != ExpenseReport::STATUS_CLOSED) + // Delete + print ''; + } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED) { - // Delete - print ''; + // Delete + print ''; } $parameters = array(); diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index c246da650af..405ba52be93 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -119,7 +119,7 @@ class ExpenseReports extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -127,26 +127,26 @@ class ExpenseReports extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) { - $obj = $db->fetch_object($result); - $expensereport_static = new ExpenseReport($db); + $obj = $this->db->fetch_object($result); + $expensereport_static = new ExpenseReport($this->db); if ($expensereport_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($expensereport_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve Expense Report list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No Expense Report found'); diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index e2ea2b377a4..3f7caca5890 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -34,80 +34,87 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.ph */ class ExpenseReport extends CommonObject { - /** + /** * @var string ID to identify managed object */ public $element = 'expensereport'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'expensereport'; - public $table_element_line = 'expensereport_det'; - public $fk_element = 'fk_expensereport'; + public $table_element_line = 'expensereport_det'; + public $fk_element = 'fk_expensereport'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'trip'; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'trip'; - public $lines = array(); + public $lines = array(); - public $date_debut; + public $date_debut; - public $date_fin; + public $date_fin; - /** - * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied - * - * @var int Status - */ - public $status; - public $fk_statut; + /** + * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied + * + * @var int Status + */ + public $status; - public $fk_c_paiement; - public $paid; + /** + * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied + * + * @var int Status + * @deprecated + */ + public $fk_statut; - public $user_author_infos; - public $user_validator_infos; + public $fk_c_paiement; + public $paid; - // ACTIONS + public $user_author_infos; + public $user_validator_infos; - // Create - public $date_create; - public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + // ACTIONS - // Update + // Create + public $date_create; + public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + + // Update public $date_modif; - public $fk_user_modif; + public $fk_user_modif; - // Refus - public $date_refuse; - public $detail_refuse; - public $fk_user_refuse; + // Refus + public $date_refuse; + public $detail_refuse; + public $fk_user_refuse; - // Annulation - public $date_cancel; - public $detail_cancel; - public $fk_user_cancel; + // Annulation + public $date_cancel; + public $detail_cancel; + public $fk_user_cancel; - public $fk_user_validator; // User that is defined to approve + public $fk_user_validator; // User that is defined to approve - // Validation - public $date_valid; // User making validation - public $fk_user_valid; - public $user_valid_infos; + // Validation + public $date_valid; // User making validation + public $fk_user_valid; + public $user_valid_infos; - // Approve - public $date_approve; - public $fk_user_approve; // User that has approved + // Approve + public $date_approve; + public $fk_user_approve; // User that has approved - // Paiement - public $user_paid_infos; + // Paiement + public $user_paid_infos; - /** + /** * Draft status */ const STATUS_DRAFT = 0; @@ -185,156 +192,156 @@ class ExpenseReport extends CommonObject ); /** - * Constructor - * - * @param DoliDB $db Handler acces base de donnees - */ - public function __construct($db) - { - $this->db = $db; - $this->total_ht = 0; - $this->total_ttc = 0; - $this->total_tva = 0; - $this->modepaymentid = 0; + * Constructor + * + * @param DoliDB $db Handler acces base de donnees + */ + public function __construct($db) + { + $this->db = $db; + $this->total_ht = 0; + $this->total_ttc = 0; + $this->total_tva = 0; + $this->modepaymentid = 0; - // List of language codes for status - $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); - $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); - } + // List of language codes for status + $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused'); + $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5'); + } - /** - * Create object in database - * - * @param User $user User that create - * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Create object in database + * + * @param User $user User that create + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs; - $now = dol_now(); + $now = dol_now(); - $error = 0; + $error = 0; - // Check parameters - if (empty($this->date_debut) || empty($this->date_fin)) - { - $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); - return -1; - } + // Check parameters + 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; + $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; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; - $sql .= "ref"; - $sql .= ",total_ht"; - $sql .= ",total_ttc"; - $sql .= ",total_tva"; - $sql .= ",date_debut"; - $sql .= ",date_fin"; - $sql .= ",date_create"; - $sql .= ",fk_user_author"; - $sql .= ",fk_user_validator"; - $sql .= ",fk_user_approve"; - $sql .= ",fk_user_modif"; - $sql .= ",fk_statut"; - $sql .= ",fk_c_paiement"; - $sql .= ",paid"; - $sql .= ",note_public"; - $sql .= ",note_private"; - $sql .= ",entity"; - $sql .= ") VALUES("; - $sql .= "'(PROV)'"; - $sql .= ", ".$this->total_ht; - $sql .= ", ".$this->total_ttc; - $sql .= ", ".$this->total_tva; - $sql .= ", '".$this->db->idate($this->date_debut)."'"; - $sql .= ", '".$this->db->idate($this->date_fin)."'"; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".$fuserid; - $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); - $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); - $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null"); - $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0); - $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); - $sql .= ", 0"; - $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); - $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); - $sql .= ", ".$conf->entity; - $sql .= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." ("; + $sql .= "ref"; + $sql .= ",total_ht"; + $sql .= ",total_ttc"; + $sql .= ",total_tva"; + $sql .= ",date_debut"; + $sql .= ",date_fin"; + $sql .= ",date_create"; + $sql .= ",fk_user_author"; + $sql .= ",fk_user_validator"; + $sql .= ",fk_user_approve"; + $sql .= ",fk_user_modif"; + $sql .= ",fk_statut"; + $sql .= ",fk_c_paiement"; + $sql .= ",paid"; + $sql .= ",note_public"; + $sql .= ",note_private"; + $sql .= ",entity"; + $sql .= ") VALUES("; + $sql .= "'(PROV)'"; + $sql .= ", ".$this->total_ht; + $sql .= ", ".$this->total_ttc; + $sql .= ", ".$this->total_tva; + $sql .= ", '".$this->db->idate($this->date_debut)."'"; + $sql .= ", '".$this->db->idate($this->date_fin)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".$fuserid; + $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); + $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null"); + $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0); + $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null"); + $sql .= ", 0"; + $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); + $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); + $sql .= ", ".$conf->entity; + $sql .= ")"; - $result = $this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->ref = '(PROV'.$this->id.')'; + $result = $this->db->query($sql); + 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; - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = $this->db->lasterror(); - $error++; - } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = $this->db->lasterror(); + $error++; + } - 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)) { - $line = (object) $line; - $newndfline = new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $line->fk_expensereport; - $newndfline->fk_c_type_fees = $line->fk_c_type_fees; - $newndfline->fk_project = $line->fk_project; - $newndfline->vatrate = $line->vatrate; - $newndfline->vat_src_code = $line->vat_src_code; - $newndfline->comments = $line->comments; - $newndfline->qty = $line->qty; - $newndfline->value_unit = $line->value_unit; - $newndfline->total_ht = $line->total_ht; - $newndfline->total_ttc = $line->total_ttc; - $newndfline->total_tva = $line->total_tva; - $newndfline->date = $line->date; - $newndfline->rule_warning_message = $line->rule_warning_message; - $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; - $newndfline->fk_ecm_files = $line->fk_ecm_files; - } else { - $newndfline = $line; - } - //$newndfline=new ExpenseReportLine($this->db); - $newndfline->fk_expensereport = $this->id; - $result = $newndfline->insert(); - if ($result < 0) - { - $this->error = $newndfline->error; - $error++; - break; - } - } - } - } + 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)) { + $line = (object) $line; + $newndfline = new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $line->fk_expensereport; + $newndfline->fk_c_type_fees = $line->fk_c_type_fees; + $newndfline->fk_project = $line->fk_project; + $newndfline->vatrate = $line->vatrate; + $newndfline->vat_src_code = $line->vat_src_code; + $newndfline->comments = $line->comments; + $newndfline->qty = $line->qty; + $newndfline->value_unit = $line->value_unit; + $newndfline->total_ht = $line->total_ht; + $newndfline->total_ttc = $line->total_ttc; + $newndfline->total_tva = $line->total_tva; + $newndfline->date = $line->date; + $newndfline->rule_warning_message = $line->rule_warning_message; + $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat; + $newndfline->fk_ecm_files = $line->fk_ecm_files; + } else { + $newndfline = $line; + } + //$newndfline=new ExpenseReportLine($this->db); + $newndfline->fk_expensereport = $this->id; + $result = $newndfline->insert(); + if ($result < 0) + { + $this->error = $newndfline->error; + $error++; + break; + } + } + } + } - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) $error++; + } - if (!$error) - { - $result = $this->update_price(); - if ($result > 0) - { + if (!$error) + { + $result = $this->update_price(); + if ($result > 0) + { if (!$notrigger) { // Call trigger @@ -354,131 +361,140 @@ class ExpenseReport extends CommonObject $this->db->rollback(); return -4; } - } else { - $this->db->rollback(); - return -3; - } - } else { - dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->lasterror()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + } else { + $this->db->rollback(); + return -3; + } + } else { + dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->lasterror()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * Load an object from its id and create a new one in database - * + /** + * Load an object from its id and create a new one in database + * * @param User $user User making the clone - * @param int $fk_user_author Id of new user - * @return int New id of clone - */ - public function createFromClone(User $user, $fk_user_author) - { - global $hookmanager; + * @param int $fk_user_author Id of new user + * @return int New id of clone + */ + public function createFromClone(User $user, $fk_user_author) + { + global $hookmanager; - $error = 0; + $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(); + $this->db->begin(); - // get extrafields so they will be clone - //foreach($this->lines as $line) - //$line->fetch_optionals(); + // get extrafields so they will be clone + //foreach($this->lines as $line) + //$line->fetch_optionals(); - // Load source object - $objFrom = clone $this; + // Load source object + $objFrom = clone $this; - $this->id = 0; - $this->ref = ''; - $this->status = 0; - $this->fk_statut = 0; + $this->id = 0; + $this->ref = ''; + $this->status = 0; + $this->fk_statut = 0; // deprecated - // Clear fields - $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_valid = ''; - $this->date_create = ''; - $this->date_creation = ''; - $this->date_validation = ''; + // Clear fields + $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_valid = ''; + $this->date_create = ''; + $this->date_creation = ''; + $this->date_validation = ''; - // Create clone - $this->context['createfromclone'] = 'createfromclone'; - $result = $this->create($user); - if ($result < 0) $error++; + // Remove link on lines to a joined file + if (is_array($this->lines) && count($this->lines) > 0) + { + foreach ($this->lines as $key => $line) + { + $this->lines[$key]->fk_ecm_files = 0; + } + } - if (!$error) - { - // Hook of thirdparty module - 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++; - } - } + // Create clone + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($user); + if ($result < 0) $error++; - unset($this->context['createfromclone']); + if (!$error) + { + // Hook of thirdparty module + 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++; + } + } - // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + unset($this->context['createfromclone']); + + // End + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * update - * - * @param User $user User making change + /** + * update + * + * @param User $user User making change * @param int $notrigger Disable triggers - * @param User $userofexpensereport New user we want to have the expense report on. - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0, $userofexpensereport = null) - { - global $langs; + * @param User $userofexpensereport New user we want to have the expense report on. + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0, $userofexpensereport = null) + { + global $langs; $error = 0; $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $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)) - { - $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"); - $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); - $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); - $sql .= " , fk_user_modif = ".$user->id; - $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); - $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); - $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); - $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); - $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $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)) + { + $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"); + $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null"); + $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null"); + $sql .= " , fk_user_modif = ".$user->id; + $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0'); + $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null"); + $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''"); + $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''"); + $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''"); + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if (!$notrigger) + dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user); @@ -498,132 +514,132 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->error(); - return -1; - } - } + $this->error = $this->db->error(); + return -1; + } + } - /** - * Load an object from database - * - * @param int $id Id {@min 1} - * @param string $ref Ref {@name ref} - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $conf; + /** + * Load an object from database + * + * @param int $id Id {@min 1} + * @param string $ref Ref {@name ref} + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $conf; - $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT - $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS - $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS - $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int) - $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) - $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; - $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; - //$sql.= $restrict; + $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT + $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS + $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS + $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int) + $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime) + $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,"; + $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; + //$sql.= $restrict; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->total_tva; - $this->total_ttc = $obj->total_ttc; - $this->note_public = $obj->note_public; - $this->note_private = $obj->note_private; - $this->detail_refuse = $obj->detail_refuse; - $this->detail_cancel = $obj->detail_cancel; + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->total_tva; + $this->total_ttc = $obj->total_ttc; + $this->note_public = $obj->note_public; + $this->note_private = $obj->note_private; + $this->detail_refuse = $obj->detail_refuse; + $this->detail_cancel = $obj->detail_cancel; - $this->date_debut = $this->db->jdate($obj->date_debut); - $this->date_fin = $this->db->jdate($obj->date_fin); - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->date_approve = $this->db->jdate($obj->date_approve); - $this->date_create = $this->db->jdate($obj->date_create); - $this->date_modif = $this->db->jdate($obj->date_modif); - $this->date_refuse = $this->db->jdate($obj->date_refuse); - $this->date_cancel = $this->db->jdate($obj->date_cancel); + $this->date_debut = $this->db->jdate($obj->date_debut); + $this->date_fin = $this->db->jdate($obj->date_fin); + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_approve = $this->db->jdate($obj->date_approve); + $this->date_create = $this->db->jdate($obj->date_create); + $this->date_modif = $this->db->jdate($obj->date_modif); + $this->date_refuse = $this->db->jdate($obj->date_refuse); + $this->date_cancel = $this->db->jdate($obj->date_cancel); - $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_user_validator = $obj->fk_user_validator; - $this->fk_user_valid = $obj->fk_user_valid; - $this->fk_user_refuse = $obj->fk_user_refuse; - $this->fk_user_cancel = $obj->fk_user_cancel; - $this->fk_user_approve = $obj->fk_user_approve; + $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_user_validator = $obj->fk_user_validator; + $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_user_refuse = $obj->fk_user_refuse; + $this->fk_user_cancel = $obj->fk_user_cancel; + $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); + $user_author = new User($this->db); + if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); - $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); + $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 - $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->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 + $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); - $this->fk_statut = $obj->status; // deprecated - $this->status = $obj->status; - $this->fk_c_paiement = $obj->fk_c_paiement; - $this->paid = $obj->paid; + $this->fk_statut = $obj->status; // deprecated + $this->status = $obj->status; + $this->fk_c_paiement = $obj->fk_c_paiement; + $this->paid = $obj->paid; - if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED) - { - $user_valid = new User($this->db); - if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); - $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); - } + 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); + $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); + } - $this->lines = array(); + $this->lines = array(); - $result = $this->fetch_lines(); + $result = $this->fetch_lines(); - return $result; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + return $result; + } else { + return 0; + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Classify the expense report as paid - * - * @param int $id Id of expense report - * @param user $fuser User making change + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Classify the expense report as paid + * + * @param int $id Id of expense report + * @param user $fuser User making change * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_paid($id, $fuser, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_paid($id, $fuser, $notrigger = 0) + { + // phpcs:enable $error = 0; $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; - $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; - $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED; + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport"; + $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1"; + $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED; - dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { + 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) { // Call trigger @@ -644,263 +660,263 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->commit(); - return 0; - } - } else { + return 0; + } + } else { $this->db->rollback(); - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** - * Returns the label status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } + /** + * Returns the label status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Returns the label of a statut - * - * @param int $status id statut - * @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 - * @return string Label - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Returns the label of a status + * + * @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 + * @return string Label + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; - $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]); - $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]); + $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]); + $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]); - $statusType = $this->statuts_logo[$status]; + $statusType = $this->statuts_logo[$status]; - return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); - } + return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); + } - /** - * Load information on object - * - * @param int $id Id of object - * @return void - */ - public function info($id) - { - global $conf; + /** + * Load information on object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + global $conf; - $sql = "SELECT f.rowid,"; - $sql .= " f.date_create as datec,"; - $sql .= " f.tms as date_modification,"; - $sql .= " f.date_valid as datev,"; - $sql .= " f.date_approve as datea,"; - //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for. - $sql .= " f.fk_user_modif as fk_user_modification,"; - $sql .= " f.fk_user_valid,"; - $sql .= " f.fk_user_approve"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; - $sql .= " WHERE f.rowid = ".$id; - $sql .= " AND f.entity = ".$conf->entity; + $sql = "SELECT f.rowid,"; + $sql .= " f.date_create as datec,"; + $sql .= " f.tms as date_modification,"; + $sql .= " f.date_valid as datev,"; + $sql .= " f.date_approve as datea,"; + //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for. + $sql .= " f.fk_user_modif as fk_user_modification,"; + $sql .= " f.fk_user_valid,"; + $sql .= " f.fk_user_approve"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f"; + $sql .= " WHERE f.rowid = ".$id; + $sql .= " AND f.entity = ".$conf->entity; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->date_modification); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_approbation = $this->db->jdate($obj->datea); + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->date_modification); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_approbation = $this->db->jdate($obj->datea); - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; - 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) - { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } - 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) - { - $auser = new User($this->db); - $auser->fetch($obj->fk_user_approve); - $this->user_approve = $auser; - } - } - $this->db->free($resql); - } else { - dol_print_error($this->db); - } - } + 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) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + 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) + { + $auser = new User($this->db); + $auser->fetch($obj->fk_user_approve); + $this->user_approve = $auser; + } + } + $this->db->free($resql); + } else { + dol_print_error($this->db); + } + } - /** - * 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() - { - global $user, $langs, $conf; + /** + * 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() + { + global $user, $langs, $conf; - $now = dol_now(); + $now = dol_now(); - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->date_create = $now; - $this->date_debut = $now; - $this->date_fin = $now; - $this->date_valid = $now; - $this->date_approve = $now; + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->date_create = $now; + $this->date_debut = $now; + $this->date_fin = $now; + $this->date_valid = $now; + $this->date_approve = $now; - $type_fees_id = 2; // TF_TRIP + $type_fees_id = 2; // TF_TRIP - $this->status = 5; - $this->fk_statut = 5; + $this->status = 5; + $this->fk_statut = 5; - $this->fk_user_author = $user->id; - $this->fk_user_validator = $user->id; - $this->fk_user_valid = $user->id; - $this->fk_user_approve = $user->id; + $this->fk_user_author = $user->id; + $this->fk_user_validator = $user->id; + $this->fk_user_valid = $user->id; + $this->fk_user_approve = $user->id; - $this->note_private = 'Private note'; - $this->note_public = 'SPECIMEN'; - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) { - $line = new ExpenseReportLine($this->db); - $line->comments = $langs->trans("Comment")." ".$xnbp; - $line->date = ($now - 3600 * (1 + $xnbp)); - $line->total_ht = 100; - $line->total_tva = 20; - $line->total_ttc = 120; - $line->qty = 1; - $line->vatrate = 20; - $line->value_unit = 120; - $line->fk_expensereport = 0; - $line->type_fees_code = 'TRA'; - $line->fk_c_type_fees = $type_fees_id; + $this->note_private = 'Private note'; + $this->note_public = 'SPECIMEN'; + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) { + $line = new ExpenseReportLine($this->db); + $line->comments = $langs->trans("Comment")." ".$xnbp; + $line->date = ($now - 3600 * (1 + $xnbp)); + $line->total_ht = 100; + $line->total_tva = 20; + $line->total_ttc = 120; + $line->qty = 1; + $line->vatrate = 20; + $line->value_unit = 120; + $line->fk_expensereport = 0; + $line->type_fees_code = 'TRA'; + $line->fk_c_type_fees = $type_fees_id; - $line->projet_ref = 'ABC'; + $line->projet_ref = 'ABC'; - $this->lines[$xnbp] = $line; - $xnbp++; + $this->lines[$xnbp] = $line; + $xnbp++; - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; - } - } + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_line_by_project - * - * @param int $projectid Project id - * @param User $user User - * @return int <0 if KO, >0 if OK - */ - public function fetch_line_by_project($projectid, $user = '') - { - // phpcs:enable - global $conf, $db, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_line_by_project + * + * @param int $projectid Project id + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function fetch_line_by_project($projectid, $user = '') + { + // phpcs:enable + global $conf, $db, $langs; - $langs->load('trips'); + $langs->load('trips'); - if ($user->rights->expensereport->lire) { - $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; - $sql .= " WHERE de.fk_projet = ".$projectid; + if ($user->rights->expensereport->lire) { + $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de"; + $sql .= " WHERE de.fk_projet = ".$projectid; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - $total_HT = 0; - $total_TTC = 0; + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + $total_HT = 0; + $total_TTC = 0; - while ($i < $num) - { - $objp = $db->fetch_object($result); + while ($i < $num) + { + $objp = $this->db->fetch_object($result); - $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut"; - $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; - $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'"; + $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status"; + $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; + $sql2 .= " WHERE d.rowid = ".((int) $objp->fk_expensereport); - $result2 = $db->query($sql2); - $obj = $db->fetch_object($result2); + $result2 = $this->db->query($sql2); + $obj = $this->db->fetch_object($result2); - $objp->fk_user_author = $obj->fk_user_author; - $objp->ref = $obj->ref; - $objp->fk_c_expensereport_status = $obj->fk_statut; - $objp->rowid = $obj->rowid; + $objp->fk_user_author = $obj->fk_user_author; + $objp->ref = $obj->ref; + $objp->fk_c_expensereport_status = $obj->status; + $objp->rowid = $obj->rowid; - $total_HT = $total_HT + $objp->total_ht; - $total_TTC = $total_TTC + $objp->total_ttc; - $author = new User($db); - $author->fetch($objp->fk_user_author); + $total_HT = $total_HT + $objp->total_ht; + $total_TTC = $total_TTC + $objp->total_ttc; + $author = new User($this->db); + $author->fetch($objp->fk_user_author); - print ''; - print ''.$objp->ref_num.''; - print ''.dol_print_date($objp->date, 'day').''; - print ''.$author->getNomUrl(1).''; - print ''.$objp->comments.''; - print ''.price($objp->total_ht).''; - print ''.price($objp->total_ttc).''; - print ''; + print ''; + print ''.$objp->ref_num.''; + print ''.dol_print_date($objp->date, 'day').''; + print ''.$author->getNomUrl(1).''; + print ''.$objp->comments.''; + print ''.price($objp->total_ht).''; + print ''.price($objp->total_ttc).''; + print ''; - switch ($objp->fk_c_expensereport_status) { - case 4: - print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); - break; - case 1: - print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); - break; - case 2: - print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); - break; - case 5: - print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); - break; - case 6: - print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); - break; - } - /* + switch ($objp->fk_c_expensereport_status) { + case 4: + print img_picto($langs->trans('StatusOrderCanceled'), 'statut5'); + break; + case 1: + print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0'); + break; + case 2: + print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3'); + break; + case 5: + print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3'); + break; + case 6: + print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4'); + 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'); @@ -908,237 +924,237 @@ class ExpenseReport extends CommonObject if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); */ - print ''; - print ''; + print ''; + print ''; - $i++; - } + $i++; + } - print ''.$langs->trans("Number").': '.$i.''; - print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; - print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; - print ' '; - print ''; - } else { - $this->error = $db->lasterror(); - return -1; - } - } - } + print ''.$langs->trans("Number").': '.$i.''; + print ''.$langs->trans("TotalHT").' : '.price($total_HT).''; + print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).''; + print ' '; + print ''; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } + } - /** - * recalculer - * TODO Replace this with call to update_price if not already done - * - * @param int $id Id of expense report - * @return int <0 if KO, >0 if OK - */ - public function recalculer($id) - { - $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt'; - $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id; + /** + * recalculer + * TODO Replace this with call to update_price if not already done + * + * @param int $id Id of expense report + * @return int <0 if KO, >0 if OK + */ + public function recalculer($id) + { + $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt'; + $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id; - $total_ht = 0; $total_tva = 0; $total_ttc = 0; + $total_ht = 0; $total_tva = 0; $total_ttc = 0; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num): - $objp = $this->db->fetch_object($result); - $total_ht += $objp->total_ht; - $total_tva += $objp->total_tva; - $i++; - endwhile; + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num): + $objp = $this->db->fetch_object($result); + $total_ht += $objp->total_ht; + $total_tva += $objp->total_tva; + $i++; + endwhile; - $total_ttc = $total_ht + $total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$total_ht; - $sql .= " , total_ttc = ".$total_ttc; - $sql .= " , total_tva = ".$total_tva; - $sql .= " WHERE rowid = ".$id; - $result = $this->db->query($sql); - if ($result): - $this->db->free($result); - return 1; - else : - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); - return -3; - endif; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); - return -3; - } - } + $total_ttc = $total_ht + $total_tva; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$total_ht; + $sql .= " , total_ttc = ".$total_ttc; + $sql .= " , total_tva = ".$total_tva; + $sql .= " WHERE rowid = ".$id; + $result = $this->db->query($sql); + if ($result): + $this->db->free($result); + return 1; + else : + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + endif; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR); + return -3; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * fetch_lines - * - * @return int <0 if OK, >0 if KO - */ - public function fetch_lines() - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * fetch_lines + * + * @return int <0 if OK, >0 if KO + */ + public function fetch_lines() + { + // phpcs:enable + global $conf; - $this->lines = array(); + $this->lines = array(); - $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; - $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,'; - $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; - $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,'; - $sql .= ' p.ref as ref_projet, p.title as title_projet'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; - $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)) - { - $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; - } else { - $sql .= ' ORDER BY de.rang ASC, de.date ASC'; - } + $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,'; + $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,'; + $sql .= ' de.total_ht, de.total_tva, de.total_ttc,'; + $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,'; + $sql .= ' p.ref as ref_projet, p.title as title_projet'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de'; + $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)) + { + $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) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($resql); - $deplig = new ExpenseReportLine($this->db); + $deplig = new ExpenseReportLine($this->db); - $deplig->rowid = $objp->rowid; - $deplig->id = $objp->rowid; - $deplig->comments = $objp->comments; - $deplig->qty = $objp->qty; - $deplig->value_unit = $objp->value_unit; - $deplig->date = $objp->date; - $deplig->dates = $this->db->jdate($objp->date); + $deplig->rowid = $objp->rowid; + $deplig->id = $objp->rowid; + $deplig->comments = $objp->comments; + $deplig->qty = $objp->qty; + $deplig->value_unit = $objp->value_unit; + $deplig->date = $objp->date; + $deplig->dates = $this->db->jdate($objp->date); - $deplig->fk_expensereport = $objp->fk_expensereport; - $deplig->fk_c_type_fees = $objp->fk_c_type_fees; - $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $deplig->fk_projet = $objp->fk_project; // deprecated - $deplig->fk_project = $objp->fk_project; - $deplig->fk_ecm_files = $objp->fk_ecm_files; + $deplig->fk_expensereport = $objp->fk_expensereport; + $deplig->fk_c_type_fees = $objp->fk_c_type_fees; + $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $deplig->fk_projet = $objp->fk_project; // deprecated + $deplig->fk_project = $objp->fk_project; + $deplig->fk_ecm_files = $objp->fk_ecm_files; - $deplig->total_ht = $objp->total_ht; - $deplig->total_tva = $objp->total_tva; - $deplig->total_ttc = $objp->total_ttc; + $deplig->total_ht = $objp->total_ht; + $deplig->total_tva = $objp->total_tva; + $deplig->total_ttc = $objp->total_ttc; - $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; - $deplig->type_fees_libelle = $objp->libelle_type_fees; + $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees; + $deplig->type_fees_libelle = $objp->libelle_type_fees; $deplig->tva_tx = $objp->tva_tx; - $deplig->vatrate = $objp->tva_tx; - $deplig->projet_ref = $objp->ref_projet; - $deplig->projet_title = $objp->title_projet; + $deplig->vatrate = $objp->tva_tx; + $deplig->projet_ref = $objp->ref_projet; + $deplig->projet_title = $objp->title_projet; - $deplig->rang = $objp->rang; + $deplig->rang = $objp->rang; - $this->lines[$i] = $deplig; + $this->lines[$i] = $deplig; - $i++; - } - $this->db->free($resql); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); - return -3; - } - } + $i++; + } + $this->db->free($resql); + return 1; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR); + return -3; + } + } - /** - * delete - * - * @param User $fuser User that delete - * @return int <0 if KO, >0 if OK - */ - public function delete(User $fuser = null) - { - global $user, $langs, $conf; + /** + * delete + * + * @param User $fuser User that delete + * @return int <0 if KO, >0 if OK + */ + public function delete(User $fuser = null) + { + global $user, $langs, $conf; - if (!$rowid) $rowid = $this->id; + if (!$rowid) $rowid = $this->id; - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid; - if ($this->db->query($sql)) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -6; - } - } else { - $this->error = $this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -4; - } - } + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid; + if ($this->db->query($sql)) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -6; + } + } else { + $this->error = $this->db->error()." sql=".$sql; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -4; + } + } - /** - * Set to status validate - * - * @param User $fuser User + /** + * Set to status validate + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - public function setValidate($fuser, $notrigger = 0) - { - global $conf, $langs, $user; + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setValidate($fuser, $notrigger = 0) + { + global $conf, $langs, $user; $error = 0; $now = dol_now(); - // Protection - if ($this->statut == self::STATUS_VALIDATED) - { - dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); - return 0; - } + // Protection + if ($this->status == self::STATUS_VALIDATED) + { + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } - $this->date_valid = $now; // Required for the getNextNum later. + $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 - { - $num = $this->getNextNumRef(); - } else { - $num = $this->ref; - } - if (empty($num) || $num < 0) return -1; + 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; - $this->newref = dol_sanitizeFileName($num); + $this->newref = dol_sanitizeFileName($num); $this->db->begin(); - // Validate - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET ref = '".$num."',"; - $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; - $sql .= " date_valid='".$this->db->idate($this->date_valid)."',"; - $sql .= " fk_user_valid = ".$user->id; - $sql .= " WHERE rowid = ".$this->id; + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate($this->date_valid)."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; - $resql = $this->db->query($sql); - if ($resql) - { + $resql = $this->db->query($sql); + if ($resql) + { if (!$error && !$notrigger) { // Call trigger @@ -1151,42 +1167,42 @@ class ExpenseReport extends CommonObject if (!$error) { - $this->oldref = $this->ref; + $this->oldref = $this->ref; - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + // Rename directory if dir was a temporary 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; + // 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(); } - // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + // 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)) { - dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); + dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$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) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @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) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } } } } @@ -1194,8 +1210,8 @@ class ExpenseReport extends CommonObject // Set new ref and current status if (!$error) { - $this->ref = $num; - $this->statut = self::STATUS_VALIDATED; + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; } if (empty($error)) @@ -1207,81 +1223,81 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } + $this->error = $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_save_from_refuse - * - * @param User $fuser User - * @return int <0 if KO, >0 if OK - */ - public function set_save_from_refuse($fuser) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_save_from_refuse + * + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function set_save_from_refuse($fuser) + { + // phpcs:enable + global $conf, $langs; - // Sélection de la date de début de la NDF - $sql = 'SELECT date_debut'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' WHERE rowid = '.$this->id; + // Sélection de la date de début de la NDF + $sql = 'SELECT date_debut'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' WHERE rowid = '.$this->id; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - $objp = $this->db->fetch_object($result); + $objp = $this->db->fetch_object($result); - $this->date_debut = $this->db->jdate($objp->date_debut); + $this->date_debut = $this->db->jdate($objp->date_debut); - if ($this->fk_statut != self::STATUS_VALIDATED) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; - $sql .= ' WHERE rowid = '.$this->id; + 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); + dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); - } - } + if ($this->db->query($sql)) + { + return 1; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING); + } + } - /** - * Set status to approved - * - * @param User $fuser User + /** + * Set status to approved + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - public function setApproved($fuser, $notrigger = 0) - { - $now = dol_now(); - $error = 0; + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + public function setApproved($fuser, $notrigger = 0) + { + $now = dol_now(); + $error = 0; - // date approval - $this->date_approve = $now; - if ($this->fk_statut != self::STATUS_APPROVED) - { + // date approval + $this->date_approve = $now; + 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) + $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) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser); @@ -1301,46 +1317,47 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); - } + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING); + } - return 0; - } + return 0; + } - /** - * setDeny - * - * @param User $fuser User - * @param string $details Details - * @param int $notrigger Disable triggers - * @return int - */ - public function setDeny($fuser, $details, $notrigger = 0) - { - $now = dol_now(); + /** + * setDeny + * + * @param User $fuser User + * @param string $details Details + * @param int $notrigger Disable triggers + * @return int + */ + public function setDeny($fuser, $details, $notrigger = 0) + { + $now = dol_now(); $error = 0; - // date de refus - if ($this->fk_statut != 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)) - { - $this->fk_statut = 99; - $this->fk_user_refuse = $fuser->id; - $this->detail_refuse = $details; - $this->date_refuse = $now; + // date de refus + 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)) + { + $this->fk_statut = 99; // deprecated + $this->status = 99; + $this->fk_user_refuse = $fuser->id; + $this->detail_refuse = $details; + $this->date_refuse = $now; if (!$notrigger) { @@ -1362,38 +1379,38 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); - } - } + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_unpaid - * - * @param User $fuser User + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_unpaid + * + * @param User $fuser User * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_unpaid($fuser, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_unpaid($fuser, $notrigger = 0) + { + // phpcs:enable $error = 0; if ($this->paid) - { + { $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); if ($this->db->query($sql)) { @@ -1422,39 +1439,39 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -1; } - } else { - dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); - } - } + } else { + dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * set_cancel - * - * @param User $fuser User - * @param string $detail Detail + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * set_cancel + * + * @param User $fuser User + * @param string $detail Detail * @param int $notrigger Disable triggers - * @return int <0 if KO, >0 if OK - */ - public function set_cancel($fuser, $detail, $notrigger = 0) - { - // phpcs:enable + * @return int <0 if KO, >0 if OK + */ + public function set_cancel($fuser, $detail, $notrigger = 0) + { + // phpcs:enable $error = 0; - $this->date_cancel = $this->db->idate(dol_now()); - if ($this->fk_statut != self::STATUS_CANCELED) - { + $this->date_cancel = $this->db->idate(dol_now()); + if ($this->status != self::STATUS_CANCELED) + { $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id; - $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; - $sql .= " ,detail_cancel='".$this->db->escape($detail)."'"; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id; + $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'"; + $sql .= " ,detail_cancel='".$this->db->escape($detail)."'"; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) + { if (!$notrigger) { // Call trigger @@ -1475,192 +1492,195 @@ class ExpenseReport extends CommonObject $this->error = $this->db->error(); return -2; } - } else { + } else { $this->db->rollback(); - $this->error = $this->db->error(); - return -1; - } - } else { - dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); - } - } + $this->error = $this->db->error(); + return -1; + } + } else { + dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING); + } + } - /** - * Return next reference of expense report not already used - * - * @return string free ref - */ - public function getNextNumRef() - { - global $langs, $conf; - $langs->load("trips"); + /** + * Return next reference of expense report not already used + * + * @return string free ref + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("trips"); - if (!empty($conf->global->EXPENSEREPORT_ADDON)) - { - $mybool = false; + if (!empty($conf->global->EXPENSEREPORT_ADDON)) + { + $mybool = false; - $file = $conf->global->EXPENSEREPORT_ADDON.".php"; + $file = $conf->global->EXPENSEREPORT_ADDON.".php"; $classname = $conf->global->EXPENSEREPORT_ADDON; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/expensereport/"); + $dir = dol_buildpath($reldir."core/modules/expensereport/"); - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } - if ($mybool === false) { - dol_print_error('', "Failed to include file ".$file); - return ''; - } + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } - $obj = new $classname(); - $numref = $obj->getNextValue($this); + $obj = new $classname(); + $numref = $obj->getNextValue($this); - if ($numref != "") - { - return $numref; - } else { + if ($numref != "") + { + return $numref; + } else { $this->error = $obj->error; $this->errors = $obj->errors; - //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); - return -1; - } - } else { - $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; - return -2; - } - } + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return -1; + } + } else { + $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined"; + return -2; + } + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $max Max length of shown ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) - { - global $langs, $conf; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $max Max length of shown ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) + { + global $langs, $conf; - $result = ''; + $result = ''; - $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; - if ($short) return $url; + if ($short) return $url; - $label = ''.$langs->trans("ShowExpenseReport").''; - if (!empty($this->ref)) - $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - 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)) - $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) - $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + $label = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").''; + if (!empty($this->ref)) + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + 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)) + $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (!empty($this->total_ttc)) + $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } + 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 ($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'; + //} - $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + $ref = $this->ref; + if (empty($ref)) $ref = $this->id; - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowExpenseReport"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowExpenseReport"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } - $linkstart = ''; - $linkend = ''; + $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 .= ($max ?dol_trunc($ref, $max) : $ref); - $result .= $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); + $result .= $linkend; - return $result; - } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update total of an expense report when you add a line. - * - * @param string $ligne_total_ht Amount without taxes - * @param string $ligne_total_tva Amount of all taxes - * @return void - */ - public function update_totaux_add($ligne_total_ht, $ligne_total_tva) - { - // phpcs:enable - $this->total_ht = $this->total_ht + $ligne_total_ht; - $this->total_tva = $this->total_tva + $ligne_total_tva; - $this->total_ttc = $this->total_ht + $this->total_tva; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you add a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_add($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht + $ligne_total_ht; + $this->total_tva = $this->total_tva + $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result): - return 1; - else : - $this->error = $this->db->error(); - return -1; - endif; - } + $result = $this->db->query($sql); + if ($result): + return 1; + else : + $this->error = $this->db->error(); + return -1; + endif; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Update total of an expense report when you delete a line. - * - * @param string $ligne_total_ht Amount without taxes - * @param string $ligne_total_tva Amount of all taxes - * @return void - */ - public function update_totaux_del($ligne_total_ht, $ligne_total_tva) - { - // phpcs:enable - $this->total_ht = $this->total_ht - $ligne_total_ht; - $this->total_tva = $this->total_tva - $ligne_total_tva; - $this->total_ttc = $this->total_ht + $this->total_tva; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Update total of an expense report when you delete a line. + * + * @param string $ligne_total_ht Amount without taxes + * @param string $ligne_total_tva Amount of all taxes + * @return void + */ + public function update_totaux_del($ligne_total_ht, $ligne_total_tva) + { + // phpcs:enable + $this->total_ht = $this->total_ht - $ligne_total_ht; + $this->total_tva = $this->total_tva - $ligne_total_tva; + $this->total_ttc = $this->total_ht + $this->total_tva; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " total_ht = ".$this->total_ht; - $sql .= " , total_ttc = ".$this->total_ttc; - $sql .= " , total_tva = ".$this->total_tva; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " total_ht = ".$this->total_ht; + $sql .= " , total_ttc = ".$this->total_ttc; + $sql .= " , total_tva = ".$this->total_tva; + $sql .= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result): - return 1; - else : - $this->error = $this->db->error(); - return -1; - endif; - } + $result = $this->db->query($sql); + if ($result): + return 1; + else : + $this->error = $this->db->error(); + return -1; + endif; + } /** * addline @@ -1677,13 +1697,13 @@ class ExpenseReport extends CommonObject * @param int $fk_ecm_files Id of ECM file to link to this expensereport line * @return int <0 if KO, >0 if OK */ - public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0) + public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0) { global $conf, $langs, $mysoc; - 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); + 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->fk_statut == self::STATUS_DRAFT) + 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; @@ -1738,28 +1758,28 @@ class ExpenseReport extends CommonObject $this->checkRules($type, $seller); $result = $this->line->insert(0, true); - 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) - { - $this->db->commit(); - return $this->line->id; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->line->error; - dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } + 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) + { + $this->db->commit(); + return $this->line->id; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->line->error; + dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } } else { - dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); + dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR); $this->error = 'ErrorExpenseNotDraft'; - return -3; - } + return -3; + } } /** @@ -1905,329 +1925,329 @@ class ExpenseReport extends CommonObject return false; } - /** - * Update an expense report line - * - * @param int $rowid Line to edit - * @param int $type_fees_id Type payment - * @param int $projet_id Project id - * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' - * @param string $comments Description - * @param float $qty Qty - * @param double $value_unit Value init - * @param int $date Date - * @param int $expensereport_id Expense report id - * @param int $fk_c_exp_tax_cat Id of category of car + /** + * Update an expense report line + * + * @param int $rowid Line to edit + * @param int $type_fees_id Type payment + * @param int $projet_id Project id + * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)' + * @param string $comments Description + * @param float $qty Qty + * @param double $value_unit Value init + * @param int $date Date + * @param int $expensereport_id Expense report id + * @param int $fk_c_exp_tax_cat Id of category of car * @param int $fk_ecm_files Id of ECM file to link to this expensereport line - * @return int <0 if KO, >0 if OK - */ - public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0) - { - global $user, $mysoc; + * @return int <0 if KO, >0 if OK + */ + public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0) + { + global $user, $mysoc; - if ($this->fk_statut == 0 || $this->fk_statut == 99) - { - $this->db->begin(); + if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) + { + $this->db->begin(); - $type = 0; // TODO What if type is service ? + $type = 0; // TODO What if type is service ? - // We don't know seller and buyer for expense reports - $seller = $mysoc; - $buyer = new Societe($this->db); + // We don't know seller and buyer for expense reports + $seller = $mysoc; + $buyer = new Societe($this->db); - $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { - $vat_src_code = $reg[1]; - $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. - } - $vatrate = preg_replace('/\*/', '', $vatrate); + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $vatrate, $reg)) + { + $vat_src_code = $reg[1]; + $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. + } + $vatrate = preg_replace('/\*/', '', $vatrate); - $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); + $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type); - // calcul total of line - //$total_ttc = price2num($qty*$value_unit, 'MT'); + // calcul total of line + //$total_ttc = price2num($qty*$value_unit, 'MT'); - $tx_tva = $vatrate / 100; - $tx_tva = $tx_tva + 1; - $total_ht = price2num($total_ttc / $tx_tva, 'MT'); + $tx_tva = $vatrate / 100; + $tx_tva = $tx_tva + 1; + $total_ht = price2num($total_ttc / $tx_tva, 'MT'); - $total_tva = price2num($total_ttc - $total_ht, 'MT'); - // fin calculs + $total_tva = price2num($total_ttc - $total_ht, 'MT'); + // fin calculs - $this->line = new ExpenseReportLine($this->db); - $this->line->comments = $comments; - $this->line->qty = $qty; - $this->line->value_unit = $value_unit; - $this->line->date = $date; + $this->line = new ExpenseReportLine($this->db); + $this->line->comments = $comments; + $this->line->qty = $qty; + $this->line->value_unit = $value_unit; + $this->line->date = $date; - $this->line->fk_expensereport = $expensereport_id; - $this->line->fk_c_type_fees = $type_fees_id; - $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; - $this->line->fk_projet = $projet_id; // deprecated - $this->line->fk_project = $projet_id; + $this->line->fk_expensereport = $expensereport_id; + $this->line->fk_c_type_fees = $type_fees_id; + $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat; + $this->line->fk_projet = $projet_id; // deprecated + $this->line->fk_project = $projet_id; - $this->line->vat_src_code = $vat_src_code; - $this->line->vatrate = price2num($vatrate); - $this->line->total_ttc = $tmp[2]; - $this->line->total_ht = $tmp[0]; - $this->line->total_tva = $tmp[1]; - $this->line->localtax1_tx = $localtaxes_type[1]; - $this->line->localtax2_tx = $localtaxes_type[3]; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->vat_src_code = $vat_src_code; + $this->line->vatrate = price2num($vatrate); + $this->line->total_ttc = $tmp[2]; + $this->line->total_ht = $tmp[0]; + $this->line->total_tva = $tmp[1]; + $this->line->localtax1_tx = $localtaxes_type[1]; + $this->line->localtax2_tx = $localtaxes_type[3]; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_ecm_files = $fk_ecm_files; + $this->line->fk_ecm_files = $fk_ecm_files; - $this->line->id = $rowid; + $this->line->id = $rowid; - // Select des infos sur le type fees - $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; - $sql .= " WHERE c.id = ".$type_fees_id; - $resql = $this->db->query($sql); - 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; - $this->db->free($resql); - } + // Select des infos sur le type fees + $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; + $sql .= " WHERE c.id = ".$type_fees_id; + $resql = $this->db->query($sql); + 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; + $this->db->free($resql); + } - // Select des informations du projet - $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; - $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; - $sql .= " WHERE p.rowid = ".$projet_id; - $resql = $this->db->query($sql); - if ($resql) { - $objp_projet = $this->db->fetch_object($resql); - $this->line->projet_ref = $objp_projet->ref_projet; - $this->line->projet_title = $objp_projet->title_projet; - $this->db->free($resql); - } + // Select des informations du projet + $sql = "SELECT p.ref as ref_projet, p.title as title_projet"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql .= " WHERE p.rowid = ".$projet_id; + $resql = $this->db->query($sql); + if ($resql) { + $objp_projet = $this->db->fetch_object($resql); + $this->line->projet_ref = $objp_projet->ref_projet; + $this->line->projet_title = $objp_projet->title_projet; + $this->db->free($resql); + } $this->applyOffset(); $this->checkRules(); - $result = $this->line->update($user); - if ($result > 0) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->line->error; - $this->errors = $this->line->errors; - $this->db->rollback(); - return -2; - } - } - } + $result = $this->line->update($user); + if ($result > 0) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -2; + } + } + } - /** - * deleteline - * - * @param int $rowid Row id - * @param User $fuser User - * @return int <0 if KO, >0 if OK - */ - public function deleteline($rowid, $fuser = '') - { - $this->db->begin(); + /** + * deleteline + * + * @param int $rowid Row id + * @param User $fuser User + * @return int <0 if KO, >0 if OK + */ + public function deleteline($rowid, $fuser = '') + { + $this->db->begin(); - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql .= ' WHERE rowid = '.$rowid; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql .= ' WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::deleteline sql=".$sql); - $result = $this->db->query($sql); - if (!$result) - { - $this->error = $this->db->error(); - dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } + dol_syslog(get_class($this)."::deleteline sql=".$sql); + $result = $this->db->query($sql); + if (!$result) + { + $this->error = $this->db->error(); + dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } - $this->db->commit(); + $this->db->commit(); - return 1; - } + return 1; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * periode_existe - * - * @param User $fuser User - * @param integer $date_debut Start date - * @param integer $date_fin End date - * @return int <0 if KO, >0 if OK - */ - public function periode_existe($fuser, $date_debut, $date_fin) - { - // phpcs:enable - $sql = "SELECT rowid, date_debut, date_fin"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE fk_user_author = '{$fuser->id}'"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * periode_existe + * + * @param User $fuser User + * @param integer $date_debut Start date + * @param integer $date_fin End date + * @return int <0 if KO, >0 if OK + */ + public function periode_existe($fuser, $date_debut, $date_fin) + { + // phpcs:enable + $sql = "SELECT rowid, date_debut, date_fin"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE fk_user_author = '{$fuser->id}'"; - dol_syslog(get_class($this)."::periode_existe sql=".$sql); - $result = $this->db->query($sql); - if ($result) { - $num_rows = $this->db->num_rows($result); $i = 0; + dol_syslog(get_class($this)."::periode_existe sql=".$sql); + $result = $this->db->query($sql); + if ($result) { + $num_rows = $this->db->num_rows($result); $i = 0; - if ($num_rows > 0) - { - $date_d_form = $date_debut; - $date_f_form = $date_fin; + if ($num_rows > 0) + { + $date_d_form = $date_debut; + $date_f_form = $date_fin; - $existe = false; + $existe = false; - while ($i < $num_rows) - { - $objp = $this->db->fetch_object($result); + 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 + $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++; - } + $i++; + } - if ($existe) return 1; - else return 0; - } else { - return 0; - } - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); - return -1; - } - } + if ($existe) return 1; + else return 0; + } else { + return 0; + } + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of people with permission to validate expense reports. - * Search for permission "approve expense report" - * - * @return array Array of user ids - */ - public function fetch_users_approver_expensereport() - { - // phpcs:enable - $users_validator = array(); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of people with permission to validate expense reports. + * Search for permission "approve expense report" + * + * @return array Array of user ids + */ + public function fetch_users_approver_expensereport() + { + // phpcs:enable + $users_validator = array(); - $sql = "SELECT DISTINCT ur.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - $sql .= "UNION"; - $sql .= " SELECT DISTINCT ugu.fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; - $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; - //print $sql; + $sql = "SELECT DISTINCT ur.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + $sql .= "UNION"; + $sql .= " SELECT DISTINCT ugu.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd"; + $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve'; + //print $sql; - dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); - $result = $this->db->query($sql); - if ($result) - { - $num_rows = $this->db->num_rows($result); $i = 0; - while ($i < $num_rows) - { - $objp = $this->db->fetch_object($result); - array_push($users_validator, $objp->fk_user); - $i++; - } - return $users_validator; - } else { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); - return -1; - } - } + dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); + $result = $this->db->query($sql); + if ($result) + { + $num_rows = $this->db->num_rows($result); $i = 0; + while ($i < $num_rows) + { + $objp = $this->db->fetch_object($result); + array_push($users_validator, $objp->fk_user); + $i++; + } + return $users_validator; + } else { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR); + return -1; + } + } - /** - * Create a document onto disk accordign to template module. - * - * @param string $modele Force le mnodele a utiliser ('' to not force) - * @param Translate $outputlangs objet lang a utiliser pour traduction - * @param int $hidedetails Hide details of lines - * @param int $hidedesc Hide description - * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information - * @return int 0 if KO, 1 if OK - */ - public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) - { - global $conf, $langs; + /** + * Create a document onto disk accordign to template module. + * + * @param string $modele Force le mnodele a utiliser ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; - $langs->load("trips"); + $langs->load("trips"); - if (!dol_strlen($modele)) { - $modele = 'standard'; + if (!dol_strlen($modele)) { + $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; - } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { - $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; - } - } + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { + $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; + } + } - $modelpath = "core/modules/expensereport/doc/"; + $modelpath = "core/modules/expensereport/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - } + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } - /** - * List of types - * - * @param int $active Active or not - * @return array - */ - public function listOfTypes($active = 1) - { - global $langs; - $ret = array(); - $sql = "SELECT id, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; - $sql .= " WHERE active = ".$active; - dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - 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++; - } - } else { - dol_print_error($this->db); - } - return $ret; - } + /** + * List of types + * + * @param int $active Active or not + * @return array + */ + public function listOfTypes($active = 1) + { + global $langs; + $ret = array(); + $sql = "SELECT id, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees"; + $sql .= " WHERE active = ".$active; + dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + 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++; + } + } else { + dol_print_error($this->db); + } + return $ret; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Charge indicateurs this->nb pour le tableau de bord - * - * @return int <0 if KO, >0 if OK - */ - public function load_state_board() - { - // phpcs:enable - global $conf, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge indicateurs this->nb pour le tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + public function load_state_board() + { + // phpcs:enable + global $conf, $user; - $this->nb = array(); + $this->nb = array(); - $sql = "SELECT count(ex.rowid) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - $sql .= " WHERE ex.fk_statut > 0"; - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + $sql = "SELECT count(ex.rowid) as nb"; + $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)) { $userchildids = $user->getAllChildIds(1); @@ -2235,145 +2255,145 @@ class ExpenseReport extends CommonObject $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; } - $resql = $this->db->query($sql); - if ($resql) { - while ($obj = $this->db->fetch_object($resql)) { - $this->nb["expensereports"] = $obj->nb; - } - $this->db->free($resql); - return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + $this->nb["expensereports"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param string $option 'topay' or 'toapprove' - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - public function load_board($user, $option = 'topay') - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param string $option 'topay' or 'toapprove' + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user, $option = 'topay') + { + // 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(); + $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 = 2"; - else $sql .= " WHERE ex.fk_statut = 5"; - $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + $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; + $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; + 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) - { - $langs->load("trips"); + $resql = $this->db->query($sql); + if ($resql) + { + $langs->load("trips"); - $response = new WorkboardResponse(); - if ($option == 'toapprove') - { - $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToApprove"); - $response->labelShort = $langs->trans("ToApprove"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2'; - } else { - $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("ExpenseReportsToPay"); - $response->labelShort = $langs->trans("StatusToPay"); - $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5'; - } - $response->img = img_object('', "trip"); + $response = new WorkboardResponse(); + if ($option == 'toapprove') + { + $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToApprove"); + $response->labelShort = $langs->trans("ToApprove"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut='.self::STATUS_VALIDATED; + } else { + $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("ExpenseReportsToPay"); + $response->labelShort = $langs->trans("StatusToPay"); + $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut='.self::STATUS_APPROVED; + } + $response->img = img_object('', "trip"); - while ($obj = $this->db->fetch_object($resql)) - { - $response->nbtodo++; + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; - if ($option == 'toapprove') - { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { - $response->nbtodolate++; - } - } else { - if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) { - $response->nbtodolate++; - } - } - } + if ($option == 'toapprove') + { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { + $response->nbtodolate++; + } + } else { + if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) { + $response->nbtodolate++; + } + } + } - return $response; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } + return $response; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - /** - * Return if an expense report is late or not - * - * @param string $option 'topay' or 'toapprove' - * @return boolean True if late, False if not late - */ - public function hasDelay($option) - { - global $conf; + /** + * Return if an expense report is late or not + * + * @param string $option 'topay' or 'toapprove' + * @return boolean True if late, False if not late + */ + public function hasDelay($option) + { + global $conf; - // Only valid expenses reports - if ($option == 'toapprove' && $this->status != 2) return false; - if ($option == 'topay' && $this->status != 5) return false; + // Only valid expenses reports + if ($option == 'toapprove' && $this->status != 2) return false; + if ($option == 'topay' && $this->status != 5) return false; - $now = dol_now(); - if ($option == 'toapprove') - { - return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); - } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); - } + $now = dol_now(); + if ($option == 'toapprove') + { + return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay); + } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay); + } - /** - * Return if an expensereport was dispatched into bookkeeping - * - * @return int <0 if KO, 0=no, 1=yes - */ - public function getVentilExportCompta() - { - $alreadydispatched = 0; + /** + * Return if an expensereport was dispatched into bookkeeping + * + * @return int <0 if KO, 0=no, 1=yes + */ + public function getVentilExportCompta() + { + $alreadydispatched = 0; - $type = 'expense_report'; + $type = 'expense_report'; - $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $alreadydispatched = $obj->nb; - } - } else { - $this->error = $this->db->lasterror(); - return -1; - } + $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) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $alreadydispatched = $obj->nb; + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } - if ($alreadydispatched) - { - return 1; - } - return 0; - } + if ($alreadydispatched) + { + return 1; + } + return 0; + } /** * Return amount of payments already done @@ -2409,174 +2429,174 @@ class ExpenseReport extends CommonObject */ class ExpenseReportLine { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - /** + /** * @var string Error code (or message) */ public $error = ''; - /** + /** * @var int ID */ public $rowid; - public $comments; - public $qty; - public $value_unit; - public $date; + public $comments; + public $qty; + public $value_unit; + public $date; - /** - * @var int ID - */ - public $fk_c_type_fees; + /** + * @var int ID + */ + public $fk_c_type_fees; - /** - * @var int ID - */ - public $fk_c_exp_tax_cat; + /** + * @var int ID + */ + public $fk_c_exp_tax_cat; - /** - * @var int ID - */ - public $fk_projet; + /** + * @var int ID + */ + public $fk_projet; - /** - * @var int ID - */ - public $fk_expensereport; + /** + * @var int ID + */ + public $fk_expensereport; - public $type_fees_code; - public $type_fees_libelle; + public $type_fees_code; + public $type_fees_libelle; - public $projet_ref; - public $projet_title; + public $projet_ref; + public $projet_title; - public $vatrate; - public $total_ht; - public $total_tva; - public $total_ttc; + public $vatrate; + public $total_ht; + public $total_tva; + public $total_ttc; - /** - * @var int ID into llx_ecm_files table to link line to attached file - */ - public $fk_ecm_files; + /** + * @var int ID into llx_ecm_files table to link line to attached file + */ + public $fk_ecm_files; - /** - * Constructor - * - * @param DoliDB $db Handlet database - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Handlet database + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Fetch record for expense report detailed line - * - * @param int $rowid Id of object to load - * @return int <0 if KO, >0 if OK - */ - public function fetch($rowid) - { - $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,'; - $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,'; - $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; - $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here. - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; - $sql .= ' WHERE fde.rowid = '.$rowid; + /** + * Fetch record for expense report detailed line + * + * @param int $rowid Id of object to load + * @return int <0 if KO, >0 if OK + */ + public function fetch($rowid) + { + $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,'; + $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,'; + $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,'; + $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here. + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid'; + $sql .= ' WHERE fde.rowid = '.$rowid; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - $objp = $this->db->fetch_object($result); + if ($result) + { + $objp = $this->db->fetch_object($result); - $this->rowid = $objp->rowid; - $this->id = $objp->rowid; - $this->ref = $objp->ref; - $this->fk_expensereport = $objp->fk_expensereport; - $this->comments = $objp->comments; - $this->qty = $objp->qty; - $this->date = $objp->date; - $this->dates = $this->db->jdate($objp->date); - $this->value_unit = $objp->value_unit; - $this->fk_c_type_fees = $objp->fk_c_type_fees; - $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; - $this->fk_projet = $objp->fk_project; // deprecated - $this->fk_project = $objp->fk_project; - $this->type_fees_code = $objp->type_fees_code; - $this->type_fees_libelle = $objp->type_fees_libelle; - $this->projet_ref = $objp->projet_ref; - $this->projet_title = $objp->projet_title; - $this->vatrate = $objp->vatrate; - $this->vat_src_code = $objp->vat_src_code; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; - $this->fk_ecm_files = $objp->fk_ecm_files; + $this->rowid = $objp->rowid; + $this->id = $objp->rowid; + $this->ref = $objp->ref; + $this->fk_expensereport = $objp->fk_expensereport; + $this->comments = $objp->comments; + $this->qty = $objp->qty; + $this->date = $objp->date; + $this->dates = $this->db->jdate($objp->date); + $this->value_unit = $objp->value_unit; + $this->fk_c_type_fees = $objp->fk_c_type_fees; + $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat; + $this->fk_projet = $objp->fk_project; // deprecated + $this->fk_project = $objp->fk_project; + $this->type_fees_code = $objp->type_fees_code; + $this->type_fees_libelle = $objp->type_fees_libelle; + $this->projet_ref = $objp->projet_ref; + $this->projet_title = $objp->projet_title; + $this->vatrate = $objp->vatrate; + $this->vat_src_code = $objp->vat_src_code; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; + $this->fk_ecm_files = $objp->fk_ecm_files; - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - /** - * insert - * - * @param int $notrigger 1=No trigger - * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object - * @return int <0 if KO, >0 if OK - */ - public function insert($notrigger = 0, $fromaddline = false) - { - global $langs, $user, $conf; + /** + * insert + * + * @param int $notrigger 1=No trigger + * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object + * @return int <0 if KO, >0 if OK + */ + public function insert($notrigger = 0, $fromaddline = false) + { + global $langs, $user, $conf; - $error = 0; + $error = 0; - dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG); + dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG); - // Clean parameters - $this->comments = trim($this->comments); - if (!$this->value_unit_HT) $this->value_unit_HT = 0; - $this->qty = price2num($this->qty); - $this->vatrate = price2num($this->vatrate); + // Clean parameters + $this->comments = trim($this->comments); + if (!$this->value_unit_HT) $this->value_unit_HT = 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; - $this->db->begin(); + $this->db->begin(); - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; - $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; - $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; - $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; - $sql .= " ".$this->db->escape($this->fk_c_type_fees).","; - $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).","; - $sql .= " ".$this->db->escape($this->vatrate).","; - $sql .= " '".$this->db->escape($this->vat_src_code)."',"; - $sql .= " '".$this->db->escape($this->comments)."',"; - $sql .= " ".$this->db->escape($this->qty).","; - $sql .= " ".$this->db->escape($this->value_unit).","; - $sql .= " ".$this->db->escape($this->total_ht).","; - $sql .= " ".$this->db->escape($this->total_tva).","; - $sql .= " ".$this->db->escape($this->total_ttc).","; - $sql .= " '".$this->db->idate($this->date)."',"; + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det'; + $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,'; + $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)'; + $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).","; + $sql .= " ".$this->db->escape($this->fk_c_type_fees).","; + $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).","; + $sql .= " ".$this->db->escape($this->vatrate).","; + $sql .= " '".$this->db->escape($this->vat_src_code)."',"; + $sql .= " '".$this->db->escape($this->comments)."',"; + $sql .= " ".$this->db->escape($this->qty).","; + $sql .= " ".$this->db->escape($this->value_unit).","; + $sql .= " ".$this->db->escape($this->total_ht).","; + $sql .= " ".$this->db->escape($this->total_tva).","; + $sql .= " ".$this->db->escape($this->total_ttc).","; + $sql .= " '".$this->db->idate($this->date)."',"; $sql .= " '".$this->db->escape($this->rule_warning_message)."',"; $sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).","; $sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); - $sql .= ")"; + $sql .= ")"; - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); if (!$fromaddline) { @@ -2590,21 +2610,21 @@ class ExpenseReportLine $this->errors = $tmpparent->errors; } } - } else { + } else { $error++; } - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } /** * Function to get total amount in expense reports for a same rule @@ -2646,161 +2666,81 @@ class ExpenseReportLine return $amount + $this->total_ttc; } - /** - * Update line - * - * @param User $user User - * @return int <0 if KO, >0 if OK - */ - public function update(User $user) - { - global $langs, $conf; + /** + * Update line + * + * @param User $user User + * @return int <0 if KO, >0 if OK + */ + public function update(User $user) + { + global $langs, $conf; - $error = 0; + $error = 0; - // Clean parameters - $this->comments = trim($this->comments); - $this->vatrate = price2num($this->vatrate); - $this->value_unit = price2num($this->value_unit); + // Clean parameters + $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; - $this->db->begin(); + $this->db->begin(); - // Update line in database - $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; - $sql .= " comments='".$this->db->escape($this->comments)."'"; - $sql .= ",value_unit=".$this->db->escape($this->value_unit); - $sql .= ",qty=".$this->db->escape($this->qty); - $sql .= ",date='".$this->db->idate($this->date)."'"; - $sql .= ",total_ht=".$this->db->escape($this->total_ht).""; - $sql .= ",total_tva=".$this->db->escape($this->total_tva).""; - $sql .= ",total_ttc=".$this->db->escape($this->total_ttc).""; - $sql .= ",tva_tx=".$this->db->escape($this->vatrate); + // Update line in database + $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET"; + $sql .= " comments='".$this->db->escape($this->comments)."'"; + $sql .= ",value_unit=".$this->db->escape($this->value_unit); + $sql .= ",qty=".$this->db->escape($this->qty); + $sql .= ",date='".$this->db->idate($this->date)."'"; + $sql .= ",total_ht=".$this->db->escape($this->total_ht).""; + $sql .= ",total_tva=".$this->db->escape($this->total_tva).""; + $sql .= ",total_ttc=".$this->db->escape($this->total_ttc).""; + $sql .= ",tva_tx=".$this->db->escape($this->vatrate); $sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'"; - $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; + $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"; - $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); + 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); + dol_syslog("ExpenseReportLine::update sql=".$sql); - $resql = $this->db->query($sql); - if ($resql) - { - $tmpparent = new ExpenseReport($this->db); - $result = $tmpparent->fetch($this->fk_expensereport); - if ($result > 0) - { - $result = $tmpparent->update_price(); - if ($result < 0) - { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - $this->error = $tmpparent->error; - $this->errors = $tmpparent->errors; - } - } else { - $error++; - dol_print_error($this->db); - } + $resql = $this->db->query($sql); + if ($resql) + { + $tmpparent = new ExpenseReport($this->db); + $result = $tmpparent->fetch($this->fk_expensereport); + if ($result > 0) + { + $result = $tmpparent->update_price(); + if ($result < 0) + { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } else { + $error++; + $this->error = $tmpparent->error; + $this->errors = $tmpparent->errors; + } + } else { + $error++; + dol_print_error($this->db); + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } -} - - -/** - * Retourne la liste deroulante des differents etats d'une note de frais. - * Les valeurs de la liste sont les id de la table c_expensereport_statuts - * - * @param int $selected preselect status - * @param string $htmlname Name of HTML select - * @param int $useempty 1=Add empty line - * @param int $useshortlabel Use short labels - * @return string HTML select with status - */ -function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $useempty = 1, $useshortlabel = 0) -{ - global $db, $langs; - - $tmpep = new ExpenseReport($db); - - print ''; -} - -/** - * Return list of types of notes with select value = id - * - * @param int $selected Preselected type - * @param string $htmlname Name of field in form - * @param int $showempty Add an empty field - * @param int $active 1=Active only, 0=Unactive only, -1=All - * @return string Select html - */ -function select_type_fees_id($selected = '', $htmlname = 'type', $showempty = 0, $active = 1) -{ - global $db, $langs, $user; - $langs->load("trips"); - - print ''; + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/expensereport/class/expensereportstats.class.php b/htdocs/expensereport/class/expensereportstats.class.php index f400d5e4277..174c2be4ccf 100644 --- a/htdocs/expensereport/class/expensereportstats.class.php +++ b/htdocs/expensereport/class/expensereportstats.class.php @@ -136,7 +136,7 @@ class ExpenseReportStats extends Stats { $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, sum(".$this->field.")"; $sql .= " FROM ".$this->from; - $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'"; + $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$this->db->escape($year)."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -156,7 +156,7 @@ class ExpenseReportStats extends Stats { $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, avg(".$this->field.")"; $sql .= " FROM ".$this->from; - $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'"; + $sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$this->db->escape($year)."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); diff --git a/htdocs/expensereport/document.php b/htdocs/expensereport/document.php index 82ac70b7ccb..6814c0a5b0d 100644 --- a/htdocs/expensereport/document.php +++ b/htdocs/expensereport/document.php @@ -39,9 +39,11 @@ $langs->loadLangs(array("other", "trips", "companies", "interventions")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); +$childids = $user->getAllChildIds(1); + // Security check if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); @@ -49,8 +51,8 @@ $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -61,7 +63,10 @@ if (!$sortfield) $sortfield = "position_name"; $object = new ExpenseReport($db); -$object->fetch($id, $ref); +if (!$object->fetch($id, $ref) > 0) +{ + dol_print_error($db); +} $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); $modulepart = 'trip'; @@ -69,6 +74,18 @@ $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) +{ + // 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) + { + accessforbidden(); + } +} + /* * Actions diff --git a/htdocs/expensereport/info.php b/htdocs/expensereport/info.php index b52680ad215..0b50a69071f 100644 --- a/htdocs/expensereport/info.php +++ b/htdocs/expensereport/info.php @@ -31,11 +31,33 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; // Load translation files required by the page $langs->load("trips"); -// Security check $id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); + +$childids = $user->getAllChildIds(1); + +// Security check if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); +$object = new ExpenseReport($db); +if (!$object->fetch($id, $ref) > 0) +{ + dol_print_error($db); +} + +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) + { + accessforbidden(); + } +} + /* * View diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index a21ed4d6612..0a264c59a2a 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formexpensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php'; @@ -74,8 +75,8 @@ $diroutputmassaction = $conf->expensereport->dir_output.'/temp/massgeneration/'. // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -199,48 +200,6 @@ if (empty($reshook)) $permissiontodelete = $user->rights->expensereport->supprimer; $uploaddir = $conf->expensereport->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.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 (!$error) - { - $objectuser->fetch($id); - - $objectuser->oldcopy = clone $objectuser; - - $db->begin(); - - $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 && !count($objectuser->errors)) { - setEventMessages($langs->trans("UserModified"), null, 'mesgs'); - $db->commit(); - } else { - $db->rollback(); - } - } - } - } } @@ -251,6 +210,7 @@ if (empty($reshook)) $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); +$formexpensereport = new FormExpenseReport($db); $fuser = new User($db); @@ -302,7 +262,7 @@ if ($search_amount_ttc != '') $sql .= natural_search('d.total_ttc', $search_amou // 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->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))) @@ -385,71 +345,22 @@ if ($resql) dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin); - print '
    '; - print '
    '; - - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { - print ''; - - if ($action == 'edit') - { - print ''; - print ''; - - print ''; - print ''; - } else { - print ''; - print ''; - - print ''; - print ''; - } - - print '
    '.$langs->trans("DefaultCategoryCar").''; - print $form->selectExpenseCategories($fuser->default_c_exp_tax_cat, 'default_c_exp_tax_cat', 1); - print '
    '.$langs->trans("DefaultRangeNumber").''; - $maxRangeNum = ExpenseReportIk::getMaxRangeNumber($fuser->default_c_exp_tax_cat); - print $form->selectarray('default_range', range(0, $maxRangeNum), $fuser->default_range); - print '
    '.$langs->trans("DefaultCategoryCar").''; - print dol_getIdFromCode($db, $fuser->default_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label'); - print '
    '.$langs->trans("DefaultRangeNumber").''; - print $fuser->default_range; - print '
    '; - } - - print '
    '; - - /*if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) - { - print '
    '; - - print '
    '; - - showMyBalance($holiday, $user_id); - }*/ - dol_fiche_end(); if ($action != 'edit') { print '
    '; - if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) - { - print ''.$langs->trans("Modify").''; - } - $childids = $user->getAllChildIds(1); $canedit = ((in_array($user_id, $childids) && $user->rights->expensereport->creer) || ($conf->global->MAIN_USE_ADVANCED_PERMS && $user->rights->expensereport->writeall_advance)); // Buttons for actions - if ($canedit) - { + if ($canedit) { print ''.$langs->trans("AddTrip").''; + } else { + print ''.$langs->trans("AddTrip").''; } print '
    '; @@ -461,11 +372,9 @@ if ($resql) } else { $title = $langs->trans("ListTripsAndExpenses"); - $newcardbutton = ''; - if ($user->rights->expensereport->creer) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewTrip'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/expensereport/card.php?action=create'); - } + $url = DOL_URL_ROOT.'/expensereport/card.php?action=create'; + 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); } @@ -599,7 +508,7 @@ if ($resql) if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''; - select_expensereport_statut($search_status, 'search_status', 1, 1); + $formexpensereport->selectExpensereportStatus($search_status, 'search_status', 1, 1); print ''; } // Action column diff --git a/htdocs/expensereport/note.php b/htdocs/expensereport/note.php index 8447fd4fcbc..171e8980fab 100644 --- a/htdocs/expensereport/note.php +++ b/htdocs/expensereport/note.php @@ -35,7 +35,9 @@ $langs->loadLangs(array('trips', 'companies', 'bills', 'orders')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); + +$childids = $user->getAllChildIds(1); // Security check $socid = 0; @@ -51,6 +53,18 @@ if (!$object->fetch($id, $ref) > 0) $permissionnote = $user->rights->expensereport->creer; // Used by the include of actions_setnotes.inc.php +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) + { + accessforbidden(); + } +} + /* * Actions diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php index 3e8da949bff..9bc50341973 100644 --- a/htdocs/expensereport/payment/card.php +++ b/htdocs/expensereport/payment/card.php @@ -94,7 +94,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->expensere $outputlangs->setDefaultLang($_REQUEST['lang_id']); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $fac->generateDocument($fac->modelpdf, $outputlangs); + $fac->generateDocument($fac->model_pdf, $outputlangs); } } @@ -293,7 +293,7 @@ if ($action == '') { if (!$disable_delete) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } diff --git a/htdocs/expensereport/payment/info.php b/htdocs/expensereport/payment/info.php index 4a5cd165fc5..b548eb54be2 100644 --- a/htdocs/expensereport/payment/info.php +++ b/htdocs/expensereport/payment/info.php @@ -34,7 +34,7 @@ $langs->loadLangs(array('bills', 'trips')); $id = GETPOST('id'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); /* diff --git a/htdocs/expensereport/payment/payment.php b/htdocs/expensereport/payment/payment.php index 00d690f20d5..c17f3ec10ee 100644 --- a/htdocs/expensereport/payment/payment.php +++ b/htdocs/expensereport/payment/payment.php @@ -119,7 +119,7 @@ if ($action == 'add_payment') $payment->total = $total; $payment->fk_typepayment = GETPOST("fk_typepayment", 'int'); $payment->num_payment = GETPOST("num_payment", 'alphanothtml'); - $payment->note_public = GETPOST("note_public", 'none'); + $payment->note_public = GETPOST("note_public", 'restricthtml'); if (!$error) { diff --git a/htdocs/expensereport/stats/index.php b/htdocs/expensereport/stats/index.php index eff10cd9323..2079a2bf045 100644 --- a/htdocs/expensereport/stats/index.php +++ b/htdocs/expensereport/stats/index.php @@ -75,7 +75,7 @@ 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->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),...) diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php index e04b8f20dfb..89ae2103476 100644 --- a/htdocs/exports/class/export.class.php +++ b/htdocs/exports/class/export.class.php @@ -338,7 +338,7 @@ class Export } break; default: - dol_syslog("Error we try to forge an sql export request with a condition on a field with type '".$InfoFieldList[0]."' (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR); + dol_syslog("Error we try to forge an sql export request with a condition on a field with type ".$InfoFieldList[0]." (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR); } return $szFilterQuery; @@ -539,6 +539,7 @@ class Export if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) { $this->error = "ErrorBadParameter"; + dol_syslog($this->error, LOG_ERR); return -1; } @@ -705,10 +706,10 @@ class Export $sql .= 'filter'; $sql .= ') VALUES ('; $sql .= "'".$this->db->escape($this->model_name)."',"; - $sql .= "'".$this->db->escape($this->datatoexport)."',"; - $sql .= "'".$this->db->escape($this->hexa)."',"; - $sql .= "'".$user->id."',"; - $sql .= "'".$this->db->escape($this->hexafiltervalue)."'"; + $sql .= " '".$this->db->escape($this->datatoexport)."',"; + $sql .= " '".$this->db->escape($this->hexa)."',"; + $sql .= ' '.($user->id > 0 ? $user->id : 'null').","; + $sql .= " '".$this->db->escape($this->hexafiltervalue)."'"; $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -735,7 +736,7 @@ class Export { $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter'; $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em'; - $sql .= ' WHERE em.rowid = '.$id; + $sql .= ' WHERE em.rowid = '.((int) $id); dol_syslog("Export::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -844,7 +845,7 @@ class Export } // suppression de l'export print ''; - print 'rowid.'">'; + print 'rowid.'">'; print img_delete(); print ''; print ""; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index 98353d42bf1..d7075d86e1b 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -130,7 +130,7 @@ $entitytolang = array( $array_selected = isset($_SESSION["export_selected_fields"]) ? $_SESSION["export_selected_fields"] : array(); $array_filtervalue = isset($_SESSION["export_filtered_fields"]) ? $_SESSION["export_filtered_fields"] : array(); $datatoexport = GETPOST("datatoexport", "aZ09"); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $step = GETPOST("step", "int") ?GETPOST("step", "int") : 1; $export_name = GETPOST("export_name", "alphanohtml"); @@ -302,9 +302,9 @@ if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes') if ($action == 'deleteprof') { - if ($_GET["id"]) + if (GETPOST("id", 'int')) { - $objexport->fetch($_GET["id"]); + $objexport->fetch(GETPOST('id', 'int')); $result = $objexport->delete($user); } } @@ -459,7 +459,7 @@ if ($step == 1 || !$datatoexport) print ''; if ($objexport->array_export_perms[$key]) { - print ''.img_picto($langs->trans("NewExport"), 'filenew').''; + print ''.img_picto($langs->trans("NewExport"), 'next', 'class="fa-15x"').''; } else { print $langs->trans("NotEnoughPermissions"); } @@ -1054,13 +1054,13 @@ if ($step == 4 && $datatoexport) print ''; print ''; - print ''; + print ''; print ''; // List of existing export profils $sql = "SELECT rowid, label"; $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql .= " WHERE type = '".$datatoexport."'"; + $sql .= " WHERE type = '".$db->escape($datatoexport)."'"; if (empty($conf->global->EXPORTS_SHARE_MODELS))$sql .= " AND fk_user=".$user->id; $sql .= " ORDER BY rowid"; $resql = $db->query($sql); @@ -1074,14 +1074,14 @@ if ($step == 4 && $datatoexport) print ''; print $obj->label; print ''; - print 'rowid.'">'; + print 'rowid.'">'; print img_delete(); print ''; print ''; $i++; } } else { - dol_print_error($this->db); + dol_print_error($db); } print ''; diff --git a/htdocs/externalsite/admin/externalsite.php b/htdocs/externalsite/admin/externalsite.php index e2af9e5267d..cb73403356b 100644 --- a/htdocs/externalsite/admin/externalsite.php +++ b/htdocs/externalsite/admin/externalsite.php @@ -40,7 +40,7 @@ $langs->loadLangs(array('admin', 'other', 'externalsite')); $def = array(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Sauvegardes parametres if ($action == 'update') @@ -50,7 +50,7 @@ if ($action == 'update') $db->begin(); $label = GETPOST('EXTERNALSITE_LABEL', 'alpha'); - $exturl = GETPOST('EXTERNALSITE_URL', 'none'); + $exturl = GETPOST('EXTERNALSITE_URL', 'restricthtml'); $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); @@ -101,7 +101,7 @@ print ""; print ''; print ''.$langs->trans("ExternalSiteURL").""; print ''; print "http://localhost/myurl/"; print "
    https://wikipedia.org/"; diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php index 5199e9de0db..c19bce3c9d1 100644 --- a/htdocs/fichinter/admin/fichinter_extrafields.php +++ b/htdocs/fichinter/admin/fichinter_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'fichinter'; //Must be the $element of the class that manage extrafield diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php index 62dc9025209..768de47cfd0 100644 --- a/htdocs/fichinter/admin/fichinterdet_extrafields.php +++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php @@ -41,7 +41,7 @@ $tmptype2label = ExtraFields::$type2label; $type2label = array(''); foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'fichinterdet'; //Must be the $element of the class that manage extrafield diff --git a/htdocs/fichinter/card-rec.php b/htdocs/fichinter/card-rec.php index 55ad529df3b..b8ff3714596 100644 --- a/htdocs/fichinter/card-rec.php +++ b/htdocs/fichinter/card-rec.php @@ -51,7 +51,7 @@ $langs->loadLangs(array("interventions", "admin", "compta", "bills")); // Security check $id = (GETPOST('fichinterid', 'int') ?GETPOST('fichinterid', 'int') : GETPOST('id', 'int')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); if ($user->socid) $socid = $user->socid; $objecttype = 'fichinter_rec'; if ($action == "create" || $action == "add") $objecttype = ''; @@ -131,7 +131,7 @@ if ($action == 'add') { if (!$error) { $object->id_origin = $id; $object->title = GETPOST('titre', 'alpha'); - $object->description = GETPOST('description', 'alpha'); + $object->description = GETPOST('description', 'restricthtml'); $object->socid = GETPOST('socid', 'alpha'); $object->fk_project = GETPOST('projectid', 'int'); $object->fk_contract = GETPOST('contractid', 'int'); @@ -714,14 +714,14 @@ if ($action == 'create') { if ($user->rights->ficheinter->creer) { print ''; } if ($user->rights->ficheinter->supprimer) { print ''; } print '
    '; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index ed01164b3df..e4afe4b0452 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -2,7 +2,7 @@ /* Copyright (C) 2002-2007 Rodolphe Quiedeville * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2018 Regis Houssin - * Copyright (C) 2011-2017 Juanjo Menent + * Copyright (C) 2011-2020 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2018 Ferran Marcet * Copyright (C) 2014-2018 Charlene Benke @@ -65,7 +65,7 @@ $confirm = GETPOST('confirm', 'alpha'); $mesg = GETPOST('msg', 'alpha'); $origin = GETPOST('origin', 'alpha'); $originid = (GETPOST('originid', 'int') ?GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility -$note_public = GETPOST('note_public', 'none'); +$note_public = GETPOST('note_public', 'restricthtml'); $lineid = GETPOST('line_id', 'int'); //PDF @@ -167,13 +167,13 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs); + $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->model_pdf : GETPOST('model', 'alpha'), $outputlangs); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { - $mesg = '
    '.$object->error.'
    '; + $mesg = $object->error; } } elseif ($action == 'confirm_modify' && $confirm == 'yes' && $user->rights->ficheinter->creer) { @@ -192,26 +192,26 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs); + $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->model_pdf : GETPOST('model', 'alpha'), $outputlangs); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { - $mesg = '
    '.$object->error.'
    '; + $mesg = $object->error; } } elseif ($action == 'add' && $user->rights->ficheinter->creer) { - $object->socid = $socid; - $object->duration = GETPOST('duration', 'int'); - $object->fk_project = GETPOST('projectid', 'int'); - $object->fk_contrat = GETPOST('contratid', 'int'); - $object->author = $user->id; - $object->description = GETPOST('description', 'none'); - $object->ref = $ref; - $object->modelpdf = GETPOST('model', 'alpha'); - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); + $object->socid = $socid; + $object->duration = GETPOST('duration', 'int'); + $object->fk_project = GETPOST('projectid', 'int'); + $object->fk_contrat = GETPOST('contratid', 'int'); + $object->author = $user->id; + $object->description = GETPOST('description', 'restricthtml'); + $object->ref = $ref; + $object->model_pdf = GETPOST('model', 'alpha'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); if ($object->socid > 0) { @@ -251,7 +251,7 @@ if (empty($reshook)) $extrafields = new ExtraFields($db); $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; $id = $object->create($user); @@ -356,12 +356,12 @@ if (empty($reshook)) $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); if ($result < 0) { @@ -371,51 +371,51 @@ if (empty($reshook)) } } } - } else { - $mesg = $srcobject->error; - $error++; - } - } else { - $mesg = $object->error; - $error++; - } - } else { - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) { - $error++; - $action = 'create'; - } + } else { + $mesg = $srcobject->error; + $error++; + } + } else { + $mesg = $object->error; + $error++; + } + } else { + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) { + $error++; + $action = 'create'; + } - if (!$error) - { - // Extrafields - $array_options = $extrafields->getOptionalsFromPost($object->table_element); + if (!$error) + { + // Extrafields + $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; - $result = $object->create($user); - if ($result > 0) - { - $id = $result; // Force raffraichissement sur fiche venant d'etre cree - } else { - $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; - } - } - } - } else { - $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")).'
    '; - $action = 'create'; - } + $result = $object->create($user); + if ($result > 0) + { + $id = $result; // Force raffraichissement sur fiche venant d'etre cree + } else { + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } + } + } else { + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")); + $action = 'create'; + } } elseif ($action == 'update' && $user->rights->ficheinter->creer) { $object->socid = $socid; $object->fk_project = GETPOST('projectid', 'int'); $object->fk_contrat = GETPOST('contratid', 'int'); $object->author = $user->id; - $object->description = GETPOST('description', 'alpha'); + $object->description = GETPOST('description', 'restricthtml'); $object->ref = $ref; $result = $object->update($user); @@ -454,26 +454,26 @@ if (empty($reshook)) // Add line elseif ($action == "addline" && $user->rights->ficheinter->creer) { - if (!GETPOST('np_desc', 'none') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) + if (!GETPOST('np_desc', 'restricthtml') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")).'
    '; + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")); $error++; } if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) { - $mesg = '
    '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")).'
    '; + $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")); $error++; } if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) { - $mesg = '
    '.$langs->trans("ErrorValueTooHigh").'
    '; + $mesg = $langs->trans("ErrorValueTooHigh"); $error++; } if (!$error) { $db->begin(); - $desc = GETPOST('np_desc', 'none'); + $desc = GETPOST('np_desc', 'restricthtml'); $date_intervention = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); $duration = empty($conf->global->FICHINTER_WITHOUT_DURATION) ?convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')) : 0; @@ -482,14 +482,14 @@ if (empty($reshook)) $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options = $extrafields->getOptionalsFromPost($object->table_element_line); - $result = $object->addline( + $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); // Define output language $outputlangs = $langs; @@ -506,7 +506,7 @@ if (empty($reshook)) { $db->commit(); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $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 { @@ -538,21 +538,35 @@ if (empty($reshook)) header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { - $mesg = '
    '.$object->error.'
    '; + $mesg = $object->error; } } // Classify Done elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { - $result = $object->setStatut(3); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setStatut(3); + 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) + { + $result = $object->setStatut(Fichinter::STATUS_VALIDATED); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else { + $mesg = $object->error; + } } /* @@ -573,13 +587,13 @@ if (empty($reshook)) } $object->fetch_thirdparty(); - $desc = GETPOST('np_desc'); + $desc = GETPOST('np_desc', 'restricthtml'); $date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); $duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')); - $objectline->datei = $date_inter; - $objectline->desc = $desc; - $objectline->duration = $duration; + $objectline->datei = $date_inter; + $objectline->desc = $desc; + $objectline->duration = $duration; // Extrafields $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -587,11 +601,11 @@ if (empty($reshook)) $objectline->array_options = $array_options; $result = $objectline->update($user); - if ($result < 0) - { - dol_print_error($db); - exit; - } + if ($result < 0) + { + dol_print_error($db); + exit; + } // Define output language $outputlangs = $langs; @@ -603,7 +617,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $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; @@ -638,7 +652,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); } /* @@ -658,7 +672,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $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; @@ -676,7 +690,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $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; @@ -701,7 +715,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -735,9 +749,9 @@ if (empty($reshook)) if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
    '.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
    '; + $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); } else { - $mesg = '
    '.$object->error.'
    '; + $mesg = $object->error; } } } @@ -784,7 +798,11 @@ if ($action == 'create') print load_fiche_titre($langs->trans("AddIntervention"), '', 'intervention'); - dol_htmloutput_mesg($mesg); + if ($error > 0) { + dol_htmloutput_errors($mesg); + } else { + dol_htmloutput_mesg($mesg); + } if ($socid) $res = $soc->fetch($socid); @@ -799,11 +817,11 @@ if ($action == 'create') $subelement = $regs[2]; } - if ($element == 'project') - { - $projectid = GETPOST('originid', 'int'); - } else { - // For compatibility + if ($element == 'project') + { + $projectid = GETPOST('originid', 'int'); + } else { + // For compatibility if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } @@ -830,8 +848,8 @@ if ($action == 'create') $soc = $objectsrc->thirdparty; - $note_private = (!empty($objectsrc->note) ? $objectsrc->note : (!empty($objectsrc->note_private) ? $objectsrc->note_private : GETPOST('note_private', 'none'))); - $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : GETPOST('note_public', 'none')); + $note_private = (!empty($objectsrc->note) ? $objectsrc->note : (!empty($objectsrc->note_private) ? $objectsrc->note_private : GETPOST('note_private', 'restricthtml'))); + $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : GETPOST('note_public', 'restricthtml')); // Object source contacts list $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1); @@ -886,27 +904,27 @@ if ($action == 'create') $langs->load("project"); - print ''.$langs->trans("Project").''; - /* 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 + print ''.$langs->trans("Project").''; + /* 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'); */ - $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); - if ($numprojet == 0) - { - print '   '; - } - print ''; - } + $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); + if ($numprojet == 0) + { + print '   '; + } + print ''; + } // Contract if ($conf->contrat->enabled) { $langs->load("contracts"); print ''.$langs->trans("Contract").''; - $numcontrat = $formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1); + $numcontrat = $formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1, 1); if ($numcontrat == 0) { print '   '; @@ -914,53 +932,53 @@ if ($action == 'create') print ''; } - // Model - print ''; - print ''.$langs->trans("DefaultModel").''; - print ''; - $liste = ModelePDFFicheinter::liste_modeles($db); - print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); - print ""; + // Model + print ''; + print ''.$langs->trans("DefaultModel").''; + print ''; + $liste = ModelePDFFicheinter::liste_modeles($db); + print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); + print ""; - // Public note - print ''; - print ''.$langs->trans('NotePublic').''; - print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; + // Public note + print ''; + print ''.$langs->trans('NotePublic').''; + print ''; + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''.$langs->trans('NotePrivate').''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; - } + // Private note + if (empty($user->socid)) + { + print ''; + print ''.$langs->trans('NotePrivate').''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; + } - // 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)) + // 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)) { print $object->showOptionals($extrafields, 'edit'); } - // Show link to origin object - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { - $newclassname = $classname; - if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; - print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; + // Show link to origin object + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) + { + $newclassname = $classname; + if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; + print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; - // Amount - /* Hide amount because we only copy services so amount may differ than source + // Amount + /* Hide amount because we only copy services so amount may differ than source print '' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht) . ''; print '' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva) . ""; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -982,14 +1000,14 @@ if ($action == 'create') print '' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; } */ - } + } - print ''; + print ''; - if (is_object($objectsrc)) - { - print ''; - print ''; + if (is_object($objectsrc)) + { + print ''; + print ''; } elseif ($origin == 'project' && !empty($projectid)) { print ''; } @@ -998,8 +1016,8 @@ if ($action == 'create') print '
    '; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
    '; print ''; @@ -1040,8 +1058,8 @@ if ($action == 'create') print '
    '; print ''; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
    '; print ''; @@ -1058,7 +1076,11 @@ if ($action == 'create') $soc = new Societe($db); $soc->fetch($object->socid); - dol_htmloutput_mesg($mesg); + if ($error > 0) { + dol_htmloutput_errors($mesg); + } else { + dol_htmloutput_mesg($mesg); + } $head = fichinter_prepare_head($object); @@ -1099,6 +1121,12 @@ if ($action == 'create') $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') + { + $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') { @@ -1144,46 +1172,46 @@ if ($action == 'create') // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->ficheinter->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->ficheinter->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 .= '
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { @@ -1238,50 +1266,50 @@ if ($action == 'create') if ($action == 'contrat') { $formcontract = new Formcontract($db); - $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1); + $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1); } else { if ($object->fk_contrat) - { - $contratstatic = new Contrat($db); - $contratstatic->fetch($object->fk_contrat); - //print ''.$projet->title.''; - print $contratstatic->getNomUrl(0, '', 1); - } else { - print " "; - } + { + $contratstatic = new Contrat($db); + $contratstatic->fetch($object->fk_contrat); + //print ''.$projet->title.''; + print $contratstatic->getNomUrl(0, '', 1); + } else { + print " "; + } } print ''; print ''; } - // Other attributes - $cols = 2; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print '
    '; + print ''; - print '
    '; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { - // Duration - print ''; - print ''; - print ''; - } + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + // Duration + print ''; + print ''; + print ''; + } print "
    '.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
    '.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
    "; print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; - print '

    '; + print '

    '; if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) @@ -1331,8 +1359,13 @@ if ($action == 'create') { print '
    '; print ''; - print ''; + + // No. + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; + } + print ''; print ''; print ''; @@ -1344,11 +1377,16 @@ if ($action == 'create') { $objp = $db->fetch_object($resql); - // Ligne en mode visu if ($action != 'editline' || GETPOST('line_id', 'int') != $objp->rowid) { print ''; + + // No. + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; + } + print ''; + + // No. + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; + } + print ''; - // Duration - print ''; + // Duration + print ''; - print ''; print ''."\n"; @@ -1461,56 +1505,68 @@ if ($action == 'create') { if (!$num) { - print '
    '.$langs->trans('Description').''.$langs->trans('Date').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'
    '.($i + 1).''; print ''; // ancre pour retourner sur la ligne print dol_htmlentitiesbr($objp->description); @@ -1409,6 +1447,12 @@ if ($action == 'create') if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id', 'int') == $objp->rowid) { print '
    '.($i + 1).''; print ''; // ancre pour retourner sur la ligne @@ -1420,25 +1464,25 @@ if ($action == 'create') // Date d'intervention print ''; - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); - } else { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); - } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); + } else { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); + } print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) - $selectmode = 'text'; - $form->select_duration('duration', $objp->duree, 0, $selectmode); - } - print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) + $selectmode = 'text'; + $form->select_duration('duration', $objp->duree, 0, $selectmode); + } + print ''; - print ''; + print ''; + print ''; print '
    '; + print '
    '; + print '
    '; + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + // No. + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; + } + + print ''; + print ''; + print ''; + print ''; + print "\n"; } print ''."\n"; - print ''; - // Date intervention - print ''; + } + + print ''; + + // Date intervention + print ''; - // Duration - print ''; + // Duration + print ''; - print ''; + print ''; print ''; //Line extrafield @@ -1545,22 +1601,22 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook 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))) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { - print ''; - } - } + if ($action != 'editdescription' && ($action != 'presend')) { + // Validate + if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { + print ''; + } + } - // 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))) + // 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))) { print ''; } + // Reopen + if ($object->statut >= Fichinter::STATUS_CLOSED) + { + if ($user->rights->ficheinter->creer) + { + print ''; + } else print ''; + } + // Send if (empty($user->socid)) { if ($object->statut > Fichinter::STATUS_DRAFT) @@ -1580,7 +1645,7 @@ if ($action == 'create') } // create intervention model - if ($conf->global->MAIN_FEATURES_LEVEL >= 2 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { + if ($conf->global->MAIN_FEATURES_LEVEL >= 1 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { print ''; @@ -1619,7 +1684,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 ''; } @@ -1632,7 +1697,7 @@ if ($action == 'create') // Delete if (($object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) { - print ''; } } @@ -1653,7 +1718,7 @@ if ($action == 'create') $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $user->rights->ficheinter->lire; $delallowed = $user->rights->ficheinter->creer; - print $formfile->showdocuments('ficheinter', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('ficheinter', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('fichinter')); diff --git a/htdocs/fichinter/class/api_interventions.class.php b/htdocs/fichinter/class/api_interventions.class.php index b36ca265b6f..c2328e5cfd3 100644 --- a/htdocs/fichinter/class/api_interventions.class.php +++ b/htdocs/fichinter/class/api_interventions.class.php @@ -144,7 +144,7 @@ class Interventions extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -152,28 +152,28 @@ class Interventions extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; while ($i < $min) { - $obj = $db->fetch_object($result); - $fichinter_static = new Fichinter($db); + $obj = $this->db->fetch_object($result); + $fichinter_static = new Fichinter($this->db); if ($fichinter_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($fichinter_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve intervention list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve intervention list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No intervention found'); diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 754fc8dd507..930c6e07978 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -2,9 +2,9 @@ /* Copyright (C) 2002-2003 Rodolphe Quiedeville * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2011-2013 Juanjo Menent + * Copyright (C) 2011-2020 Juanjo Menent * Copyright (C) 2015 Marcos García - * Copyright (C) 2015 Charlie Benke + * Copyright (C) 2015-2020 Charlene Benke * Copyright (C) 2018 Nicolas ZABOURI * Copyright (C) 2018-2019 Frédéric France * @@ -58,8 +58,8 @@ class Fichinter extends CommonObject 'datet' =>array('type'=>'date', 'label'=>'Datet', 'enabled'=>1, 'visible'=>-1, 'position'=>95), 'duree' =>array('type'=>'double', 'label'=>'Duree', 'enabled'=>1, 'visible'=>-1, 'position'=>100), 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>105, 'showoncombobox'=>1), - 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>110), - 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>115), + 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110), + 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>115), 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>120), 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>125), 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>130), @@ -279,7 +279,7 @@ class Fichinter extends CommonObject $sql .= ", ".$user->id; $sql .= ", ".$user->id; $sql .= ", ".($this->description ? "'".$this->db->escape($this->description)."'" : "null"); - $sql .= ", '".$this->db->escape($this->modelpdf)."'"; + $sql .= ", '".$this->db->escape($this->model_pdf)."'"; $sql .= ", ".($this->fk_project ? $this->fk_project : 0); $sql .= ", ".($this->fk_contrat ? $this->fk_contrat : 0); $sql .= ", ".$this->statut; @@ -448,7 +448,8 @@ class Fichinter extends CommonObject $this->fk_project = $obj->fk_project; $this->note_public = $obj->note_public; $this->note_private = $obj->note_private; - $this->modelpdf = $obj->model_pdf; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated $this->fk_contrat = $obj->fk_contrat; $this->user_creation = $obj->fk_user_author; @@ -764,7 +765,7 @@ class Fichinter extends CommonObject $result = ''; - $label = ''.$langs->trans("ShowIntervention").''; + $label = img_picto('', $this->picto).' '.$langs->trans("Intervention").''; $label .= '
    '.$langs->trans('Ref').': '.$this->ref; if (isset($this->status)) { $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); @@ -809,7 +810,7 @@ class Fichinter extends CommonObject $result .= $linkend; global $action; - $hookmanager->initHooks(array('intervnetiondao')); + $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; @@ -1008,6 +1009,9 @@ class Fichinter extends CommonObject 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) @@ -1128,7 +1132,7 @@ class Fichinter extends CommonObject if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; - $sql .= " SET fk_contrat = '".$contractid."'"; + $sql .= " SET fk_contrat = ".((int) $contractid); $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index 66475f83edf..c9e689ffd4c 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -38,776 +38,777 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; */ class FichinterRec extends Fichinter { - public $element = 'fichinterrec'; - public $table_element = 'fichinter_rec'; - public $table_element_line = 'fichinter_rec'; - public $fk_element = 'fk_fichinter'; + public $element = 'fichinterrec'; + public $table_element = 'fichinter_rec'; + public $table_element_line = 'fichinter_rec'; + public $fk_element = 'fk_fichinter'; - /** + /** * {@inheritdoc} */ protected $table_ref_field = 'titre'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'intervention'; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'intervention'; - public $title; - public $number; - public $date; - public $amount; - public $remise; - public $tva; - public $total; - public $db_table; - public $propalid; + public $title; + public $number; + public $date; + public $amount; + public $remise; + public $tva; + public $total; + public $db_table; + public $propalid; - public $date_last_gen; - public $date_when; - public $nb_gen_done; - public $nb_gen_max; + public $date_last_gen; + public $date_when; + public $nb_gen_done; + public $nb_gen_max; - public $rang; - public $special_code; + public $rang; + public $special_code; - public $usenewprice = 0; + public $usenewprice = 0; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; - //status dans l'ordre de l'intervention - $this->statuts[0] = 'Draft'; - $this->statuts[1] = 'Closed'; + //status dans l'ordre de l'intervention + $this->statuts[0] = 'Draft'; + $this->statuts[1] = 'Closed'; - $this->statuts_short[0] = 'Draft'; - $this->statuts_short[1] = 'Closed'; + $this->statuts_short[0] = 'Draft'; + $this->statuts_short[1] = 'Closed'; - $this->statuts_logo[0] = 'statut0'; - $this->statuts_logo[1] = 'statut1'; - } + $this->statuts_logo[0] = 'statut0'; + $this->statuts_logo[1] = 'statut1'; + } - /** - * Returns the label status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->statut, $mode); - } + /** + * Returns the label status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode); + } - /** - * Create a predefined fichinter - * - * @param User $user User object - * @param int $notrigger no trigger - * @return int <0 if KO, id of fichinter if OK - */ - public function create($user, $notrigger = 0) - { - global $conf; + /** + * Create a predefined fichinter + * + * @param User $user User object + * @param int $notrigger no trigger + * @return int <0 if KO, id of fichinter if OK + */ + public function create($user, $notrigger = 0) + { + global $conf; - $error = 0; - $now = dol_now(); + $error = 0; + $now = dol_now(); - // Clean parameters - $this->title = trim($this->title); - $this->description = trim($this->description); + // Clean parameters + $this->title = trim($this->title); + $this->description = trim($this->description); - $this->db->begin(); + $this->db->begin(); - // Load fichinter model - $fichintsrc = new Fichinter($this->db); + // Load fichinter model + $fichintsrc = new Fichinter($this->db); - $result = $fichintsrc->fetch($this->id_origin); - $result = $fichintsrc->fetch_lines(1); // to get all lines + $result = $fichintsrc->fetch($this->id_origin); + $result = $fichintsrc->fetch_lines(1); // to get all lines - if ($result > 0) { - // On positionne en mode brouillon la facture - $this->brouillon = 1; + if ($result > 0) { + // On positionne en mode brouillon la facture + $this->brouillon = 1; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter_rec ("; - $sql .= "titre"; - $sql .= ", fk_soc"; - $sql .= ", entity"; - $sql .= ", datec"; - $sql .= ", duree"; - $sql .= ", description"; - $sql .= ", note_private"; - $sql .= ", note_public"; - $sql .= ", fk_user_author"; - $sql .= ", fk_projet"; - $sql .= ", fk_contrat"; - $sql .= ", modelpdf"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter_rec ("; + $sql .= "titre"; + $sql .= ", fk_soc"; + $sql .= ", entity"; + $sql .= ", datec"; + $sql .= ", duree"; + $sql .= ", description"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", fk_user_author"; + $sql .= ", fk_projet"; + $sql .= ", fk_contrat"; + $sql .= ", modelpdf"; - $sql .= ", frequency"; - $sql .= ", unit_frequency"; - $sql .= ", date_when"; - $sql .= ", date_last_gen"; - $sql .= ", nb_gen_done"; - $sql .= ", nb_gen_max"; - // $sql.= ", auto_validate"; + $sql .= ", frequency"; + $sql .= ", unit_frequency"; + $sql .= ", date_when"; + $sql .= ", date_last_gen"; + $sql .= ", nb_gen_done"; + $sql .= ", nb_gen_max"; + // $sql.= ", auto_validate"; - $sql .= ") VALUES ("; - $sql .= "'".$this->db->escape($this->title)."'"; - $sql .= ", ".($this->socid > 0 ? $this->socid : 'null'); - $sql .= ", ".$conf->entity; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".(!empty($fichintsrc->duration) ? $fichintsrc->duration : '0'); - $sql .= ", ".(!empty($this->description) ? ("'".$this->db->escape($this->description)."'") : "null"); - $sql .= ", ".(!empty($fichintsrc->note_private) ? ("'".$this->db->escape($fichintsrc->note_private)."'") : "null"); - $sql .= ", ".(!empty($fichintsrc->note_public) ? ("'".$this->db->escape($fichintsrc->note_public)."'") : "null"); - $sql .= ", '".$user->id."'"; - // si c'est la même société on conserve les liens vers le projet et le contrat - if ($this->socid == $fichintsrc->socid) { - $sql .= ", ".(!empty($fichintsrc->fk_project) ? $fichintsrc->fk_project : "null"); - $sql .= ", ".(!empty($fichintsrc->fk_contrat) ? $fichintsrc->fk_contrat : "null"); - } else { - $sql .= ", null, null"; - } + $sql .= ") VALUES ("; + $sql .= "'".$this->db->escape($this->title)."'"; + $sql .= ", ".($this->socid > 0 ? $this->socid : 'null'); + $sql .= ", ".$conf->entity; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".(!empty($fichintsrc->duration) ? $fichintsrc->duration : '0'); + $sql .= ", ".(!empty($this->description) ? ("'".$this->db->escape($this->description)."'") : "null"); + $sql .= ", ".(!empty($fichintsrc->note_private) ? ("'".$this->db->escape($fichintsrc->note_private)."'") : "null"); + $sql .= ", ".(!empty($fichintsrc->note_public) ? ("'".$this->db->escape($fichintsrc->note_public)."'") : "null"); + $sql .= ", ".$user->id; + // si c'est la même société on conserve les liens vers le projet et le contrat + if ($this->socid == $fichintsrc->socid) { + $sql .= ", ".(!empty($fichintsrc->fk_project) ? $fichintsrc->fk_project : "null"); + $sql .= ", ".(!empty($fichintsrc->fk_contrat) ? $fichintsrc->fk_contrat : "null"); + } else { + $sql .= ", null, null"; + } - $sql .= ", ".(!empty($fichintsrc->modelpdf) ? "'".$this->db->escape($fichintsrc->modelpdf)."'" : "''"); + $sql .= ", ".(!empty($fichintsrc->model_pdf) ? "'".$this->db->escape($fichintsrc->model_pdf)."'" : "''"); - // récurrence - $sql .= ", ".(!empty($this->frequency) ? $this->frequency : "null"); - $sql .= ", '".$this->db->escape($this->unit_frequency)."'"; - $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'null'); - $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'null'); - $sql .= ", 0"; // we start à 0 - $sql .= ", ".$this->nb_gen_max; - // $sql.= ", ".$this->auto_validate; - $sql .= ")"; + // récurrence + $sql .= ", ".(!empty($this->frequency) ? $this->frequency : "null"); + $sql .= ", '".$this->db->escape($this->unit_frequency)."'"; + $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'null'); + $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'null'); + $sql .= ", 0"; // we start à 0 + $sql .= ", ".$this->nb_gen_max; + // $sql.= ", ".$this->auto_validate; + $sql .= ")"; - if ($this->db->query($sql)) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + if ($this->db->query($sql)) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - /* + /* * Lines */ - $num = count($fichintsrc->lines); - for ($i = 0; $i < $num; $i++) { - //var_dump($fichintsrc->lines[$i]); - $result_insert = $this->addline( - $fichintsrc->lines[$i]->desc, - $fichintsrc->lines[$i]->duration, - $fichintsrc->lines[$i]->datei, - $fichintsrc->lines[$i]->rang, - $fichintsrc->lines[$i]->subprice, - $fichintsrc->lines[$i]->qty, - $fichintsrc->lines[$i]->tva_tx, - $fichintsrc->lines[$i]->fk_product, - $fichintsrc->lines[$i]->remise_percent, - 'HT', - 0, - '', - 0, - $fichintsrc->lines[$i]->product_type, - $fichintsrc->lines[$i]->special_code, - $fichintsrc->lines[$i]->label, - $fichintsrc->lines[$i]->fk_unit - ); - - if ($result_insert < 0) - $error++; - } - - if ($error) - $this->db->rollback(); - else { - $this->db->commit(); - return $this->id; - } - } else { - $this->error = $this->db->error().' sql='.$sql; - $this->db->rollback(); - return -2; - } - } else { - $this->db->rollback(); - return -1; - } - } - - - /** - * Get the template of intervention object and lines - * - * @param int $rowid Id of object to load - * @param string $ref Reference of fichinter - * @param string $ref_ext External reference of fichinter - * @return int >0 if OK, <0 if KO, 0 if not found - */ - public function fetch($rowid = 0, $ref = '', $ref_ext = '') - { - $sql = 'SELECT f.titre, f.fk_soc'; - $sql .= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description'; - $sql .= ', f.note_private, f.note_public, f.fk_user_author'; - $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)."'"; - - dol_syslog(get_class($this)."::fetch rowid=".$rowid, LOG_DEBUG); - - $result = $this->db->query($sql); - if ($result) { - if ($this->db->num_rows($result)) { - $obj = $this->db->fetch_object($result); - - $this->id = $rowid; - $this->titre = $obj->titre; - $this->ref = $obj->titre; - $this->description = $obj->description; - $this->datec = $obj->datec; - $this->duration = $obj->duree; - $this->socid = $obj->fk_soc; - $this->statut = 0; - $this->fk_project = $obj->fk_projet; - $this->fk_contrat = $obj->fk_contrat; - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->user_author = $obj->fk_user_author; - $this->modelpdf = $obj->model_pdf; - $this->rang = $obj->rang; - $this->special_code = $obj->special_code; - $this->frequency = $obj->frequency; - $this->unit_frequency = $obj->unit_frequency; - $this->date_when = $this->db->jdate($obj->date_when); - $this->date_last_gen = $this->db->jdate($obj->date_last_gen); - $this->nb_gen_done = $obj->nb_gen_done; - $this->nb_gen_max = $obj->nb_gen_max; - $this->auto_validate = $obj->auto_validate; - - $this->brouillon = 1; - - // Lines - $result = $this->fetch_lines(); - if ($result < 0) { - $this->error = $this->db->error(); - return -3; - } - return 1; - } else { - $this->error = 'Interventional with id '.$rowid.' not found sql='.$sql; - dol_syslog(get_class($this).'::Fetch Error '.$this->error, LOG_ERR); - return -2; - } - } else { - $this->error = $this->db->error(); - return -1; - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load all lines of template of intervention into this->lines - * - * @param int $sall sall - * @return int 1 if OK, < 0 if KO - */ - public function fetch_lines($sall = 0) - { - // phpcs:enable - $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, '; - $sql .= ' l.price, l.qty, l.tva_tx, l.remise, l.remise_percent, l.subprice, l.duree, '; - $sql .= ' l.total_ht, l.total_tva, l.total_ttc,'; - $sql .= ' l.rang, l.special_code,'; - $sql .= ' l.fk_unit, p.ref as product_ref, p.fk_product_type as fk_product_type,'; - $sql .= ' p.label as product_label, p.description as product_desc'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_rec as l'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - $sql .= ' WHERE l.fk_fichinter = '.$this->id; - - dol_syslog('FichInter-rec::fetch_lines', LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) { - $objp = $this->db->fetch_object($result); - $line = new FichinterLigne($this->db); - - $line->id = $objp->rowid; - $line->label = $objp->custom_label; // Label line - $line->desc = $objp->description; // Description line - $line->product_type = $objp->product_type; // Type of line - $line->product_ref = $objp->product_ref; // Ref product - $line->product_label = $objp->product_label; // Label product - $line->product_desc = $objp->product_desc; // Description product - $line->fk_product_type = $objp->fk_product_type; // Type of product - $line->qty = $objp->qty; - $line->duree = $objp->duree; - $line->duration = $objp->duree; - $line->datei = $objp->date; - $line->subprice = $objp->subprice; - $line->tva_tx = $objp->tva_tx; - $line->remise_percent = $objp->remise_percent; - $line->fk_remise_except = $objp->fk_remise_except; - $line->fk_product = $objp->fk_product; - $line->date_start = $objp->date_start; - $line->date_end = $objp->date_end; - $line->date_start = $objp->date_start; - $line->date_end = $objp->date_end; - $line->info_bits = $objp->info_bits; - $line->total_ht = $objp->total_ht; - $line->total_tva = $objp->total_tva; - $line->total_ttc = $objp->total_ttc; - $line->code_ventilation = $objp->fk_code_ventilation; - $line->rang = $objp->rang; - $line->special_code = $objp->special_code; - $line->fk_unit = $objp->fk_unit; - - // Ne plus utiliser - $line->price = $objp->price; - $line->remise = $objp->remise; - - $this->lines[$i] = $line; - - $i++; - } - - $this->db->free($result); - return 1; - } else { - $this->error = $this->db->error(); - return -3; - } - } - - - /** - * Delete template fichinter rec - * - * @param int $rowid Id of fichinter rec to delete. If empty, we delete current instance of fichinter rec - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @param int $idwarehouse Id warehouse to use for stock change. - * @return int <0 if KO, >0 if OK - */ - public function delete($rowid = 0, $notrigger = 0, $idwarehouse = -1) - { - if (empty($rowid)) $rowid = $this->id; - - dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); - - $error = 0; - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet_rec WHERE fk_fichinter = ".$rowid; - dol_syslog($sql); - if ($this->db->query($sql)) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter_rec WHERE rowid = ".$rowid; - dol_syslog($sql); - if (!$this->db->query($sql)) { - $this->error = $this->db->lasterror(); - $error = -1; - } - } else { - $this->error = $this->db->lasterror(); - $error = -2; - } - - if (!$error) { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return $error; - } - } - - - /** - * Add a line to fichinter rec - * - * @param string $desc Description de la ligne - * @param integer $duration Durée - * @param string $datei Date - * @param int $rang Position of line - * @param double $pu_ht Unit price without tax (> 0 even for credit note) - * @param double $qty Quantity - * @param double $txtva Forced VAT rate, otherwise -1 - * @param int $fk_product Id of predefined product/service - * @param double $remise_percent Percentage of discount on line - * @param string $price_base_type HT or TTC - * @param int $info_bits Bits for type of lines - * @param int $fk_remise_except Id discount - * @param double $pu_ttc Unit price with tax (> 0 even for credit note) - * @param int $type Type of line (0=product, 1=service) - * @param int $special_code Special code - * @param string $label Label of the line - * @param string $fk_unit Unit - * @return int <0 if KO, Id of line if OK - */ - public function addline($desc, $duration, $datei, $rang = -1, $pu_ht = 0, $qty = 0, $txtva = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $special_code = 0, $label = '', $fk_unit = null) - { - global $mysoc; - - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - - // Check parameters - 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; - $pu_ht = price2num($pu_ht); - $pu_ttc = price2num($pu_ttc); - $txtva = price2num($txtva); - - if ($price_base_type == 'HT') { - $pu = $pu_ht; - } else { - $pu = $pu_ttc; - } - - - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, 0, 0, 0, $price_base_type, $info_bits, $type, $mysoc); - - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - - $product_type = $type; - if ($fk_product) { - $product = new Product($this->db); - $result = $product->fetch($fk_product); - $product_type = $product->type; - } - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinterdet_rec ("; - $sql .= "fk_fichinter"; - $sql .= ", label"; - $sql .= ", description"; - $sql .= ", date"; - $sql .= ", duree"; - //$sql.= ", price"; - //$sql.= ", qty"; - //$sql.= ", tva_tx"; - $sql .= ", fk_product"; - $sql .= ", product_type"; - $sql .= ", remise_percent"; - //$sql.= ", subprice"; - $sql .= ", remise"; - $sql .= ", total_ht"; - $sql .= ", total_tva"; - $sql .= ", total_ttc"; - $sql .= ", rang"; - //$sql.= ", special_code"; - $sql .= ", fk_unit"; - $sql .= ") VALUES ("; - $sql .= (int) $this->id; - $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); - $sql .= ", ".(!empty($desc) ? "'".$this->db->escape($desc)."'" : "null"); - $sql .= ", ".(!empty($datei) ? "'".$this->db->idate($datei)."'" : "null"); - $sql .= ", ".$duration; - //$sql.= ", ".price2num($pu_ht); - //$sql.= ", ".(!empty($qty)? $qty :(!empty($duration)? $duration :"null")); - //$sql.= ", ".price2num($txtva); - $sql .= ", ".(!empty($fk_product) ? $fk_product : "null"); - $sql .= ", ".$product_type; - $sql .= ", ".(!empty($remise_percent) ? $remise_percent : "null"); - //$sql.= ", '".price2num($pu_ht)."'"; - $sql .= ", null"; - $sql .= ", '".price2num($total_ht)."'"; - $sql .= ", '".price2num($total_tva)."'"; - $sql .= ", '".price2num($total_ttc)."'"; - $sql .= ", ".(int) $rang; - //$sql.= ", ".$special_code; - $sql .= ", ".(!empty($fk_unit) ? $fk_unit : "null"); - $sql .= ")"; - - dol_syslog(get_class($this)."::addline", LOG_DEBUG); - if ($this->db->query($sql)) { - return 1; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Rend la fichinter automatique - * - * @param User $user User object - * @param int $freq Freq - * @param string $courant Courant - * @return int 0 if OK, <0 if KO - */ - public function set_auto($user, $freq, $courant) - { - // phpcs:enable - if ($user->rights->fichinter->creer) { - $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter_rec "; - $sql .= " SET frequency='".$this->db->escape($freq)."'"; - $sql .= ", last_gen='".$this->db->escape($courant)."'"; - $sql .= " WHERE rowid = ".$this->id; - - $resql = $this->db->query($sql); - - if ($resql) { - $this->frequency = $freq; - $this->last_gen = $courant; - return 0; - } else { - dol_print_error($this->db); - return -1; - } - } else { - return -2; - } - } - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto Add picto into link - * @param string $option Where point the link - * @param int $max Maxlength of ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '') - { - global $langs; - - $result = ''; - $label = $langs->trans("ShowInterventionModel").': '.$this->ref; - - $url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id; - - if ($short) return $url; - - $picto = 'intervention'; - - $link = ''; - $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; - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @param string $option ''=Create a specimen fichinter with lines, 'nolines'=No lines - * @return void - */ - public function initAsSpecimen($option = '') - { - global $user, $langs, $conf; - - $now = dol_now(); - $arraynow = dol_getdate($now); - $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); - - parent::initAsSpecimen($option); - - $this->usenewprice = 1; - } - - /** - * Function used to replace a thirdparty id with another one. - * - * @param DoliDB $db Database handler - * @param int $origin_id Old thirdparty id - * @param int $dest_id New thirdparty id - * @return bool - */ - public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) - { - $tables = array('fichinter_rec'); - - return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); - } - - - /** - * Update frequency and unit - * - * @param int $frequency value of frequency - * @param string $unit unit of frequency (d, m, y) - * @return int <0 if KO, >0 if OK - */ - public function setFrequencyAndUnit($frequency, $unit) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setFrequencyAndUnit called with table_element not defined", LOG_ERR); - return -1; - } - - if (!empty($frequency) && empty($unit)) { - dol_syslog(get_class($this)."::setFrequencyAndUnit called with frequency defined but unit not ", LOG_ERR); - return -2; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); - if (!empty($unit)) { - $sql .= ', unit_frequency = "'.$this->db->escape($unit).'"'; - } - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the next date of execution - * - * @param datetime $date date of execution - * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done - * @return int <0 if KO, >0 if OK - */ - public function setNextDate($date, $increment_nb_gen_done = 0) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - $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'; - $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++; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the maximum period - * - * @param int $nb number of maximum period - * @return int <0 if KO, >0 if OK - */ - public function setMaxPeriod($nb) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); - return -1; - } - - if (empty($nb)) $nb = 0; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET nb_gen_max = '.$nb; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->nb_gen_max = $nb; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the auto validate fichinter - * - * @param int $validate 0 to create in draft, 1 to create and validate fichinter - * @return int <0 if KO, >0 if OK - */ - public function setAutoValidate($validate) - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::setAutoValidate called with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET auto_validate = '.$validate; - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->auto_validate = $validate; - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } - - /** - * Update the Number of Generation Done - * - * @return int <0 if KO, >0 if OK - */ - public function updateNbGenDone() - { - if (!$this->table_element) { - dol_syslog(get_class($this)."::updateNbGenDone called with property table_element not defined", LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $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) - $sql .= ' , statut = 1'; - - $sql .= ' WHERE rowid = '.$this->id; - - dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); - if ($this->db->query($sql)) { - $this->nb_gen_done = $this->nb_gen_done + 1; - $this->nb_gen_done = dol_now(); - return 1; - } else { - dol_print_error($this->db); - return -1; - } - } + $num = count($fichintsrc->lines); + for ($i = 0; $i < $num; $i++) { + //var_dump($fichintsrc->lines[$i]); + $result_insert = $this->addline( + $fichintsrc->lines[$i]->desc, + $fichintsrc->lines[$i]->duration, + $fichintsrc->lines[$i]->datei, + $fichintsrc->lines[$i]->rang, + $fichintsrc->lines[$i]->subprice, + $fichintsrc->lines[$i]->qty, + $fichintsrc->lines[$i]->tva_tx, + $fichintsrc->lines[$i]->fk_product, + $fichintsrc->lines[$i]->remise_percent, + 'HT', + 0, + '', + 0, + $fichintsrc->lines[$i]->product_type, + $fichintsrc->lines[$i]->special_code, + $fichintsrc->lines[$i]->label, + $fichintsrc->lines[$i]->fk_unit + ); + + if ($result_insert < 0) + $error++; + } + + if ($error) + $this->db->rollback(); + else { + $this->db->commit(); + return $this->id; + } + } else { + $this->error = $this->db->error().' sql='.$sql; + $this->db->rollback(); + return -2; + } + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Get the template of intervention object and lines + * + * @param int $rowid Id of object to load + * @param string $ref Reference of fichinter + * @param string $ref_ext External reference of fichinter + * @return int >0 if OK, <0 if KO, 0 if not found + */ + public function fetch($rowid = 0, $ref = '', $ref_ext = '') + { + $sql = 'SELECT f.titre as title, f.fk_soc'; + $sql .= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description'; + $sql .= ', f.note_private, f.note_public, f.fk_user_author'; + $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)."'"; + + dol_syslog(get_class($this)."::fetch rowid=".$rowid, LOG_DEBUG); + + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + + $this->id = $rowid; + $this->titre = $obj->title; + $this->title = $obj->title; + $this->ref = $obj->title; + $this->description = $obj->description; + $this->datec = $obj->datec; + $this->duration = $obj->duree; + $this->socid = $obj->fk_soc; + $this->statut = 0; + $this->fk_project = $obj->fk_projet; + $this->fk_contrat = $obj->fk_contrat; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->user_author = $obj->fk_user_author; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; + $this->rang = $obj->rang; + $this->special_code = $obj->special_code; + $this->frequency = $obj->frequency; + $this->unit_frequency = $obj->unit_frequency; + $this->date_when = $this->db->jdate($obj->date_when); + $this->date_last_gen = $this->db->jdate($obj->date_last_gen); + $this->nb_gen_done = $obj->nb_gen_done; + $this->nb_gen_max = $obj->nb_gen_max; + $this->auto_validate = $obj->auto_validate; + + $this->brouillon = 1; + + // Lines + $result = $this->fetch_lines(); + if ($result < 0) { + $this->error = $this->db->error(); + return -3; + } + return 1; + } else { + $this->error = 'Interventional with id '.$rowid.' not found sql='.$sql; + dol_syslog(get_class($this).'::Fetch Error '.$this->error, LOG_ERR); + return -2; + } + } else { + $this->error = $this->db->error(); + return -1; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load all lines of template of intervention into this->lines + * + * @param int $sall sall + * @return int 1 if OK, < 0 if KO + */ + public function fetch_lines($sall = 0) + { + // phpcs:enable + $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, '; + $sql .= ' l.price, l.qty, l.tva_tx, l.remise, l.remise_percent, l.subprice, l.duree, '; + $sql .= ' l.total_ht, l.total_tva, l.total_ttc,'; + $sql .= ' l.rang, l.special_code,'; + $sql .= ' l.fk_unit, p.ref as product_ref, p.fk_product_type as fk_product_type,'; + $sql .= ' p.label as product_label, p.description as product_desc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinterdet_rec as l'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; + $sql .= ' WHERE l.fk_fichinter = '.$this->id; + + dol_syslog('FichInter-rec::fetch_lines', LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($result); + $line = new FichinterLigne($this->db); + + $line->id = $objp->rowid; + $line->label = $objp->custom_label; // Label line + $line->desc = $objp->description; // Description line + $line->product_type = $objp->product_type; // Type of line + $line->product_ref = $objp->product_ref; // Ref product + $line->product_label = $objp->product_label; // Label product + $line->product_desc = $objp->product_desc; // Description product + $line->fk_product_type = $objp->fk_product_type; // Type of product + $line->qty = $objp->qty; + $line->duree = $objp->duree; + $line->duration = $objp->duree; + $line->datei = $objp->date; + $line->subprice = $objp->subprice; + $line->tva_tx = $objp->tva_tx; + $line->remise_percent = $objp->remise_percent; + $line->fk_remise_except = $objp->fk_remise_except; + $line->fk_product = $objp->fk_product; + $line->date_start = $objp->date_start; + $line->date_end = $objp->date_end; + $line->date_start = $objp->date_start; + $line->date_end = $objp->date_end; + $line->info_bits = $objp->info_bits; + $line->total_ht = $objp->total_ht; + $line->total_tva = $objp->total_tva; + $line->total_ttc = $objp->total_ttc; + $line->code_ventilation = $objp->fk_code_ventilation; + $line->rang = $objp->rang; + $line->special_code = $objp->special_code; + $line->fk_unit = $objp->fk_unit; + + // Ne plus utiliser + $line->price = $objp->price; + $line->remise = $objp->remise; + + $this->lines[$i] = $line; + + $i++; + } + + $this->db->free($result); + return 1; + } else { + $this->error = $this->db->error(); + return -3; + } + } + + + /** + * Delete template fichinter rec + * + * @param int $rowid Id of fichinter rec to delete. If empty, we delete current instance of fichinter rec + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $idwarehouse Id warehouse to use for stock change. + * @return int <0 if KO, >0 if OK + */ + public function delete($rowid = 0, $notrigger = 0, $idwarehouse = -1) + { + if (empty($rowid)) $rowid = $this->id; + + dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); + + $error = 0; + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet_rec WHERE fk_fichinter = ".$rowid; + dol_syslog($sql); + if ($this->db->query($sql)) { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter_rec WHERE rowid = ".$rowid; + dol_syslog($sql); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); + $error = -1; + } + } else { + $this->error = $this->db->lasterror(); + $error = -2; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return $error; + } + } + + + /** + * Add a line to fichinter rec + * + * @param string $desc Description de la ligne + * @param integer $duration Durée + * @param string $datei Date + * @param int $rang Position of line + * @param double $pu_ht Unit price without tax (> 0 even for credit note) + * @param double $qty Quantity + * @param double $txtva Forced VAT rate, otherwise -1 + * @param int $fk_product Id of predefined product/service + * @param double $remise_percent Percentage of discount on line + * @param string $price_base_type HT or TTC + * @param int $info_bits Bits for type of lines + * @param int $fk_remise_except Id discount + * @param double $pu_ttc Unit price with tax (> 0 even for credit note) + * @param int $type Type of line (0=product, 1=service) + * @param int $special_code Special code + * @param string $label Label of the line + * @param string $fk_unit Unit + * @return int <0 if KO, Id of line if OK + */ + public function addline($desc, $duration, $datei, $rang = -1, $pu_ht = 0, $qty = 0, $txtva = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $special_code = 0, $label = '', $fk_unit = null) + { + global $mysoc; + + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + + // Check parameters + 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; + $pu_ht = price2num($pu_ht); + $pu_ttc = price2num($pu_ttc); + $txtva = price2num($txtva); + + if ($price_base_type == 'HT') { + $pu = $pu_ht; + } else { + $pu = $pu_ttc; + } + + + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, 0, 0, 0, $price_base_type, $info_bits, $type, $mysoc); + + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + + $product_type = $type; + if ($fk_product) { + $product = new Product($this->db); + $result = $product->fetch($fk_product); + $product_type = $product->type; + } + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinterdet_rec ("; + $sql .= "fk_fichinter"; + $sql .= ", label"; + $sql .= ", description"; + $sql .= ", date"; + $sql .= ", duree"; + //$sql.= ", price"; + //$sql.= ", qty"; + //$sql.= ", tva_tx"; + $sql .= ", fk_product"; + $sql .= ", product_type"; + $sql .= ", remise_percent"; + //$sql.= ", subprice"; + $sql .= ", remise"; + $sql .= ", total_ht"; + $sql .= ", total_tva"; + $sql .= ", total_ttc"; + $sql .= ", rang"; + //$sql.= ", special_code"; + $sql .= ", fk_unit"; + $sql .= ") VALUES ("; + $sql .= (int) $this->id; + $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null"); + $sql .= ", ".(!empty($desc) ? "'".$this->db->escape($desc)."'" : "null"); + $sql .= ", ".(!empty($datei) ? "'".$this->db->idate($datei)."'" : "null"); + $sql .= ", ".$duration; + //$sql.= ", ".price2num($pu_ht); + //$sql.= ", ".(!empty($qty)? $qty :(!empty($duration)? $duration :"null")); + //$sql.= ", ".price2num($txtva); + $sql .= ", ".(!empty($fk_product) ? $fk_product : "null"); + $sql .= ", ".$product_type; + $sql .= ", ".(!empty($remise_percent) ? $remise_percent : "null"); + //$sql.= ", '".price2num($pu_ht)."'"; + $sql .= ", null"; + $sql .= ", '".price2num($total_ht)."'"; + $sql .= ", '".price2num($total_tva)."'"; + $sql .= ", '".price2num($total_ttc)."'"; + $sql .= ", ".(int) $rang; + //$sql.= ", ".$special_code; + $sql .= ", ".(!empty($fk_unit) ? $fk_unit : "null"); + $sql .= ")"; + + dol_syslog(get_class($this)."::addline", LOG_DEBUG); + if ($this->db->query($sql)) { + return 1; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Rend la fichinter automatique + * + * @param User $user User object + * @param int $freq Freq + * @param string $courant Courant + * @return int 0 if OK, <0 if KO + */ + public function set_auto($user, $freq, $courant) + { + // phpcs:enable + if ($user->rights->fichinter->creer) { + $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter_rec "; + $sql .= " SET frequency='".$this->db->escape($freq)."'"; + $sql .= ", date_last_gen='".$this->db->escape($courant)."'"; + $sql .= " WHERE rowid = ".$this->id; + + $resql = $this->db->query($sql); + + if ($resql) { + $this->frequency = $freq; + $this->date_last_gen = $courant; + return 0; + } else { + dol_print_error($this->db); + return -1; + } + } else { + return -2; + } + } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto Add picto into link + * @param string $option Where point the link + * @param int $max Maxlength of ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '') + { + global $langs; + + $result = ''; + $label = $langs->trans("ShowInterventionModel").': '.$this->ref; + + $url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id; + + if ($short) return $url; + + $picto = 'intervention'; + + $link = ''; + $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; + } + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @param string $option ''=Create a specimen fichinter with lines, 'nolines'=No lines + * @return void + */ + public function initAsSpecimen($option = '') + { + global $user, $langs, $conf; + + $now = dol_now(); + $arraynow = dol_getdate($now); + $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); + + parent::initAsSpecimen($option); + + $this->usenewprice = 1; + } + + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old thirdparty id + * @param int $dest_id New thirdparty id + * @return bool + */ + public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) + { + $tables = array('fichinter_rec'); + + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); + } + + + /** + * Update frequency and unit + * + * @param int $frequency value of frequency + * @param string $unit unit of frequency (d, m, y) + * @return int <0 if KO, >0 if OK + */ + public function setFrequencyAndUnit($frequency, $unit) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setFrequencyAndUnit called with table_element not defined", LOG_ERR); + return -1; + } + + if (!empty($frequency) && empty($unit)) { + dol_syslog(get_class($this)."::setFrequencyAndUnit called with frequency defined but unit not ", LOG_ERR); + return -2; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null'); + if (!empty($unit)) { + $sql .= ', unit_frequency = "'.$this->db->escape($unit).'"'; + } + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->frequency = $frequency; + if (!empty($unit)) $this->unit_frequency = $unit; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the next date of execution + * + * @param datetime $date date of execution + * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done + * @return int <0 if KO, >0 if OK + */ + public function setNextDate($date, $increment_nb_gen_done = 0) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + $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'; + $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++; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the maximum period + * + * @param int $nb number of maximum period + * @return int <0 if KO, >0 if OK + */ + public function setMaxPeriod($nb) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); + return -1; + } + + if (empty($nb)) $nb = 0; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET nb_gen_max = '.$nb; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->nb_gen_max = $nb; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the auto validate fichinter + * + * @param int $validate 0 to create in draft, 1 to create and validate fichinter + * @return int <0 if KO, >0 if OK + */ + public function setAutoValidate($validate) + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::setAutoValidate called with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET auto_validate = '.$validate; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->auto_validate = $validate; + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Update the Number of Generation Done + * + * @return int <0 if KO, >0 if OK + */ + public function updateNbGenDone() + { + if (!$this->table_element) { + dol_syslog(get_class($this)."::updateNbGenDone called with property table_element not defined", LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $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) + $sql .= ' , statut = 1'; + + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); + if ($this->db->query($sql)) { + $this->nb_gen_done = $this->nb_gen_done + 1; + $this->nb_gen_done = dol_now(); + return 1; + } else { + dol_print_error($this->db); + return -1; + } + } } diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index e991efb2009..1eb0df5147a 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -36,7 +36,7 @@ $langs->loadLangs(array('interventions', 'sendings', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php index 9825c0a58d1..49988e27e78 100644 --- a/htdocs/fichinter/document.php +++ b/htdocs/fichinter/document.php @@ -43,7 +43,7 @@ $langs->loadLangs(array('other', 'fichinter', 'companies', 'interventions')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -53,8 +53,8 @@ $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index 0204689b9b0..f6b95678f9d 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -40,7 +40,7 @@ $langs->loadLangs(array('companies', 'bills', 'interventions')); if (!empty($conf->projet->enabled)) $langs->load("projects"); if (!empty($conf->contrat->enabled)) $langs->load("contracts"); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -65,8 +65,8 @@ $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $diroutputmassaction = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -95,9 +95,10 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'f.description'=>'Description', '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['f.description']); +if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['fd.description']); // Definition of fields for list $arrayfields = array( @@ -108,6 +109,8 @@ $arrayfields = array( 'f.description'=>array('label'=>'Description', 'checked'=>1), 'f.datec'=>array('label'=>'DateCreation', 'checked'=>0, 'position'=>500), 'f.tms'=>array('label'=>'DateModificationShort', 'checked'=>0, 'position'=>500), + 'f.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'position'=>510, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PUBLIC_NOTES))), + 'f.note_private'=>array('label'=>'NotePrivate', 'checked'=>0, 'position'=>511, 'enabled'=>(empty($conf->global->MAIN_LIST_ALLOW_PRIVATE_NOTES))), 'f.fk_statut'=>array('label'=>'Status', 'checked'=>1, 'position'=>1000), 'fd.description'=>array('label'=>"DescriptionOfLine", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS) ? 1 : 0), 'fd.date'=>array('label'=>'DateOfLine', 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS) ? 1 : 0), @@ -200,7 +203,7 @@ 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_private,"; +$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,"; $sql .= " s.nom as name, s.rowid as socid, s.client, s.fournisseur, s.email, s.status as thirdpartystatus"; if (!empty($conf->projet->enabled)) { @@ -319,7 +322,10 @@ if ($resql) $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; - $morehtmlcenter .= dolGetButtonTitle($langs->trans('NewIntervention'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fichinter/card.php?action=create', '', $user->rights->ficheinter->creer); + + $url = DOL_URL_ROOT.'/fichinter/card.php?action=create'; + 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 '
    '."\n"; @@ -414,6 +420,18 @@ if ($resql) print '
    '; } + if (!empty($arrayfields['f.note_public']['checked'])) + { + // Note public + print ''; + } + if (!empty($arrayfields['f.note_private']['checked'])) + { + // Note private + print ''; + } // Status if (!empty($arrayfields['f.fk_statut']['checked'])) { @@ -458,6 +476,8 @@ if ($resql) 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 '); @@ -583,6 +603,22 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Note public + if (!empty($arrayfields['f.note_public']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Note private + if (!empty($arrayfields['f.note_private']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Status if (!empty($arrayfields['f.fk_statut']['checked'])) { diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index b5ef5f91241..42003b8a27a 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -36,7 +36,7 @@ $langs->loadLangs(array('companies', 'interventions')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/fichinter/stats/index.php b/htdocs/fichinter/stats/index.php index cb076e01ef1..90d9741fbc3 100644 --- a/htdocs/fichinter/stats/index.php +++ b/htdocs/fichinter/stats/index.php @@ -70,7 +70,7 @@ 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->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); diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php index d9f3d3a14c3..8912fd2a299 100644 --- a/htdocs/filefunc.inc.php +++ b/htdocs/filefunc.inc.php @@ -276,8 +276,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php'; //print memory_get_usage(); -// If password is encoded, we decode it -if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) +// If password is encoded, we decode it. Note: When page is called for install, $dolibarr_main_db_pass may not be defined yet. +if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) { if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) { diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index d404f52ea48..9aeef877bab 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -118,7 +118,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; @@ -366,7 +366,7 @@ if ($object->id > 0) $icon = 'bill'; if ($link) $boxstat .= ''; $boxstat .= '
    '; - $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; $boxstat .= '
    '; if ($link) $boxstat .= '
    '; @@ -384,7 +384,7 @@ if ($object->id > 0) $icon = 'bill'; if ($link) $boxstat .= ''; $boxstat .= '
    '; - $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; $boxstat .= '
    '; if ($link) $boxstat .= '
    '; @@ -402,7 +402,7 @@ if ($object->id > 0) $icon = 'bill'; if ($link) $boxstat .= ''; $boxstat .= '
    '; - $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).''; $boxstat .= '
    '; if ($link) $boxstat .= '
    '; @@ -413,7 +413,7 @@ if ($object->id > 0) $icon = 'bill'; if ($link) $boxstat .= ''; $boxstat .= '
    '; - $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; + $boxstat .= ''.img_object("", $icon).' '.$text.'
    '; $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; $boxstat .= '
    '; if ($link) $boxstat .= '
    '; @@ -595,10 +595,10 @@ if ($object->id > 0) // Show orders we can bill if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) { - $sql2 .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/orderstoinvoice.php + $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 - $sql2 .= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; + $sql2 .= " AND c.fk_statut IN (".$db->sanitize($db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)).")"; } $sql2 .= " AND c.billed = 0"; // Find order that are not already invoiced @@ -795,10 +795,9 @@ if ($object->id > 0) { if (!empty($orders2invoice) && $orders2invoice > 0) { - if ($object->status == 1) - { + if ($object->status == 1) { // Company is open - print ''; + print ''; } else { print ''; } diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 501f0c48977..8c3ca0108e3 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -30,519 +30,519 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; */ class SupplierInvoices extends DolibarrApi { - /** - * - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid', - ); + /** + * + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + ); - /** - * @var FactureFournisseur $invoice {@type FactureFournisseur} - */ - public $invoice; + /** + * @var FactureFournisseur $invoice {@type FactureFournisseur} + */ + public $invoice; - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - $this->invoice = new FactureFournisseur($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + $this->invoice = new FactureFournisseur($this->db); + } - /** - * Get properties of a supplier invoice object - * - * Return an array with supplier invoice information - * - * @param int $id ID of supplier invoice - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) { - throw new RestException(401); - } + /** + * Get properties of a supplier invoice object + * + * Return an array with supplier invoice information + * + * @param int $id ID of supplier invoice + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $this->invoice->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->invoice); - } - - /** - * List invoices - * - * Get a list of supplier invoices - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter invoices of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} - * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" - * @return array Array of invoice objects - * - * @throws RestException - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') - { - global $db; - - $obj_ret = array(); - - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - - // 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; - - $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"; - $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"; - - $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 - - // Filter by status - if ($status == 'draft') { - $sql .= " AND t.fk_statut IN (0)"; - } - if ($status == 'unpaid') { - $sql .= " AND t.fk_statut IN (1)"; - } - if ($status == 'paid') { - $sql .= " AND t.fk_statut IN (2)"; - } - if ($status == 'cancelled') { - $sql .= " AND t.fk_statut IN (3)"; - } - // Insert sale filter - if ($search_sale > 0) { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $db->plimit($limit + 1, $offset); - } - - $result = $db->query($sql); - if ($result) { - $i = 0; - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $invoice_static = new FactureFournisseur($db); - if ($invoice_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($invoice_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve supplier invoice list : '.$db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No supplier invoice found'); - } - return $obj_ret; - } - - /** - * Create supplier invoice object - * - * @param array $request_data Request datas - * - * @return int ID of supplier invoice - * - * @throws RestException 401 - * @throws RestException 500 - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validate($request_data); - - foreach ($request_data as $field => $value) { - $this->invoice->$field = $value; - } - if (!array_key_exists('date', $request_data)) { - $this->invoice->date = dol_now(); - } - - if ($this->invoice->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating order", array_merge(array($this->invoice->error), $this->invoice->errors)); - } - return $this->invoice->id; - } - - /** - * Update supplier invoice - * - * @param int $id Id of supplier invoice to update - * @param array $request_data Datas - * - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->invoice->$field = $value; - } - - if ($this->invoice->update($id, DolibarrApiAccess::$user)) - return $this->get($id); - - return false; - } - - /** - * Delete supplier invoice - * - * @param int $id Supplier invoice ID - * - * @return array - * - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->supprimer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) - { - throw new RestException(500); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Supplier invoice deleted' - ) - ); - } - - /** - * Validate an invoice - * - * @param int $id Invoice ID - * @param int $idwarehouse Warehouse ID - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * - * @url POST {id}/validate - * - * @return array - * - * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - * @throws RestException 500 - */ - public function validate($id, $idwarehouse = 0, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } - - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. The invoice is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); - } - - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')' - ) - ); - } - - /** - * Get list of payments of a given supplier invoice - * - * @param int $id Id of SupplierInvoice - * - * @url GET {id}/payments - * - * @return array - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 405 - */ - public function getPayments($id) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) { - throw new RestException(401); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + $this->invoice->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->invoice); + } - $result = $this->invoice->getListOfPayments(); - if ($result < 0) { - throw new RestException(405, $this->invoice->error); - } + /** + * List invoices + * + * Get a list of supplier invoices + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter invoices of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" + * @return array Array of invoice objects + * + * @throws RestException + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') + { + global $db; - return $result; - } + $obj_ret = array(); + + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + + // 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; + + $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"; + $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"; + + $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 + + // Filter by status + if ($status == 'draft') { + $sql .= " AND t.fk_statut IN (0)"; + } + if ($status == 'unpaid') { + $sql .= " AND t.fk_statut IN (1)"; + } + if ($status == 'paid') { + $sql .= " AND t.fk_statut IN (2)"; + } + if ($status == 'cancelled') { + $sql .= " AND t.fk_statut IN (3)"; + } + // Insert sale filter + if ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit + 1, $offset); + } + + $result = $this->db->query($sql); + if ($result) { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $invoice_static = new FactureFournisseur($this->db); + if ($invoice_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($invoice_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve supplier invoice list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No supplier invoice found'); + } + return $obj_ret; + } + + /** + * Create supplier invoice object + * + * @param array $request_data Request datas + * + * @return int ID of supplier invoice + * + * @throws RestException 401 + * @throws RestException 500 + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach ($request_data as $field => $value) { + $this->invoice->$field = $value; + } + if (!array_key_exists('date', $request_data)) { + $this->invoice->date = dol_now(); + } + + if ($this->invoice->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating order", array_merge(array($this->invoice->error), $this->invoice->errors)); + } + return $this->invoice->id; + } + + /** + * Update supplier invoice + * + * @param int $id Id of supplier invoice to update + * @param array $request_data Datas + * + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->invoice->$field = $value; + } + + if ($this->invoice->update($id, DolibarrApiAccess::$user)) + return $this->get($id); + + return false; + } + + /** + * Delete supplier invoice + * + * @param int $id Supplier invoice ID + * + * @return array + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->supprimer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) + { + throw new RestException(500); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Supplier invoice deleted' + ) + ); + } + + /** + * Validate an invoice + * + * @param int $id Invoice ID + * @param int $idwarehouse Warehouse ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + * + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + * @throws RestException 500 + */ + public function validate($id, $idwarehouse = 0, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. The invoice is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')' + ) + ); + } + + /** + * Get list of payments of a given supplier invoice + * + * @param int $id Id of SupplierInvoice + * + * @url GET {id}/payments + * + * @return array + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 + */ + public function getPayments($id) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) { + throw new RestException(401); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->getListOfPayments(); + if ($result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } - /** - * Add payment line to a specific supplier invoice with the remain to pay as amount. - * - * @param int $id Id of invoice - * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paiementid {@from body} Payment mode Id {@min 1} - * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} - * @param int $accountid {@from body} Account Id {@min 1} - * @param string $num_payment {@from body} Payment number (optional) - * @param string $comment {@from body} Note (optional) - * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') - * @param string $chqbank {@from body} Issuer bank name (optional) - * - * @url POST {id}/payments - * - * @return int Payment ID - * @throws RestException 400 - * @throws RestException 401 - * @throws RestException 404 - */ - public function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '') - { - global $conf; + /** + * Add payment line to a specific supplier invoice with the remain to pay as amount. + * + * @param int $id Id of invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $payment_mode_id {@from body} Payment mode ID (look it up via REST GET to /setup/dictionary/payment_types) {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Bank account ID (look it up via REST GET to /bankaccounts) {@min 1} + * @param string $num_payment {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if payment_mode_id corresponds to 'CHQ'-payment type) + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST {id}/payments + * + * @return int Payment ID + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + */ + public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '') + { + global $conf; - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(403); - } - if (empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(403); + } + if (empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!empty($conf->banque->enabled)) { - if (empty($accountid)) { - throw new RestException(400, 'Account ID is mandatory'); - } - } + if (!empty($conf->banque->enabled)) { + if (empty($accountid)) { + throw new RestException(400, 'Bank account ID is mandatory'); + } + } - if (empty($paiementid)) { - throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); - } + if (empty($payment_mode_id)) { + throw new RestException(400, 'Payment mode ID is mandatory'); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } - // Calculate amount to pay - $totalpaye = $this->invoice->getSommePaiement(); - $totaldeposits = $this->invoice->getSumDepositsUsed(); - $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totaldeposits, 'MT'); + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totaldeposits, 'MT'); - $this->db->begin(); + $this->db->begin(); - $amounts = array(); - $multicurrency_amounts = array(); + $amounts = array(); + $multicurrency_amounts = array(); - $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = $resteapayer; + $resteapayer = price2num($resteapayer, 'MT'); + $amounts[$id] = $resteapayer; - // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = $newvalue; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); + $multicurrency_amounts[$id] = $newvalue; - // Creation of payment line - $paiement = new PaiementFourn($this->db); - $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id - $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = $paiementid; - $paiement->paiementcode = dol_getIdFromCode($this->db, $paiementid, 'c_paiement', 'id', 'code', 1); - $paiement->oper = $paiement->paiementcode; // For backward compatibility - $paiement->num_payment = $num_payment; - $paiement->note_public = $comment; + // Creation of payment line + $paiement = new PaiementFourn($this->db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = $payment_mode_id; + $paiement->paiementcode = dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1); + $paiement->oper = $paiement->paiementcode; // For backward compatibility + $paiement->num_payment = $num_payment; + $paiement->note_public = $comment; - $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($paiement_id < 0) - { - $this->db->rollback(); - throw new RestException(400, 'Payment error : '.$paiement->error); - } + $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices + 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) - { - $this->db->rollback(); - throw new RestException(400, 'Add payment to bank error : '.$paiement->error); - } - } + if (!empty($conf->banque->enabled)) { + $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } - $this->db->commit(); + $this->db->commit(); - return $paiement_id; - } + return $paiement_id; + } - /** - * Get lines of a supplier invoice - * - * @param int $id Id of supplier invoice - * - * @url GET {id}/lines - * - * @return array - */ - public function getLines($id) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } + /** + * Get lines of a supplier invoice + * + * @param int $id Id of supplier invoice + * + * @url GET {id}/lines + * + * @return array + */ + public function getLines($id) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->invoice->fetch_lines(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->invoice->fetch_lines(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Add a line to given supplier invoice - * - * @param int $id Id of supplier invoice to update - * @param array $request_data supplier invoice line data - * - * @url POST {id}/lines - * - * @return int|bool - */ - public function postLine($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } + /** + * Add a line to given supplier invoice + * + * @param int $id Id of supplier invoice to update + * @param array $request_data supplier invoice line data + * + * @url POST {id}/lines + * + * @return int|bool + */ + public function postLine($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; - $updateRes = $this->invoice->addline( - $request_data->description, - $request_data->pu_ht, + $updateRes = $this->invoice->addline( + $request_data->description, + $request_data->pu_ht, $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->qty, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->qty, $request_data->fk_product, $request_data->remise_percent, $request_data->date_start, @@ -559,54 +559,53 @@ class SupplierInvoices extends DolibarrApi $request_data->multicurrency_subprice, $request_data->ref_supplier, $request_data->special_code - ); + ); - if ($updateRes < 0) { - throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error); - } + if ($updateRes < 0) { + throw new RestException(400, 'Unable to insert the new line. Check your inputs. '.$this->invoice->error); + } - return $updateRes; - } + return $updateRes; + } - /** - * Update a line to a given supplier invoice - * - * @param int $id Id of supplier invoice to update - * @param int $lineid Id of line to update - * @param array $request_data InvoiceLine data - * - * @url PUT {id}/lines/{lineid} - * - * @return object - * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - */ - public function putLine($id, $lineid, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } + /** + * Update a line to a given supplier invoice + * + * @param int $id Id of supplier invoice to update + * @param int $lineid Id of line to update + * @param array $request_data InvoiceLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + * + * @throws RestException 401 Not allowed + * @throws RestException 404 Not found + * @throws RestException 304 Error + */ + public function putLine($id, $lineid, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { + throw new RestException(401); + } - $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } + $result = $this->invoice->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->invoice->updateline( - $lineid, - $request_data->description, - $request_data->pu_ht, + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->invoice->updateline( + $lineid, + $request_data->description, + $request_data->pu_ht, $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->qty, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->qty, $request_data->fk_product, 'HT', $request_data->info_bits, @@ -619,98 +618,98 @@ class SupplierInvoices extends DolibarrApi $request_data->fk_unit, $request_data->multicurrency_subprice, $request_data->ref_supplier - ); + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } else { - throw new RestException(304, $this->invoice->error); - } - } + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } else { + throw new RestException(304, $this->invoice->error); + } + } /** - * Deletes a line of a given supplier invoice - * - * @param int $id Id of supplier invoice - * @param int $lineid Id of the line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return array - * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 - */ - public function deleteLine($id, $lineid) - { + * Deletes a line of a given supplier invoice + * + * @param int $id Id of supplier invoice + * @param int $lineid Id of the line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return array + * + * @throws RestException 400 Bad parameters + * @throws RestException 401 Not allowed + * @throws RestException 404 Not found + * @throws RestException 405 Error + */ + public function deleteLine($id, $lineid) + { if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) { - throw new RestException(401); - } + throw new RestException(401); + } $result = $this->invoice->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier invoice not found'); - } + if (!$result) { + throw new RestException(404, 'Supplier invoice not found'); + } - if (empty($lineid)) { - throw new RestException(400, 'Line ID is mandatory'); - } + if (empty($lineid)) { + throw new RestException(400, 'Line ID is mandatory'); + } - if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) { + 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->invoice->deleteline($lineid); - if ($updateRes > 0) { - return $this->get($id); - } else { - throw new RestException(405, $this->invoice->error); - } - } + $updateRes = $this->invoice->deleteline($lineid); + if ($updateRes > 0) { + return $this->get($id); + } else { + throw new RestException(405, $this->invoice->error); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->rowid); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); + unset($object->rowid); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Datas to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $invoice = array(); - foreach (SupplierInvoices::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $invoice[$field] = $data[$field]; - } - return $invoice; - } + /** + * Validate fields before create or update object + * + * @param array $data Datas to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $invoice = array(); + foreach (SupplierInvoices::$FIELDS as $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 b180016bdd9..0fd06790011 100644 --- a/htdocs/fourn/class/api_supplier_orders.class.php +++ b/htdocs/fourn/class/api_supplier_orders.class.php @@ -149,7 +149,7 @@ class SupplierOrders extends DolibarrApi $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql .= $db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) { @@ -157,26 +157,26 @@ class SupplierOrders extends DolibarrApi } $offset = $limit * $page; - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $this->db->plimit($limit + 1, $offset); } - $result = $db->query($sql); + $result = $this->db->query($sql); if ($result) { $i = 0; - $num = $db->num_rows($result); + $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) { - $obj = $db->fetch_object($result); - $order_static = new CommandeFournisseur($db); + $obj = $this->db->fetch_object($result); + $order_static = new CommandeFournisseur($this->db); if ($order_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($order_static); } $i++; } } else { - throw new RestException(503, 'Error when retrieve supplier order list : '.$db->lasterror()); + throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror()); } if (!count($obj_ret)) { throw new RestException(404, 'No supplier order found'); @@ -187,7 +187,7 @@ class SupplierOrders extends DolibarrApi /** * Create supplier order object * - * Example: {"ref": "auto", "ref_supplier": "1234", "socid": "1", "multicurrency_code": "SEK", "multicurrency_tx": 1, "tva_tx": 25, "note": "Imported via the REST API"} + * Example: {"ref": "auto", "ref_supplier": "1234", "socid": "1", "multicurrency_code": "SEK", "multicurrency_tx": 1, "tva_tx": 25, "note": "Imported via the REST API"} * * @param array $request_data Request datas * @return int ID of supplier order diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index f6d506a28be..f354b89186d 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -3,7 +3,7 @@ * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2010-2014 Juanjo Menent + * Copyright (C) 2010-2020 Juanjo Menent * Copyright (C) 2010-2018 Philippe Grand * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2013 Florian Henry @@ -42,22 +42,22 @@ require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; */ class CommandeFournisseur extends CommonOrder { - /** + /** * @var string ID to identify managed object */ public $element = 'order_supplier'; - /** + /** * @var string Name of table without prefix where object is stored */ public $table_element = 'commande_fournisseur'; - /** + /** * @var int Name of subtable line */ public $table_element_line = 'commande_fournisseurdet'; - /** + /** * @var int Field with ID of parent key if this field has a parent */ public $fk_element = 'fk_commande'; @@ -67,24 +67,24 @@ class CommandeFournisseur extends CommonOrder */ public $picto = 'supplier_order'; - /** - * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - * @var int - */ - public $ismultientitymanaged = 1; + /** + * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int + */ + public $ismultientitymanaged = 1; - /** - * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user - * @var integer - */ - public $restrictiononfksoc = 1; + /** + * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user + * @var integer + */ + public $restrictiononfksoc = 1; - /** - * {@inheritdoc} - */ - protected $table_ref_field = 'ref'; + /** + * {@inheritdoc} + */ + protected $table_ref_field = 'ref'; - /** + /** * @var int ID */ public $id; @@ -93,75 +93,70 @@ class CommandeFournisseur extends CommonOrder * Supplier order reference * @var string */ - public $ref; + public $ref; - public $ref_supplier; - public $brouillon; - public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/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 - // -> 9=Refused -> (reopen) 1=Validated - // Note: billed or not is on another field "billed" - public $statuts; // List of status + public $ref_supplier; + public $brouillon; + public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/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 + // -> 9=Refused -> (reopen) 1=Validated + // Note: billed or not is on another field "billed" + public $statuts; // List of status - public $billed; + public $billed; - public $socid; - public $fourn_id; - public $date; - public $date_valid; - public $date_approve; - public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set - public $date_commande; + public $socid; + public $fourn_id; + public $date; + public $date_valid; + public $date_approve; + public $date_approve2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set + public $date_commande; - /** - * Delivery date - */ - public $date_livraison; + /** + * Delivery date + */ + public $date_livraison; - public $total_ht; - public $total_tva; - public $total_localtax1; // Total Local tax 1 - public $total_localtax2; // Total Local tax 2 - public $total_ttc; - public $source; + public $total_ht; + public $total_tva; + public $total_localtax1; // Total Local tax 1 + public $total_localtax2; // Total Local tax 2 + public $total_ttc; + public $source; /** * @deprecated * @see $note_private, $note_public */ - public $note; + public $note; public $note_private; - public $note_public; - public $model_pdf; + public $note_public; + public $model_pdf; - /** - * @var int ID - */ - public $fk_project; + /** + * @var int ID + */ + public $fk_project; - public $cond_reglement_id; - public $cond_reglement_code; + public $cond_reglement_id; + public $cond_reglement_code; - /** - * @var int ID - */ - public $fk_account; + /** + * @var int ID + */ + public $fk_account; - public $mode_reglement_id; - public $mode_reglement_code; - public $user_author_id; - public $user_valid_id; - public $user_approve_id; - public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set + public $mode_reglement_id; + public $mode_reglement_code; + public $user_author_id; + public $user_valid_id; + public $user_approve_id; + public $user_approve_id2; // Used when SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set - //Incoterms - public $fk_incoterms; - public $location_incoterms; - public $label_incoterms; //Used into tooltip - - public $extraparams = array(); + public $extraparams = array(); /** * @var CommandeFournisseurLigne[] @@ -169,74 +164,74 @@ class CommandeFournisseur extends CommonOrder public $lines = array(); //Add for supplier_proposal - public $origin; - public $origin_id; - public $linked_objects = array(); + public $origin; + public $origin_id; + public $linked_objects = array(); // Multicurrency /** - * @var int ID - */ - public $fk_multicurrency; + * @var int ID + */ + public $fk_multicurrency; - public $multicurrency_code; - public $multicurrency_tx; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; + public $multicurrency_code; + public $multicurrency_tx; + public $multicurrency_total_ht; + public $multicurrency_total_tva; + public $multicurrency_total_ttc; - public $fields = array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15), - 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), - 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>25), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1), - 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>35), - 'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>40), - 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk projet', 'enabled'=>1, 'visible'=>-1, 'position'=>45), - 'date_creation' =>array('type'=>'datetime', 'label'=>'Date creation', 'enabled'=>1, 'visible'=>-1, 'position'=>50), - 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>55), - 'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>60), - 'date_approve2' =>array('type'=>'datetime', 'label'=>'Date approve2', 'enabled'=>1, 'visible'=>-1, 'position'=>65), - 'date_commande' =>array('type'=>'date', 'label'=>'Date commande', 'enabled'=>1, 'visible'=>-1, 'position'=>70), - 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>75), - 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>80), - 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>85), - 'fk_user_approve' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserApproval', 'enabled'=>1, 'visible'=>-1, 'position'=>90), - 'fk_user_approve2' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserSecondApproval', 'enabled'=>1, 'visible'=>-1, 'position'=>95), - 'source' =>array('type'=>'smallint(6)', 'label'=>'Source', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100), - 'billed' =>array('type'=>'smallint(6)', 'label'=>'Billed', 'enabled'=>1, 'visible'=>-1, 'position'=>110), - '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), - '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), - 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>150, 'isameasure'=>1), - 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>155), - 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>160), - 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPDF', 'enabled'=>1, 'visible'=>0, 'position'=>165), - 'fk_input_method' =>array('type'=>'integer', 'label'=>'InputMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>170), - 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>175), - 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>180), - 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>190), - 'date_livraison' =>array('type'=>'datetime', 'label'=>'DeliveryDate', 'enabled'=>1, 'visible'=>-1, 'position'=>195), - 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>200), - 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>-1, 'position'=>205), - 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>-1, 'position'=>210), - 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>215), - 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>220), - 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>1, 'visible'=>-1, 'position'=>225), - 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>230), - 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>235), - 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>240), - 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>245), - 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), - ); + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), + 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>25), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>35), + 'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>40), + 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk projet', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + 'date_creation' =>array('type'=>'datetime', 'label'=>'Date creation', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'date_approve' =>array('type'=>'datetime', 'label'=>'Date approve', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'date_approve2' =>array('type'=>'datetime', 'label'=>'Date approve2', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'date_commande' =>array('type'=>'date', 'label'=>'Date commande', 'enabled'=>1, 'visible'=>-1, 'position'=>70), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>80), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>85), + 'fk_user_approve' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserApproval', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'fk_user_approve2' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserSecondApproval', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + 'source' =>array('type'=>'smallint(6)', 'label'=>'Source', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>100), + 'billed' =>array('type'=>'smallint(6)', 'label'=>'Billed', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + '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), + '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), + 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>150, 'isameasure'=>1), + 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>155), + 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>160), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPDF', 'enabled'=>1, 'visible'=>0, 'position'=>165), + 'fk_input_method' =>array('type'=>'integer', 'label'=>'InputMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>170), + 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>175), + 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>180), + 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'date_livraison' =>array('type'=>'datetime', 'label'=>'DeliveryDate', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>200), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>-1, 'position'=>205), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>-1, 'position'=>210), + 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>220), + 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>1, 'visible'=>-1, 'position'=>225), + 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>230), + 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>235), + 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>240), + 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>245), + 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), + ); /** @@ -288,111 +283,112 @@ class CommandeFournisseur extends CommonOrder /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; - $this->products = array(); - } + $this->products = array(); + } - /** - * Get object and lines from database - * - * @param int $id Id of order to load - * @param string $ref Ref of object - * @return int >0 if OK, <0 if KO, 0 if not found - */ - public function fetch($id, $ref = '') - { - global $conf; + /** + * Get object and lines from database + * + * @param int $id Id of order to load + * @param string $ref Ref of object + * @return int >0 if OK, <0 if KO, 0 if not found + */ + public function fetch($id, $ref = '') + { + global $conf; - // Check parameters - if (empty($id) && empty($ref)) return -1; + // Check parameters + 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 .= " 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,"; - $sql .= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,"; - $sql .= " c.fk_account,"; - $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 .= " 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'; - $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id"; - $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'; + $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 .= " 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,"; + $sql .= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,"; + $sql .= " c.fk_account,"; + $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 .= " 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'; + $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON c.fk_cond_reglement = cr.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON c.fk_mode_reglement = p.id"; + $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) - { - $obj = $this->db->fetch_object($resql); - if (!$obj) - { - $this->error = 'Bill with id '.$id.' not found'; - dol_syslog(get_class($this).'::fetch '.$this->error); - return 0; - } + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if (!$obj) + { + $this->error = 'Bill with id '.$id.' not found'; + dol_syslog(get_class($this).'::fetch '.$this->error); + return 0; + } - $this->id = $obj->rowid; - $this->entity = $obj->entity; + $this->id = $obj->rowid; + $this->entity = $obj->entity; - $this->ref = $obj->ref; - $this->ref_supplier = $obj->ref_supplier; - $this->socid = $obj->fk_soc; - $this->fourn_id = $obj->fk_soc; - $this->statut = $obj->fk_statut; - $this->status = $obj->fk_statut; - $this->billed = $obj->billed; - $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $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_localtax1 = $obj->localtax1; - $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total_ttc; - $this->date = $this->db->jdate($obj->date_creation); - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->date_approve = $this->db->jdate($obj->date_approve); - $this->date_approve2 = $this->db->jdate($obj->date_approve2); - $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier + $this->ref = $obj->ref; + $this->ref_supplier = $obj->ref_supplier; + $this->socid = $obj->fk_soc; + $this->fourn_id = $obj->fk_soc; + $this->statut = $obj->fk_statut; + $this->status = $obj->fk_statut; + $this->billed = $obj->billed; + $this->user_author_id = $obj->fk_user_author; + $this->user_valid_id = $obj->fk_user_valid; + $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_localtax1 = $obj->localtax1; + $this->total_localtax2 = $obj->localtax2; + $this->total_ttc = $obj->total_ttc; + $this->date = $this->db->jdate($obj->date_creation); + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_approve = $this->db->jdate($obj->date_approve); + $this->date_approve2 = $this->db->jdate($obj->date_approve2); + $this->date_commande = $this->db->jdate($obj->date_commande); // date we make the order to supplier $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->remise_percent = $obj->remise_percent; - $this->methode_commande_id = $obj->fk_input_method; - $this->methode_commande = $obj->methode_commande; + $this->remise_percent = $obj->remise_percent; + $this->methode_commande_id = $obj->fk_input_method; + $this->methode_commande = $obj->methode_commande; - $this->source = $obj->source; - $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->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->note = $obj->note_private; // deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->modelpdf = $obj->model_pdf; + $this->source = $obj->source; + $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->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->note = $obj->note_private; // deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -407,109 +403,109 @@ class CommandeFournisseur extends CommonOrder $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); - $this->db->free($resql); + $this->db->free($resql); - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) $this->brouillon = 1; - /* + /* * Lines */ - $result = $this->fetch_lines(); - if ($result < 0) - { - return -1; - } else { - return 1; - } - } else { - $this->error = $this->db->error()." sql=".$sql; - return -1; - } - } + $result = $this->fetch_lines(); + if ($result < 0) + { + return -1; + } else { + return 1; + } + } else { + $this->error = $this->db->error()." sql=".$sql; + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load array lines - * - * @param int $only_product Return only physical products - * @return int <0 if KO, >0 if OK - */ - public function fetch_lines($only_product = 0) - { - global $conf; - // phpcs:enable - //$result=$this->fetch_lines(); - $this->lines = array(); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load array lines + * + * @param int $only_product Return only physical products + * @return int <0 if KO, >0 if OK + */ + public function fetch_lines($only_product = 0) + { + global $conf; + // phpcs:enable + //$result=$this->fetch_lines(); + $this->lines = array(); - $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,"; - $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,"; - $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,"; - $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,"; - $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; - $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'; + $sql = "SELECT l.rowid, l.ref as ref_supplier, l.fk_product, l.product_type, l.label, l.description, l.qty,"; + $sql .= " l.vat_src_code, l.tva_tx, l.remise_percent, l.subprice,"; + $sql .= " l.localtax1_tx, l. localtax2_tx, l.localtax1_type, l. localtax2_type, l.total_localtax1, l.total_localtax2,"; + $sql .= " l.total_ht, l.total_tva, l.total_ttc, l.special_code, l.fk_parent_line, l.rang,"; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; + $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)) $sql .= ", pfp.rowid as fk_pfp, pfp.packaging"; - $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 .= " 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)) $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'; - $sql .= " ORDER BY l.rang, l.rowid"; - //print $sql; + $sql .= " WHERE l.fk_commande = ".$this->id; + 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) - { - $num = $this->db->num_rows($result); - $i = 0; + dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); + while ($i < $num) + { + $objp = $this->db->fetch_object($result); - $line = new CommandeFournisseurLigne($this->db); + $line = new CommandeFournisseurLigne($this->db); - $line->id = $objp->rowid; - $line->desc = $objp->description; - $line->description = $objp->description; - $line->qty = $objp->qty; - $line->tva_tx = $objp->tva_tx; - $line->localtax1_tx = $objp->localtax1_tx; - $line->localtax2_tx = $objp->localtax2_tx; - $line->localtax1_type = $objp->localtax1_type; - $line->localtax2_type = $objp->localtax2_type; - $line->subprice = $objp->subprice; - $line->pu_ht = $objp->subprice; - $line->remise_percent = $objp->remise_percent; + $line->id = $objp->rowid; + $line->desc = $objp->description; + $line->description = $objp->description; + $line->qty = $objp->qty; + $line->tva_tx = $objp->tva_tx; + $line->localtax1_tx = $objp->localtax1_tx; + $line->localtax2_tx = $objp->localtax2_tx; + $line->localtax1_type = $objp->localtax1_type; + $line->localtax2_type = $objp->localtax2_type; + $line->subprice = $objp->subprice; + $line->pu_ht = $objp->subprice; + $line->remise_percent = $objp->remise_percent; - $line->vat_src_code = $objp->vat_src_code; - $line->total_ht = $objp->total_ht; - $line->total_tva = $objp->total_tva; - $line->total_localtax1 = $objp->total_localtax1; - $line->total_localtax2 = $objp->total_localtax2; - $line->total_ttc = $objp->total_ttc; - $line->product_type = $objp->product_type; + $line->vat_src_code = $objp->vat_src_code; + $line->total_ht = $objp->total_ht; + $line->total_tva = $objp->total_tva; + $line->total_localtax1 = $objp->total_localtax1; + $line->total_localtax2 = $objp->total_localtax2; + $line->total_ttc = $objp->total_ttc; + $line->product_type = $objp->product_type; - $line->fk_product = $objp->fk_product; + $line->fk_product = $objp->fk_product; - $line->libelle = $objp->product_label; // deprecated - $line->product_label = $objp->product_label; - $line->product_desc = $objp->product_desc; + $line->libelle = $objp->product_label; // deprecated + $line->product_label = $objp->product_label; + $line->product_desc = $objp->product_desc; - $line->ref = $objp->product_ref; // Ref of product - $line->product_ref = $objp->product_ref; // Ref of product - $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 + $line->ref = $objp->product_ref; // Ref of product + $line->product_ref = $objp->product_ref; // Ref of product + $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)) { @@ -518,740 +514,740 @@ class CommandeFournisseur extends CommonOrder } $line->date_start = $this->db->jdate($objp->date_start); - $line->date_end = $this->db->jdate($objp->date_end); - $line->fk_unit = $objp->fk_unit; + $line->date_end = $this->db->jdate($objp->date_end); + $line->fk_unit = $objp->fk_unit; - // Multicurrency - $line->fk_multicurrency = $objp->fk_multicurrency; - $line->multicurrency_code = $objp->multicurrency_code; - $line->multicurrency_subprice = $objp->multicurrency_subprice; - $line->multicurrency_total_ht = $objp->multicurrency_total_ht; - $line->multicurrency_total_tva = $objp->multicurrency_total_tva; - $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; + // Multicurrency + $line->fk_multicurrency = $objp->fk_multicurrency; + $line->multicurrency_code = $objp->multicurrency_code; + $line->multicurrency_subprice = $objp->multicurrency_subprice; + $line->multicurrency_total_ht = $objp->multicurrency_total_ht; + $line->multicurrency_total_tva = $objp->multicurrency_total_tva; + $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $line->special_code = $objp->special_code; - $line->fk_parent_line = $objp->fk_parent_line; + $line->special_code = $objp->special_code; + $line->fk_parent_line = $objp->fk_parent_line; - $line->rang = $objp->rang; + $line->rang = $objp->rang; - // Retreive all extrafield - // fetch optionals attributes and labels - $line->fetch_optionals(); + // Retreive all extrafield + // fetch optionals attributes and labels + $line->fetch_optionals(); - $this->lines[$i] = $line; + $this->lines[$i] = $line; - $i++; - } - $this->db->free($result); + $i++; + } + $this->db->free($result); - return $num; - } else { - $this->error = $this->db->error()." sql=".$sql; - return -1; - } - } + return $num; + } else { + $this->error = $this->db->error()." sql=".$sql; + return -1; + } + } - /** - * Validate an order - * - * @param User $user Validator User - * @param int $idwarehouse Id of warehouse to use for stock decrease - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function valid($user, $idwarehouse = 0, $notrigger = 0) - { - global $langs, $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Validate an order + * + * @param User $user Validator User + * @param int $idwarehouse Id of warehouse to use for stock decrease + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function valid($user, $idwarehouse = 0, $notrigger = 0) + { + global $langs, $conf; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error = 0; + $error = 0; - 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))) - { - $this->db->begin(); + 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))) + { + $this->db->begin(); - // Definition of supplier order numbering model name - $soc = new Societe($this->db); - $soc->fetch($this->fourn_id); + // Definition of supplier order numbering model name + $soc = new Societe($this->db); + $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 - { - $num = $this->getNextNumRef($soc); - } else { - $num = $this->ref; - } - $this->newref = dol_sanitizeFileName($num); + // 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 + { + $num = $this->getNextNumRef($soc); + } else { + $num = $this->ref; + } + $this->newref = dol_sanitizeFileName($num); - $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur"; - $sql .= " SET ref='".$this->db->escape($num)."',"; - $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; - $sql .= " date_valid='".$this->db->idate(dol_now())."',"; - $sql .= " fk_user_valid = ".$user->id; - $sql .= " WHERE rowid = ".$this->id; - $sql .= " AND fk_statut = ".self::STATUS_DRAFT; + $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur"; + $sql .= " SET ref='".$this->db->escape($num)."',"; + $sql .= " fk_statut = ".self::STATUS_VALIDATED.","; + $sql .= " date_valid='".$this->db->idate(dol_now())."',"; + $sql .= " fk_user_valid = ".$user->id; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND fk_statut = ".self::STATUS_DRAFT; - $resql = $this->db->query($sql); - if (!$resql) - { - dol_print_error($this->db); - $error++; - } + $resql = $this->db->query($sql); + 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++; // End call triggers - } + } - if (!$error) - { - $this->oldref = $this->ref; + if (!$error) + { + $this->oldref = $this->ref; - // Rename directory if dir was a temporary 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(); } + // Rename directory if dir was a temporary 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(); } - // 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)) - { - dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); + // 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)) + { + dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$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) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @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) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } - if (!$error) - { - $result = 1; - $this->statut = self::STATUS_VALIDATED; - $this->ref = $num; - } + if (!$error) + { + $result = 1; + $this->statut = self::STATUS_VALIDATED; + $this->ref = $num; + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = 'NotAuthorized'; - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); - return -1; - } - } - - /** - * Return label of the status of object - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->statut, $mode, $this->billed); - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return label of a status - * - * @param int $status Id statut - * @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 int $billed 1=Billed - * @return string Label of status - */ - public function LibStatut($status, $mode = 0, $billed = 0) - { - // phpcs:enable - global $conf, $langs; - - if (empty($this->statuts) || empty($this->statutshort)) { - $langs->load('orders'); - - $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'; - $this->statuts[4] = 'StatusSupplierOrderReceivedPartially'; - $this->statuts[5] = 'StatusSupplierOrderReceivedAll'; - $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled - $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled - $this->statuts[9] = 'StatusSupplierOrderRefused'; - - // List of language codes for status - $this->statutshort[0] = 'StatusSupplierOrderDraftShort'; - $this->statutshort[1] = 'StatusSupplierOrderValidatedShort'; - $this->statutshort[2] = 'StatusSupplierOrderApprovedShort'; - $this->statutshort[3] = 'StatusSupplierOrderOnProcessShort'; - $this->statutshort[4] = 'StatusSupplierOrderReceivedPartiallyShort'; - $this->statutshort[5] = 'StatusSupplierOrderReceivedAllShort'; - $this->statutshort[6] = 'StatusSupplierOrderCanceledShort'; - $this->statutshort[7] = 'StatusSupplierOrderCanceledShort'; - $this->statutshort[9] = 'StatusSupplierOrderRefusedShort'; - } - - $statustrans = array( - 0 => 'status0', - 1 => 'status1b', - 2 => 'status1', - 3 => 'status4', - 4 => 'status4b', - 5 => 'status6', - 6 => 'status9', - 7 => 'status9', - 9 => 'status9', - ); - - $statusClass = 'status0'; - if (!empty($statustrans[$status])) { - $statusClass = $statustrans[$status]; - } - - $billedtext = ''; - if ($billed) { - $billedtext = ' - '.$langs->trans("Billed"); - } - if ($status == 5 && $billed) $statusClass = 'status6'; - - $statusLong = $langs->trans($this->statuts[$status]).$billedtext; - $statusShort = $langs->trans($this->statutshort[$status]); - - return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode); - } - - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option On what the link points - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param int $addlinktonotes Add link to show notes - * @return string Chain with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) - { - global $langs, $conf, $user; - - $result = ''; - $label = ''.$langs->trans("ShowOrder").''; - if (!empty($this->ref)) - $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_supplier)) - $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); - 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)) - $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - - $picto = 'order'; - $url = DOL_URL_ROOT.'/fourn/commande/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("ShowOrder"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } - - $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; - $result .= $linkend; - - if ($addlinktonotes) - { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - $notetoshow = $langs->trans("ViewPrivateNote").':
    '.dol_string_nohtmltag($txttoshow, 1); - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } - } - - return $result; - } - - - /** - * Returns the following order reference not used depending on the numbering model activated - * defined within COMMANDE_SUPPLIER_ADDON_NUMBER - * - * @param Societe $soc company object - * @return string free reference for the invoice - */ - public function getNextNumRef($soc) - { - global $db, $langs, $conf; - $langs->load("orders"); - - if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) - { - $mybool = false; - - $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php'; - $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER; - - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_order/"); - - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } - - if ($mybool === false) { - dol_print_error('', "Failed to include file ".$file); - return ''; - } - - $obj = new $classname(); - $numref = $obj->getNextValue($soc, $this); - - if ($numref != "") - { - return $numref; - } else { - $this->error = $obj->error; - return -1; - } - } else { - $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined"; - return -2; - } - } - /** - * Class invoiced the supplier order - * - * @param User $user Object user making the change - * @return int <0 if KO, >0 if KO - */ - public function classifyBilled(User $user) - { - $error = 0; - $this->db->begin(); - - $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) - { - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); - if ($result < 0) $error++; - // End call triggers - } - - if (!$error) - { - $this->billed = 1; - - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - dol_print_error($this->db); - - $this->db->rollback(); + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = 'NotAuthorized'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; - } - } + } + } - /** - * Approve a supplier order - * - * @param User $user Object user - * @param int $idwarehouse Id of warhouse for stock change - * @param int $secondlevel 0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set) - * @return int <0 if KO, >0 if OK - */ - public function approve($user, $idwarehouse = 0, $secondlevel = 0) - { - global $langs, $conf; + /** + * Return label of the status of object + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode, $this->billed); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of a status + * + * @param int $status Id statut + * @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 int $billed 1=Billed + * @return string Label of status + */ + public function LibStatut($status, $mode = 0, $billed = 0) + { + // phpcs:enable + global $conf, $langs; + + if (empty($this->statuts) || empty($this->statutshort)) { + $langs->load('orders'); + + $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'; + $this->statuts[4] = 'StatusSupplierOrderReceivedPartially'; + $this->statuts[5] = 'StatusSupplierOrderReceivedAll'; + $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled + $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled + $this->statuts[9] = 'StatusSupplierOrderRefused'; + + // List of language codes for status + $this->statutshort[0] = 'StatusSupplierOrderDraftShort'; + $this->statutshort[1] = 'StatusSupplierOrderValidatedShort'; + $this->statutshort[2] = 'StatusSupplierOrderApprovedShort'; + $this->statutshort[3] = 'StatusSupplierOrderOnProcessShort'; + $this->statutshort[4] = 'StatusSupplierOrderReceivedPartiallyShort'; + $this->statutshort[5] = 'StatusSupplierOrderReceivedAllShort'; + $this->statutshort[6] = 'StatusSupplierOrderCanceledShort'; + $this->statutshort[7] = 'StatusSupplierOrderCanceledShort'; + $this->statutshort[9] = 'StatusSupplierOrderRefusedShort'; + } + + $statustrans = array( + 0 => 'status0', + 1 => 'status1b', + 2 => 'status1', + 3 => 'status4', + 4 => 'status4b', + 5 => 'status6', + 6 => 'status9', + 7 => 'status9', + 9 => 'status9', + ); + + $statusClass = 'status0'; + if (!empty($statustrans[$status])) { + $statusClass = $statustrans[$status]; + } + + $billedtext = ''; + if ($billed) { + $billedtext = ' - '.$langs->trans("Billed"); + } + if ($status == 5 && $billed) $statusClass = 'status6'; + + $statusLong = $langs->trans($this->statuts[$status]).$billedtext; + $statusShort = $langs->trans($this->statutshort[$status]); + + return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode); + } + + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option On what the link points + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param int $addlinktonotes Add link to show notes + * @return string Chain with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) + { + global $langs, $conf, $user; + + $result = ''; + $label = ''.$langs->trans("PurchaseOrder").''; + if (!empty($this->ref)) + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_supplier)) + $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); + 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)) + $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + + $picto = 'order'; + $url = DOL_URL_ROOT.'/fourn/commande/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("ShowOrder"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } + + $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; + $result .= $linkend; + + if ($addlinktonotes) + { + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + $notetoshow = $langs->trans("ViewPrivateNote").':
    '.dol_string_nohtmltag($txttoshow, 1); + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } + } + + return $result; + } + + + /** + * Returns the following order reference not used depending on the numbering model activated + * defined within COMMANDE_SUPPLIER_ADDON_NUMBER + * + * @param Societe $soc company object + * @return string free reference for the invoice + */ + public function getNextNumRef($soc) + { + global $db, $langs, $conf; + $langs->load("orders"); + + if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) + { + $mybool = false; + + $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php'; + $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/supplier_order/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + $obj = new $classname(); + $numref = $obj->getNextValue($soc, $this); + + if ($numref != "") + { + return $numref; + } else { + $this->error = $obj->error; + return -1; + } + } else { + $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined"; + return -2; + } + } + /** + * Class invoiced the supplier order + * + * @param User $user Object user making the change + * @return int <0 if KO, >0 if KO + */ + public function classifyBilled(User $user) + { + $error = 0; + $this->db->begin(); + + $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) + { + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); + if ($result < 0) $error++; + // End call triggers + } + + if (!$error) + { + $this->billed = 1; + + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + dol_print_error($this->db); + + $this->db->rollback(); + return -1; + } + } + + /** + * Approve a supplier order + * + * @param User $user Object user + * @param int $idwarehouse Id of warhouse for stock change + * @param int $secondlevel 0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set) + * @return int <0 if KO, >0 if OK + */ + public function approve($user, $idwarehouse = 0, $secondlevel = 0) + { + global $langs, $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::approve"); + dol_syslog(get_class($this)."::approve"); - if ($user->rights->fournisseur->commande->approuver) - { - $now = dol_now(); + if ($user->rights->fournisseur->commande->approuver) + { + $now = dol_now(); - $this->db->begin(); + $this->db->begin(); // Definition of order numbering model name - $soc = new Societe($this->db); - $soc->fetch($this->fourn_id); + $soc = new Societe($this->db); + $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 - { - $num = $this->getNextNumRef($soc); - } else { - $num = $this->ref; - } - $this->newref = dol_sanitizeFileName($num); + // 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 + { + $num = $this->getNextNumRef($soc); + } else { + $num = $this->ref; + } + $this->newref = dol_sanitizeFileName($num); - // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated) + // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated) $movetoapprovestatus = true; $comment = ''; - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET ref='".$this->db->escape($num)."',"; 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)) - { - $movetoapprovestatus = false; // second level approval not done - $comment = ' (first level)'; - } - } + $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)) + { + $movetoapprovestatus = false; // second level approval not done + $comment = ' (first level)'; + } + } } else // request a second level approval { - $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 - $comment = ' (second level)'; + $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 + $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; - $sql .= " WHERE rowid = ".$this->id; - $sql .= " AND 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 { $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)) - { - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; - $langs->load("agenda"); + // 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)) + { + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; + $langs->load("agenda"); - $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - // Product with reference - 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'); - $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++; } - unset($this->line); - } - } - } + $cpt = count($this->lines); + for ($i = 0; $i < $cpt; $i++) + { + // Product with reference + 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'); + $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++; } + unset($this->line); + } + } + } - if (!$error) - { + if (!$error) + { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user); if ($result < 0) $error++; // End call triggers - } + } - if (!$error) - { - $this->ref = $this->newref; + if (!$error) + { + $this->ref = $this->newref; - if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED; + if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED; else $this->statut = self::STATUS_VALIDATED; - if (empty($secondlevel)) // standard or first level approval + if (empty($secondlevel)) // standard or first level approval { - $this->date_approve = $now; - $this->user_approve_id = $user->id; + $this->date_approve = $now; + $this->user_approve_id = $user->id; } else // request a second level approval { - $this->date_approve2 = $now; - $this->user_approve_id2 = $user->id; + $this->date_approve2 = $now; + $this->user_approve_id2 = $user->id; } - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - return -1; - } - } else { - dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR); - } - return -1; - } + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + return -1; + } + } else { + dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR); + } + return -1; + } - /** - * Refuse an order - * - * @param User $user User making action - * @return int 0 if Ok, <0 if Ko - */ - public function refuse($user) - { - global $conf, $langs; + /** + * Refuse an order + * + * @param User $user User making action + * @return int 0 if Ok, <0 if Ko + */ + public function refuse($user) + { + global $conf, $langs; $error = 0; - dol_syslog(get_class($this)."::refuse"); - $result = 0; - if ($user->rights->fournisseur->commande->approuver) - { - $this->db->begin(); + dol_syslog(get_class($this)."::refuse"); + $result = 0; + 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; + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED; + $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - $result = 0; + 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) - { - $error++; - $this->db->rollback(); - } else $this->db->commit(); + { + $error++; + $this->db->rollback(); + } else $this->db->commit(); // End call triggers - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::refuse Error -1"); - $result = -1; - } - } else { - dol_syslog(get_class($this)."::refuse Not Authorized"); - } - return $result; - } + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::refuse Error -1"); + $result = -1; + } + } else { + dol_syslog(get_class($this)."::refuse Not Authorized"); + } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Cancel an approved order. - * The cancellation is done after approval - * - * @param User $user User making action - * @param int $idwarehouse Id warehouse to use for stock change (not used for supplier orders). - * @return int >0 if Ok, <0 if Ko - */ - public function Cancel($user, $idwarehouse = -1) - { - // phpcs:enable - global $langs, $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Cancel an approved order. + * The cancellation is done after approval + * + * @param User $user User making action + * @param int $idwarehouse Id warehouse to use for stock change (not used for supplier orders). + * @return int >0 if Ok, <0 if Ko + */ + public function Cancel($user, $idwarehouse = -1) + { + // phpcs:enable + global $langs, $conf; - $error = 0; + $error = 0; - //dol_syslog("CommandeFournisseur::Cancel"); - $result = 0; - if ($user->rights->fournisseur->commande->commander) - { - $statut = self::STATUS_CANCELED; + //dol_syslog("CommandeFournisseur::Cancel"); + $result = 0; + if ($user->rights->fournisseur->commande->commander) + { + $statut = self::STATUS_CANCELED; - $this->db->begin(); + $this->db->begin(); - $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)) - { - $result = 0; + $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)) + { + $result = 0; // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user); if ($result < 0) $error++; // End call triggers - if ($error == 0) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::cancel ".$this->error); - return -1; - } - } else { - dol_syslog(get_class($this)."::cancel Not Authorized"); - return -1; - } - } + if ($error == 0) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::cancel ".$this->error); + return -1; + } + } else { + dol_syslog(get_class($this)."::cancel Not Authorized"); + return -1; + } + } - /** - * Submit a supplier order to supplier - * - * @param User $user User making change - * @param integer $date Date - * @param int $methode Method - * @param string $comment Comment - * @return int <0 if KO, >0 if OK - */ - public function commande($user, $date, $methode, $comment = '') - { - global $langs; - dol_syslog(get_class($this)."::commande"); - $error = 0; - if ($user->rights->fournisseur->commande->commander) - { - $this->db->begin(); + /** + * Submit a supplier order to supplier + * + * @param User $user User making change + * @param integer $date Date + * @param int $methode Method + * @param string $comment Comment + * @return int <0 if KO, >0 if OK + */ + public function commande($user, $date, $methode, $comment = '') + { + global $langs; + dol_syslog(get_class($this)."::commande"); + $error = 0; + if ($user->rights->fournisseur->commande->commander) + { + $this->db->begin(); - $newnoteprivate = $this->note_private; - if ($comment) $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment); + $newnoteprivate = $this->note_private; + 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 = "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; - dol_syslog(get_class($this)."::commande", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->statut = self::STATUS_ORDERSENT; - $this->methode_commande_id = $methode; - $this->date_commande = $date; - $this->context = array('comments' => $comment); + dol_syslog(get_class($this)."::commande", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->statut = self::STATUS_ORDERSENT; + $this->methode_commande_id = $methode; + $this->date_commande = $date; + $this->context = array('comments' => $comment); - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); - if ($result < 0) $error++; - // End call triggers - } else { - $error++; - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - } + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); + if ($result < 0) $error++; + // End call triggers + } else { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + } - if (!$error) - { - $this->db->commit(); - } else { - $this->db->rollback(); - } - } else { - $error++; - $this->error = $langs->trans('NotAuthorized'); - $this->errors[] = $langs->trans('NotAuthorized'); - dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING); - } + if (!$error) + { + $this->db->commit(); + } else { + $this->db->rollback(); + } + } else { + $error++; + $this->error = $langs->trans('NotAuthorized'); + $this->errors[] = $langs->trans('NotAuthorized'); + dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING); + } - return ($error ? -1 : 1); - } + return ($error ? -1 : 1); + } - /** - * Create order with draft status - * - * @param User $user User making creation - * @param int $notrigger Disable all triggers - * @return int <0 if KO, Id of supplier order if OK - */ - public function create($user, $notrigger = 0) - { - global $langs, $conf, $hookmanager; + /** + * Create order with draft status + * + * @param User $user User making creation + * @param int $notrigger Disable all triggers + * @return int <0 if KO, Id of supplier order if OK + */ + public function create($user, $notrigger = 0) + { + global $langs, $conf, $hookmanager; - $this->db->begin(); + $this->db->begin(); $error = 0; - $now = dol_now(); + $now = dol_now(); // $date_commande is deprecated $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set if (empty($date)) $date = $now; - // Clean parameters - if (empty($this->source)) $this->source = 0; + // Clean parameters + 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); @@ -1263,104 +1259,104 @@ class CommandeFournisseur extends CommonOrder $this->multicurrency_tx = 1; } - // We set order into draft status - $this->brouillon = 1; + // We set order into draft status + $this->brouillon = 1; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur ("; - $sql .= "ref"; - $sql .= ", ref_supplier"; - $sql .= ", note_private"; - $sql .= ", note_public"; - $sql .= ", entity"; - $sql .= ", fk_soc"; - $sql .= ", fk_projet"; - $sql .= ", date_creation"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur ("; + $sql .= "ref"; + $sql .= ", ref_supplier"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", entity"; + $sql .= ", fk_soc"; + $sql .= ", fk_projet"; + $sql .= ", date_creation"; $sql .= ", date_livraison"; - $sql .= ", fk_user_author"; - $sql .= ", fk_statut"; - $sql .= ", source"; - $sql .= ", model_pdf"; - $sql .= ", fk_mode_reglement"; + $sql .= ", fk_user_author"; + $sql .= ", fk_statut"; + $sql .= ", source"; + $sql .= ", model_pdf"; + $sql .= ", fk_mode_reglement"; $sql .= ", fk_cond_reglement"; - $sql .= ", fk_account"; + $sql .= ", fk_account"; $sql .= ", fk_incoterms, location_incoterms"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ") "; - $sql .= " VALUES ("; - $sql .= "''"; - $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; - $sql .= ", '".$this->db->escape($this->note_private)."'"; - $sql .= ", '".$this->db->escape($this->note_public)."'"; - $sql .= ", ".$conf->entity; - $sql .= ", ".$this->socid; - $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); - $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= "''"; + $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", ".$this->socid; + $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); + $sql .= ", '".$this->db->idate($now)."'"; $sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null"); - $sql .= ", ".$user->id; - $sql .= ", ".self::STATUS_DRAFT; - $sql .= ", ".$this->db->escape($this->source); - $sql .= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'"; - $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); - $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null'); - $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); - $sql .= ", ".(int) $this->fk_incoterms; - $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", ".$user->id; + $sql .= ", ".self::STATUS_DRAFT; + $sql .= ", ".$this->db->escape($this->source); + $sql .= ", '".$this->db->escape($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)."'"; + $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); + $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null'); + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", ".(int) $this->fk_incoterms; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql .= ", ".(double) $this->multicurrency_tx; - $sql .= ")"; + $sql .= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + 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++) - { - $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline() + // insert products details into database + 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 - $result = $this->addline( - $this->lines[$i]->desc, - $this->lines[$i]->subprice, - $this->lines[$i]->qty, - $this->lines[$i]->tva_tx, - $this->lines[$i]->localtax1_tx, - $this->lines[$i]->localtax2_tx, - $this->lines[$i]->fk_product, - 0, - $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product - $this->lines[$i]->remise_percent, - 'HT', - 0, - $this->lines[$i]->product_type, - $this->lines[$i]->info_bits, - false, - $this->lines[$i]->date_start, - $this->lines[$i]->date_end, - $this->lines[$i]->array_options, - $this->lines[$i]->fk_unit - ); - 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; - } - } + // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set + $result = $this->addline( + $this->lines[$i]->desc, + $this->lines[$i]->subprice, + $this->lines[$i]->qty, + $this->lines[$i]->tva_tx, + $this->lines[$i]->localtax1_tx, + $this->lines[$i]->localtax2_tx, + $this->lines[$i]->fk_product, + 0, + $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product + $this->lines[$i]->remise_percent, + 'HT', + 0, + $this->lines[$i]->product_type, + $this->lines[$i]->info_bits, + false, + $this->lines[$i]->date_start, + $this->lines[$i]->date_end, + $this->lines[$i]->array_options, + $this->lines[$i]->fk_unit + ); + 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; + } + } - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql .= " SET ref='(PROV".$this->id.")'"; - $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; + $sql .= " SET ref='(PROV".$this->id.")'"; + $sql .= " WHERE rowid=".$this->id; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + if ($this->db->query($sql)) + { // Add link with price request and supplier order if ($this->id) { @@ -1376,82 +1372,82 @@ class CommandeFournisseur extends CommonOrder { 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) - { - dol_print_error($this->db); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $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) + { + dol_print_error($this->db); + $error++; + } + } + } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); if (!$ret) { dol_print_error($this->db); $error++; } - } + } } } } - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) $error++; + } if (!$error && !$notrigger) - { + { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user); if ($result < 0) - { - $this->db->rollback(); - return -1; - } + { + $this->db->rollback(); + return -1; + } // End call triggers - } + } - $this->db->commit(); - return $this->id; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return $this->id; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Load an object from its id and create a new one in database - * + /** + * Load an object from its id and create a new one in database + * * @param User $user User making the clone * @param int $socid Id of thirdparty - * @return int New id of clone - */ - public function createFromClone(User $user, $socid = 0) - { - global $conf, $user, $hookmanager; + * @return int New id of clone + */ + public function createFromClone(User $user, $socid = 0) + { + global $conf, $user, $hookmanager; - $error = 0; + $error = 0; $this->db->begin(); - // get extrafields so they will be clone - foreach ($this->lines as $line) - $line->fetch_optionals(); + // get extrafields so they will be clone + foreach ($this->lines as $line) + $line->fetch_optionals(); // Load source object $objFrom = clone $this; @@ -1473,92 +1469,92 @@ class CommandeFournisseur extends CommonOrder // TODO Change product price if multi-prices } - $this->id = 0; - $this->statut = self::STATUS_DRAFT; + $this->id = 0; + $this->statut = self::STATUS_DRAFT; - // Clear fields - $this->user_author_id = $user->id; - $this->user_valid = ''; - $this->date_creation = ''; - $this->date_validation = ''; - $this->ref_supplier = ''; - $this->user_approve_id = ''; - $this->user_approve_id2 = ''; - $this->date_approve = ''; - $this->date_approve2 = ''; + // Clear fields + $this->user_author_id = $user->id; + $this->user_valid = ''; + $this->date_creation = ''; + $this->date_validation = ''; + $this->ref_supplier = ''; + $this->user_approve_id = ''; + $this->user_approve_id2 = ''; + $this->date_approve = ''; + $this->date_approve2 = ''; - // Create clone - $this->context['createfromclone'] = 'createfromclone'; - $result = $this->create($user); - if ($result < 0) $error++; + // Create clone + $this->context['createfromclone'] = 'createfromclone'; + $result = $this->create($user); + if ($result < 0) $error++; - if (!$error) - { - // Hook of thirdparty module - 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 (!$error) + { + // Hook of thirdparty module + 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++; + } + } unset($this->context['createfromclone']); // End - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -1; + } + } - /** - * Add order line - * - * @param string $desc Description - * @param float $pu_ht Unit price - * @param float $qty Quantity - * @param float $txtva Taux tva - * @param float $txlocaltax1 Localtax1 tax - * @param float $txlocaltax2 Localtax2 tax - * @param int $fk_product Id product - * @param int $fk_prod_fourn_price Id supplier price - * @param string $ref_supplier Supplier reference price - * @param float $remise_percent Remise - * @param string $price_base_type HT or TTC - * @param float $pu_ttc Unit price TTC - * @param int $type Type of line (0=product, 1=service) - * @param int $info_bits More information - * @param bool $notrigger Disable triggers - * @param int $date_start Date start of service - * @param int $date_end Date end of service + /** + * Add order line + * + * @param string $desc Description + * @param float $pu_ht Unit price + * @param float $qty Quantity + * @param float $txtva Taux tva + * @param float $txlocaltax1 Localtax1 tax + * @param float $txlocaltax2 Localtax2 tax + * @param int $fk_product Id product + * @param int $fk_prod_fourn_price Id supplier price + * @param string $ref_supplier Supplier reference price + * @param float $remise_percent Remise + * @param string $price_base_type HT or TTC + * @param float $pu_ttc Unit price TTC + * @param int $type Type of line (0=product, 1=service) + * @param int $info_bits More information + * @param bool $notrigger Disable triggers + * @param int $date_start Date start of service + * @param int $date_end Date end of service * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $fk_unit Code of the unit to use. Null to use the default one * @param string $pu_ht_devise Amount in currency * @param string $origin 'order', ... * @param int $origin_id Id of origin object - * @return int <=0 if KO, >0 if OK - */ + * @return int <=0 if KO, >0 if OK + */ public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $fk_prod_fourn_price = 0, $ref_supplier = '', $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $type = 0, $info_bits = 0, $notrigger = false, $date_start = null, $date_end = null, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $origin = '', $origin_id = 0) - { - global $langs, $mysoc, $conf; + { + global $langs, $mysoc, $conf; - $error = 0; + $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'; + 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) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (!$qty) $qty = 1; + if (empty($qty)) $qty = 0; if (!$info_bits) $info_bits = 0; if (empty($txtva)) $txtva = 0; if (empty($txlocaltax1)) $txlocaltax1 = 0; @@ -1597,63 +1593,63 @@ class CommandeFournisseur extends CommonOrder } - $this->db->begin(); + $this->db->begin(); - if ($fk_product > 0) - { - if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) - { - // Check quantity is enough - dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." ref_supplier=".$ref_supplier); - $prod = new Product($this->db); - if ($prod->fetch($fk_product) > 0) - { - $product_type = $prod->type; - $label = $prod->label; + if ($fk_product > 0) + { + if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) + { + // Check quantity is enough + dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_prod_fourn_price=".$fk_prod_fourn_price." qty=".$qty." ref_supplier=".$ref_supplier); + $prod = new Product($this->db); + if ($prod->fetch($fk_product) > 0) + { + $product_type = $prod->type; + $label = $prod->label; - // 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 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 === '')) - { - $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 ($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(); - dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); - //$pu = $prod->fourn_pu; // We do not overwrite unit price - //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price - return -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) - { - $this->error = $prod->error; - $this->db->rollback(); - dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); - return -1; - } - } else { - $this->error = $prod->error; - $this->db->rollback(); - return -1; - } - } + // 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 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 === '')) + { + $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 ($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(); + dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); + //$pu = $prod->fourn_pu; // We do not overwrite unit price + //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price + return -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) + { + $this->error = $prod->error; + $this->db->rollback(); + dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); + return -1; + } + } else { + $this->error = $prod->error; + $this->db->rollback(); + return -1; + } + } // redefine quantity according to packaging if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) @@ -1672,385 +1668,388 @@ class CommandeFournisseur extends CommonOrder } } } - } else { - $product_type = $type; - } + } else { + $product_type = $type; + } - if ($conf->multicurrency->enabled && $pu_ht_devise > 0) { - $pu = 0; - } + if ($conf->multicurrency->enabled && $pu_ht_devise > 0) { + $pu = 0; + } - $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; - $pu = $pu_ht = $tabprice[3]; + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; + $pu = $pu_ht = $tabprice[3]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - $localtax1_type = $localtaxes_type[0]; + $localtax1_type = $localtaxes_type[0]; $localtax2_type = $localtaxes_type[2]; - $subprice = price2num($pu, 'MU'); + $subprice = price2num($pu, 'MU'); - $rangmax = $this->line_max(); - $rang = $rangmax + 1; + $rangmax = $this->line_max(); + $rang = $rangmax + 1; - // Insert line - $this->line = new CommandeFournisseurLigne($this->db); + // Insert line + $this->line = new CommandeFournisseurLigne($this->db); - $this->line->context = $this->context; + $this->line->context = $this->context; - $this->line->fk_commande = $this->id; - $this->line->label = $label; - $this->line->ref_fourn = $ref_supplier; - $this->line->ref_supplier = $ref_supplier; - $this->line->desc = $desc; - $this->line->qty = $qty; - $this->line->tva_tx = $txtva; - $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); - $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_product = $fk_product; - $this->line->product_type = $product_type; - $this->line->remise_percent = $remise_percent; - $this->line->subprice = $pu_ht; - $this->line->rang = $rang; - $this->line->info_bits = $info_bits; + $this->line->fk_commande = $this->id; + $this->line->label = $label; + $this->line->ref_fourn = $ref_supplier; + $this->line->ref_supplier = $ref_supplier; + $this->line->desc = $desc; + $this->line->qty = $qty; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0); + $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0); + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->fk_product = $fk_product; + $this->line->product_type = $product_type; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->rang = $rang; + $this->line->info_bits = $info_bits; - $this->line->vat_src_code = $vat_src_code; - $this->line->total_ht = $total_ht; - $this->line->total_tva = $total_tva; - $this->line->total_localtax1 = $total_localtax1; - $this->line->total_localtax2 = $total_localtax2; - $this->line->total_ttc = $total_ttc; - $this->line->product_type = $type; - $this->line->special_code = $this->special_code; - $this->line->origin = $origin; - $this->line->origin_id = $origin_id; - $this->line->fk_unit = $fk_unit; + $this->line->vat_src_code = $vat_src_code; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->product_type = $type; + $this->line->special_code = $this->special_code; + $this->line->origin = $origin; + $this->line->origin_id = $origin_id; + $this->line->fk_unit = $fk_unit; - $this->line->date_start = $date_start; - $this->line->date_end = $date_end; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; - // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; - $this->line->multicurrency_subprice = $pu_ht_devise; - $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + // Multicurrency + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->multicurrency_subprice = $pu_ht_devise; + $this->line->multicurrency_total_ht = $multicurrency_total_ht; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $this->line->subprice = $pu_ht; - $this->line->price = $this->line->subprice; + $this->line->subprice = $pu_ht; + $this->line->price = $this->line->subprice; - $this->line->remise_percent = $remise_percent; + $this->line->remise_percent = $remise_percent; - if (is_array($array_options) && count($array_options) > 0) { - $this->line->array_options = $array_options; - } + if (is_array($array_options) && count($array_options) > 0) { + $this->line->array_options = $array_options; + } - $result = $this->line->insert($notrigger); - if ($result > 0) - { - // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + $result = $this->line->insert($notrigger); + if ($result > 0) + { + // Reorder if child line + 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) - { - $this->db->commit(); - return $this->line->id; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->line->error; - $this->errors = $this->line->errors; - dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } - } - } + // 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) + { + $this->db->commit(); + return $this->line->id; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + } + } - /** - * Save a receiving into the tracking table of receiving (commande_fournisseur_dispatch) and add product into stock warehouse. - * - * @param User $user User object making change - * @param int $product Id of product to dispatch - * @param double $qty Qty to dispatch - * @param int $entrepot Id of warehouse to add product - * @param double $price Unit Price for PMP value calculation (Unit price without Tax and taking into account discount) - * @param string $comment Comment for stock movement + /** + * Save a receiving into the tracking table of receiving (commande_fournisseur_dispatch) and add product into stock warehouse. + * + * @param User $user User object making change + * @param int $product Id of product to dispatch + * @param double $qty Qty to dispatch + * @param int $entrepot Id of warehouse to add product + * @param double $price Unit Price for PMP value calculation (Unit price without Tax and taking into account discount) + * @param string $comment Comment for stock movement * @param integer $eatby eat-by date * @param integer $sellby sell-by date * @param string $batch Lot number * @param int $fk_commandefourndet Id of supplier order line - * @param int $notrigger 1 = notrigger - * @return int <0 if KO, >0 if OK - */ - public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0) - { - global $conf, $langs; + * @param int $notrigger 1 = notrigger + * @return int <0 if KO, >0 if OK + */ + public function dispatchProduct($user, $product, $qty, $entrepot, $price = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $fk_commandefourndet = 0, $notrigger = 0) + { + global $conf, $langs; - $error = 0; - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; + $error = 0; + 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) - { - $this->error = 'ErrorBadValueForParameterWarehouse'; - return -1; - } - if ($qty == 0) - { - $this->error = 'ErrorBadValueForParameterQty'; - return -1; - } + // Check parameters (if test are wrong here, there is bug into caller) + if ($entrepot <= 0) + { + $this->error = 'ErrorBadValueForParameterWarehouse'; + return -1; + } + 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 + $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 - $now = dol_now(); + $now = dol_now(); - if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) - { - $this->db->begin(); + 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"; - $sql .= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES"; - $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', "; - $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$batch."'" : "null"); - $sql .= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch"; + $sql .= " (fk_commande, fk_product, qty, fk_entrepot, fk_user, datec, fk_commandefourndet, status, comment, eatby, sellby, batch) VALUES"; + $sql .= " ('".$this->id."','".$product."','".$qty."',".($entrepot > 0 ? "'".$entrepot."'" : "null").",'".$user->id."','".$this->db->idate($now)."','".$fk_commandefourndet."', ".$dispatchstatus.", '".$this->db->escape($comment)."', "; + $sql .= ($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ".($batch ? "'".$this->db->escape($batch)."'" : "null"); + $sql .= ")"; - dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { - global $conf, $langs, $user; + dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$notrigger) + { + global $conf, $langs, $user; // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user); if ($result < 0) - { - $error++; - } + { + $error++; + } // End call triggers - } - } else { - $this->error = $this->db->lasterror(); - $error++; - } + } + } else { + $this->error = $this->db->lasterror(); + $error++; + } - // 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)) - { - $mouv = new MouvementStock($this->db); - if ($product > 0) - { - // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on) - $mouv->origin = &$this; + // 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)) + { + $mouv = new MouvementStock($this->db); + 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) - { - $this->error = $mouv->error; - $this->errors = $mouv->errors; - dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR); - $error++; - } - } - } + if ($result < 0) + { + $this->error = $mouv->error; + $this->errors = $mouv->errors; + dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR); + $error++; + } + } + } - if ($error == 0) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = 'BadStatusForObject'; - return -2; - } - } + if ($error == 0) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = 'BadStatusForObject'; + return -2; + } + } - /** - * Delete line - * - * @param int $idline Id of line to delete - * @param int $notrigger 1=Disable call to triggers - * @return int <0 if KO, >0 if OK - */ - public function deleteline($idline, $notrigger = 0) - { - if ($this->statut == 0) - { - $line = new CommandeFournisseurLigne($this->db); + /** + * Delete line + * + * @param int $idline Id of line to delete + * @param int $notrigger 1=Disable call to triggers + * @return int <0 if KO, >0 if OK + */ + public function deleteline($idline, $notrigger = 0) + { + if ($this->statut == 0) + { + $line = new CommandeFournisseurLigne($this->db); - if ($line->fetch($idline) <= 0) - { - return 0; - } + if ($line->fetch($idline) <= 0) + { + return 0; + } - if ($line->delete($notrigger) > 0) - { - $this->update_price(); - return 1; - } else { - $this->error = $line->error; - $this->errors = $line->errors; - return -1; - } - } else { - return -2; - } - } + if ($line->delete($notrigger) > 0) + { + $this->update_price(); + return 1; + } else { + $this->error = $line->error; + $this->errors = $line->errors; + return -1; + } + } else { + return -2; + } + } - /** - * Delete an order - * - * @param User $user Object user - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = 0) - { - global $langs, $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Delete an order + * + * @param User $user Object user + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0) + { + global $langs, $conf; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error = 0; + $error = 0; - $this->db->begin(); + $this->db->begin(); - if (empty($notrigger)) - { - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user); - if ($result < 0) - { - $this->errors[] = 'ErrorWhenRunningTrigger'; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (empty($notrigger)) + { + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user); + if ($result < 0) + { + $this->errors[] = 'ErrorWhenRunningTrigger'; + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + // End call triggers + } - $main = MAIN_DB_PREFIX.'commande_fournisseurdet'; - $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)) - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } + $main = MAIN_DB_PREFIX.'commande_fournisseurdet'; + $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)) + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } - $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)) - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } + $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)) + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } - $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) - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } - } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->db->lasterror(); - $error++; - } + $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) + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); + $error++; + } - // Remove extrafields - if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $this->error = 'FailToDeleteExtraFields'; - $this->errors[] = 'FailToDeleteExtraFields'; - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + // Remove extrafields + if (!$error) + { + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $this->error = 'FailToDeleteExtraFields'; + $this->errors[] = 'FailToDeleteExtraFields'; + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) { - $this->error = 'FailToDeleteObjectLinked'; - $this->errors[] = 'FailToDeleteObjectLinked'; - $error++; - } + $res = $this->deleteObjectLinked(); + if ($res < 0) { + $this->error = 'FailToDeleteObjectLinked'; + $this->errors[] = 'FailToDeleteObjectLinked'; + $error++; + } - if (!$error) - { - // We remove directory - $ref = dol_sanitizeFileName($this->ref); - 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 - { - $this->error = 'ErrorFailToDeleteFile'; - $this->errors[] = 'ErrorFailToDeleteFile'; - $error++; - } - } - if (file_exists($dir)) - { - $res = @dol_delete_dir_recursive($dir); - if (!$res) - { - $this->error = 'ErrorFailToDeleteDir'; - $this->errors[] = 'ErrorFailToDeleteDir'; - $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) + { + $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 + { + $this->error = 'ErrorFailToDeleteFile'; + $this->errors[] = 'ErrorFailToDeleteFile'; + $error++; + } + } + if (file_exists($dir)) + { + $res = @dol_delete_dir_recursive($dir); + if (!$res) + { + $this->error = 'ErrorFailToDeleteDir'; + $this->errors[] = 'ErrorFailToDeleteDir'; + $error++; + } + } + } + } if (!$error) { @@ -2062,54 +2061,54 @@ class CommandeFournisseur extends CommonOrder $this->db->rollback(); return -$error; } - } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Get list of order methods - * - * @return int 0 if OK, <0 if KO - */ - public function get_methodes_commande() - { - // phpcs:enable - $sql = "SELECT rowid, libelle"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method"; - $sql .= " WHERE active = 1"; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Get list of order methods + * + * @return int 0 if OK, <0 if KO + */ + public function get_methodes_commande() + { + // phpcs:enable + $sql = "SELECT rowid, libelle"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method"; + $sql .= " WHERE active = 1"; - $resql = $this->db->query($sql); - if ($resql) - { - $i = 0; - $num = $this->db->num_rows($resql); - $this->methodes_commande = array(); - while ($i < $num) - { - $row = $this->db->fetch_row($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $i = 0; + $num = $this->db->num_rows($resql); + $this->methodes_commande = array(); + while ($i < $num) + { + $row = $this->db->fetch_row($resql); - $this->methodes_commande[$row[0]] = $row[1]; + $this->methodes_commande[$row[0]] = $row[1]; - $i++; - } - return 0; - } else { - return -1; - } - } + $i++; + } + return 0; + } else { + return -1; + } + } - /** + /** * Return array of dispatched lines waiting to be approved for this order - * - * @since 8.0 Return dispatched quantity (qty). + * + * @since 8.0 Return dispatched quantity (qty). * * @param int $status Filter on stats (-1 = no filter, 0 = lines draft to be approved, 1 = approved lines) * @return array Array of lines - */ - public function getDispachedLines($status = -1) - { - $ret = array(); + */ + public function getDispachedLines($status = -1) + { + $ret = array(); - // List of already dispatched lines + // List of already dispatched lines $sql = "SELECT p.ref, p.label,"; $sql .= " e.rowid as warehouse_id, e.ref as entrepot,"; $sql .= " cfd.rowid as dispatchedlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status"; @@ -2145,454 +2144,453 @@ class CommandeFournisseur extends CommonOrder } else dol_print_error($this->db, 'Failed to execute request to get dispatched lines'); return $ret; - } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set a delivery in database for this supplier order - * - * @param User $user User that input data - * @param integer $date Date of reception - * @param string $type Type of receipt ('tot' = total/done, 'par' = partial, 'nev' = never, 'can' = cancel) - * @param string $comment Comment - * @return int <0 if KO, >0 if OK - */ - public function Livraison($user, $date, $type, $comment) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set a delivery in database for this supplier order + * + * @param User $user User that input data + * @param integer $date Date of reception + * @param string $type Type of receipt ('tot' = total/done, 'par' = partial, 'nev' = never, 'can' = cancel) + * @param string $comment Comment + * @return int <0 if KO, >0 if OK + */ + public function Livraison($user, $date, $type, $comment) + { + // phpcs:enable + global $conf, $langs; - $result = 0; + $result = 0; $error = 0; - dol_syslog(get_class($this)."::Livraison"); + dol_syslog(get_class($this)."::Livraison"); - 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; + 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 { - $error++; - dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR); - return -2; + $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)) - { + // Some checks to accept the record + 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')) - { - $dispatchedlinearray = $this->getDispachedLines(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) - { - $dispatcheddenied = $this->getDispachedLines(2); - if (count($dispatchedlinearray) > 0) - { - $result = -1; - $error++; - $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; - dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG); - } - } - } + if (!$error && ($type == 'tot')) + { + $dispatchedlinearray = $this->getDispachedLines(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) + { + $dispatcheddenied = $this->getDispachedLines(2); + if (count($dispatchedlinearray) > 0) + { + $result = -1; + $error++; + $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; + dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionDenied', LOG_DEBUG); + } + } + } - // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). + // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). - if (!$error) - { - $this->db->begin(); + if (!$error) + { + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql .= " SET fk_statut = ".$statut; - $sql .= " WHERE rowid = ".$this->id; - $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; + $sql .= " SET fk_statut = ".$statut; + $sql .= " WHERE rowid = ".$this->id; + $sql .= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received - dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $result = 0; - $old_statut = $this->statut; - $this->statut = $statut; + dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $result = 0; + $old_statut = $this->statut; + $this->statut = $statut; $this->actionmsg2 = $comment; - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); + if ($result < 0) $error++; + // End call triggers - if (!$error) - { - $this->db->commit(); - } else { - $this->statut = $old_statut; - $this->db->rollback(); - $this->error = $this->db->lasterror(); - $result = -1; - } - } else { - $this->db->rollback(); - $this->error = $this->db->lasterror(); - $result = -1; - } - } - } else { - $this->error = $langs->trans('NotAuthorized'); - $this->errors[] = $langs->trans('NotAuthorized'); - dol_syslog(get_class($this)."::Livraison Not Authorized"); - $result = -3; - } - return $result; - } + if (!$error) + { + $this->db->commit(); + } else { + $this->statut = $old_statut; + $this->db->rollback(); + $this->error = $this->db->lasterror(); + $result = -1; + } + } else { + $this->db->rollback(); + $this->error = $this->db->lasterror(); + $result = -1; + } + } + } else { + $this->error = $langs->trans('NotAuthorized'); + $this->errors[] = $langs->trans('NotAuthorized'); + dol_syslog(get_class($this)."::Livraison Not Authorized"); + $result = -3; + } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set the planned delivery date - * - * @param User $user Objet user making change - * @param integer $date_livraison Planned delivery date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function set_date_livraison($user, $date_livraison, $notrigger = 0) - { - // phpcs:enable - if ($user->rights->fournisseur->commande->creer) - { - $error = 0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); - $sql .= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->errors[] = $this->db->error(); - $error++; - } - - if (!$error) - { - $this->oldcopy = clone $this; - $this->date_livraison = $date_livraison; - } - - if (!$notrigger && empty($error)) - { - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } - - if (!$error) - { - $this->db->commit(); - return 1; - } else { - foreach ($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } - } else { - return -2; - } - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Set the id projet - * - * @param User $user Objet utilisateur qui modifie - * @param int $id_projet Date de livraison - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 si ko, >0 si ok - */ - public function set_id_projet($user, $id_projet, $notrigger = 0) - { - // phpcs:enable - if ($user->rights->fournisseur->commande->creer) - { - $error = 0; + * Set the planned delivery date + * + * @param User $user Objet user making change + * @param integer $date_livraison Planned delivery date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function set_date_livraison($user, $date_livraison, $notrigger = 0) + { + // phpcs:enable + if ($user->rights->fournisseur->commande->creer) + { + $error = 0; - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; - $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null'); - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; + $sql .= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->errors[] = $this->db->error(); - $error++; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->error(); + $error++; + } - if (!$error) - { - $this->oldcopy = clone $this; - $this->fk_projet = $id_projet; - $this->fk_project = $id_projet; - } + if (!$error) + { + $this->oldcopy = clone $this; + $this->date_livraison = $date_livraison; + } - if (!$notrigger && empty($error)) - { - // Call trigger - $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$notrigger && empty($error)) + { + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - foreach ($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } - } else { - return -2; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + foreach ($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } + } else { + return -2; + } + } - /** - * Update a supplier order from a customer order - * - * @param User $user User that create - * @param int $idc Id of supplier order to update - * @param int $comclientid Id of customer order to use as template - * @return int <0 if KO, >0 if OK - */ - public function updateFromCommandeClient($user, $idc, $comclientid) - { - $comclient = new Commande($this->db); - $comclient->fetch($comclientid); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Set the id projet + * + * @param User $user Objet utilisateur qui modifie + * @param int $id_projet Date de livraison + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 si ko, >0 si ok + */ + public function set_id_projet($user, $id_projet, $notrigger = 0) + { + // phpcs:enable + if ($user->rights->fournisseur->commande->creer) + { + $error = 0; - $this->id = $idc; + $this->db->begin(); - $this->lines = array(); + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; + $sql .= " SET fk_projet = ".($id_projet > 0 ? (int) $id_projet : 'null'); + $sql .= " WHERE rowid = ".$this->id; - $num = count($comclient->lines); - for ($i = 0; $i < $num; $i++) - { - $prod = new Product($this->db); - $label = ''; - $ref = ''; - if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) - { - $label = $prod->label; - $ref = $prod->ref; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $this->errors[] = $this->db->error(); + $error++; + } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet"; - $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)"; - $sql .= " VALUES (".$idc.", '".$this->db->escape($label)."','".$this->db->escape($comclient->lines[$i]->desc)."'"; - $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','".$ref."');"; - if ($this->db->query($sql)) - { - $this->update_price(); - } - } + if (!$error) + { + $this->oldcopy = clone $this; + $this->fk_projet = $id_projet; + $this->fk_project = $id_projet; + } - return 1; - } + if (!$notrigger && empty($error)) + { + // Call trigger + $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } - /** - * Tag order with a particular status - * - * @param User $user Object user that change status - * @param int $status New status - * @return int <0 if KO, >0 if OK - */ - public function setStatus($user, $status) - { - global $conf, $langs; - $error = 0; + if (!$error) + { + $this->db->commit(); + return 1; + } else { + foreach ($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } + } else { + return -2; + } + } - $this->db->begin(); + /** + * Update a supplier order from a customer order + * + * @param User $user User that create + * @param int $idc Id of supplier order to update + * @param int $comclientid Id of customer order to use as template + * @return int <0 if KO, >0 if OK + */ + public function updateFromCommandeClient($user, $idc, $comclientid) + { + $comclient = new Commande($this->db); + $comclient->fetch($comclientid); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql .= ' SET fk_statut='.$status; - $sql .= ' WHERE rowid = '.$this->id; + $this->id = $idc; - dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - // Trigger names for each status - $triggerName = array(); - $triggerName[0] = 'DRAFT'; - $triggerName[1] = 'VALIDATED'; - $triggerName[2] = 'APPROVED'; - $triggerName[3] = 'ORDERED'; // Ordered - $triggerName[4] = 'RECEIVED_PARTIALLY'; - $triggerName[5] = 'RECEIVED_COMPLETELY'; - $triggerName[6] = 'CANCELED'; - $triggerName[7] = 'CANCELED'; - $triggerName[9] = 'REFUSED'; + $this->lines = array(); - // Call trigger - $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user); - if ($result < 0) { $error++; } - // End call triggers - } else { - $error++; - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this)."::setStatus ".$this->error); - } + $num = count($comclient->lines); + for ($i = 0; $i < $num; $i++) + { + $prod = new Product($this->db); + $label = ''; + $ref = ''; + if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) + { + $label = $prod->label; + $ref = $prod->ref; + } - if (!$error) - { - $this->statut = $status; - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } + $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet"; + $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)"; + $sql .= " VALUES (".$idc.", '".$this->db->escape($label)."', ".$this->db->escape($comclient->lines[$i]->desc); + $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)) + { + $this->update_price(); + } + } - /** - * Update line - * - * @param int $rowid Id de la ligne de facture - * @param string $desc Description de la ligne - * @param double $pu Prix unitaire - * @param double $qty Quantity - * @param double $remise_percent Percent discount on line - * @param double $txtva VAT rate - * @param double $txlocaltax1 Localtax1 tax - * @param double $txlocaltax2 Localtax2 tax - * @param double $price_base_type Type of price base - * @param int $info_bits Miscellaneous informations - * @param int $type Type of line (0=product, 1=service) - * @param int $notrigger Disable triggers - * @param integer $date_start Date start of service - * @param integer $date_end Date end of service + return 1; + } + + /** + * Tag order with a particular status + * + * @param User $user Object user that change status + * @param int $status New status + * @return int <0 if KO, >0 if OK + */ + public function setStatus($user, $status) + { + global $conf, $langs; + $error = 0; + + $this->db->begin(); + + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql .= ' SET fk_statut='.$status; + $sql .= ' WHERE rowid = '.$this->id; + + dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + // Trigger names for each status + $triggerName = array(); + $triggerName[0] = 'DRAFT'; + $triggerName[1] = 'VALIDATED'; + $triggerName[2] = 'APPROVED'; + $triggerName[3] = 'ORDERED'; // Ordered + $triggerName[4] = 'RECEIVED_PARTIALLY'; + $triggerName[5] = 'RECEIVED_COMPLETELY'; + $triggerName[6] = 'CANCELED'; + $triggerName[7] = 'CANCELED'; + $triggerName[9] = 'REFUSED'; + + // Call trigger + $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user); + if ($result < 0) { $error++; } + // End call triggers + } else { + $error++; + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this)."::setStatus ".$this->error); + } + + if (!$error) + { + $this->statut = $status; + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Update line + * + * @param int $rowid Id de la ligne de facture + * @param string $desc Description de la ligne + * @param double $pu Prix unitaire + * @param double $qty Quantity + * @param double $remise_percent Percent discount on line + * @param double $txtva VAT rate + * @param double $txlocaltax1 Localtax1 tax + * @param double $txlocaltax2 Localtax2 tax + * @param double $price_base_type Type of price base + * @param int $info_bits Miscellaneous informations + * @param int $type Type of line (0=product, 1=service) + * @param int $notrigger Disable triggers + * @param integer $date_start Date start of service + * @param integer $date_end Date end of service * @param array $array_options Extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency * @param string $ref_supplier Supplier ref - * @return int < 0 if error, > 0 if ok - */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $notrigger = 0, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $ref_supplier = '') - { - global $mysoc, $conf, $langs; - dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + * @return int < 0 if error, > 0 if ok + */ + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $notrigger = 0, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $ref_supplier = '') + { + global $mysoc, $conf, $langs; + dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type, $fk_unit"); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - $error = 0; + $error = 0; - 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 ($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; - $remise_percent = price2num($remise_percent); - $qty = price2num($qty); - if (!$qty) $qty = 1; - $pu = price2num($pu); - $pu_ht_devise = price2num($pu_ht_devise); - $txtva = price2num($txtva); - $txlocaltax1 = price2num($txlocaltax1); - $txlocaltax2 = price2num($txlocaltax2); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu = price2num($pu); + $pu_ht_devise = price2num($pu_ht_devise); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); - // Check parameters - if ($type < 0) return -1; - if ($date_start && $date_end && $date_start > $date_end) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStartDateGreaterEnd'); - return -1; - } + // Check parameters + if ($type < 0) return -1; + if ($date_start && $date_end && $date_start > $date_end) { + $langs->load("errors"); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); + return -1; + } - $this->db->begin(); + $this->db->begin(); - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; $pu_tva = $tabprice[4]; $pu_ttc = $tabprice[5]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - $localtax1_type = $localtaxes_type[0]; + $localtax1_type = $localtaxes_type[0]; $localtax2_type = $localtaxes_type[2]; - $subprice = price2num($pu_ht, 'MU'); + $subprice = price2num($pu_ht, 'MU'); - //Fetch current line from the database and then clone the object and set it in $oldline property - $this->line = new CommandeFournisseurLigne($this->db); - $this->line->fetch($rowid); - $this->line->fetch_optionals(); + //Fetch current line from the database and then clone the object and set it in $oldline property + $this->line = new CommandeFournisseurLigne($this->db); + $this->line->fetch($rowid); + $this->line->fetch_optionals(); - $oldline = clone $this->line; - $this->line->oldline = $oldline; + $oldline = clone $this->line; + $this->line->oldline = $oldline; - $this->line->context = $this->context; + $this->line->context = $this->context; - $this->line->fk_commande = $this->id; - //$this->line->label=$label; - $this->line->desc = $desc; + $this->line->fk_commande = $this->id; + //$this->line->label=$label; + $this->line->desc = $desc; // redefine quantity according to packaging if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) @@ -2610,345 +2608,345 @@ class CommandeFournisseur extends CommonOrder } } - $this->line->qty = $qty; + $this->line->qty = $qty; $this->line->ref_supplier = $ref_supplier; - $this->line->vat_src_code = $vat_src_code; - $this->line->tva_tx = $txtva; - $this->line->localtax1_tx = $txlocaltax1; - $this->line->localtax2_tx = $txlocaltax2; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->remise_percent = $remise_percent; - $this->line->subprice = $pu_ht; - $this->line->rang = $this->rang; - $this->line->info_bits = $info_bits; - $this->line->total_ht = $total_ht; - $this->line->total_tva = $total_tva; - $this->line->total_localtax1 = $total_localtax1; - $this->line->total_localtax2 = $total_localtax2; - $this->line->total_ttc = $total_ttc; - $this->line->product_type = $type; - $this->line->special_code = $this->special_code; - $this->line->origin = $this->origin; - $this->line->fk_unit = $fk_unit; + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = $txlocaltax1; + $this->line->localtax2_tx = $txlocaltax2; + $this->line->localtax1_type = $localtaxes_type[0]; + $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->rang = $this->rang; + $this->line->info_bits = $info_bits; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->product_type = $type; + $this->line->special_code = $this->special_code; + $this->line->origin = $this->origin; + $this->line->fk_unit = $fk_unit; - $this->line->date_start = $date_start; - $this->line->date_end = $date_end; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; - // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; - $this->line->multicurrency_subprice = $pu_ht_devise; - $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + // Multicurrency + $this->line->fk_multicurrency = $this->fk_multicurrency; + $this->line->multicurrency_code = $this->multicurrency_code; + $this->line->multicurrency_subprice = $pu_ht_devise; + $this->line->multicurrency_total_ht = $multicurrency_total_ht; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $this->line->subprice = $pu_ht; - $this->line->price = $this->line->subprice; + $this->line->subprice = $pu_ht; + $this->line->price = $this->line->subprice; - $this->line->remise_percent = $remise_percent; + $this->line->remise_percent = $remise_percent; - if (is_array($array_options) && count($array_options) > 0) { - // We replace values in this->line->array_options only for entries defined into $array_options - foreach ($array_options as $key => $value) { - $this->line->array_options[$key] = $array_options[$key]; - } - } + if (is_array($array_options) && count($array_options) > 0) { + // We replace values in this->line->array_options only for entries defined into $array_options + foreach ($array_options as $key => $value) { + $this->line->array_options[$key] = $array_options[$key]; + } + } - $result = $this->line->update($notrigger); + $result = $this->line->update($notrigger); - // Mise a jour info denormalisees au niveau facture - if ($result >= 0) - { - $this->update_price('', 'auto'); + // Mise a jour info denormalisees au niveau facture + if ($result >= 0) + { + $this->update_price('', 'auto'); $this->db->commit(); return $result; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } else { - $this->error = "Order status makes operation forbidden"; - dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR); - return -2; - } - } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } else { + $this->error = "Order status makes operation forbidden"; + dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR); + return -2; + } + } - /** - * 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() - { - global $user, $langs, $conf; + /** + * 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() + { + global $user, $langs, $conf; - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; - dol_syslog(get_class($this)."::initAsSpecimen"); + dol_syslog(get_class($this)."::initAsSpecimen"); - $now = dol_now(); + $now = dol_now(); - // Find first product - $prodid = 0; - $product = new ProductFournisseur($this->db); - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."product"; - $sql .= " WHERE entity IN (".getEntity('product').")"; - $sql .= $this->db->order("rowid", "ASC"); - $sql .= $this->db->plimit(1); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $prodid = $obj->rowid; - } + // Find first product + $prodid = 0; + $product = new ProductFournisseur($this->db); + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->order("rowid", "ASC"); + $sql .= $this->db->plimit(1); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $prodid = $obj->rowid; + } - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->specimen = 1; - $this->socid = 1; - $this->date = $now; - $this->date_commande = $now; - $this->date_lim_reglement = $this->date + 3600 * 24 * 30; - $this->cond_reglement_code = 'RECEP'; - $this->mode_reglement_code = 'CHQ'; + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->specimen = 1; + $this->socid = 1; + $this->date = $now; + $this->date_commande = $now; + $this->date_lim_reglement = $this->date + 3600 * 24 * 30; + $this->cond_reglement_code = 'RECEP'; + $this->mode_reglement_code = 'CHQ'; - $this->note_public = 'This is a comment (public)'; - $this->note_private = 'This is a comment (private)'; + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; - $this->multicurrency_tx = 1; - $this->multicurrency_code = $conf->currency; + $this->multicurrency_tx = 1; + $this->multicurrency_code = $conf->currency; - $this->statut = 0; + $this->statut = 0; - // Lines - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) - { - $line = new CommandeFournisseurLigne($this->db); - $line->desc = $langs->trans("Description")." ".$xnbp; - $line->qty = 1; - $line->subprice = 100; - $line->price = 100; - $line->tva_tx = 19.6; - $line->localtax1_tx = 0; - $line->localtax2_tx = 0; - if ($xnbp == 2) - { - $line->total_ht = 50; - $line->total_ttc = 59.8; - $line->total_tva = 9.8; - $line->remise_percent = 50; - } else { - $line->total_ht = 100; - $line->total_ttc = 119.6; - $line->total_tva = 19.6; - $line->remise_percent = 00; - } - $line->fk_product = $prodid; + // Lines + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) + { + $line = new CommandeFournisseurLigne($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->price = 100; + $line->tva_tx = 19.6; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; + if ($xnbp == 2) + { + $line->total_ht = 50; + $line->total_ttc = 59.8; + $line->total_tva = 9.8; + $line->remise_percent = 50; + } else { + $line->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 00; + } + $line->fk_product = $prodid; - $this->lines[$xnbp] = $line; + $this->lines[$xnbp] = $line; - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; - $xnbp++; - } - } + $xnbp++; + } + } - /** - * Charge les informations d'ordre info dans l'objet facture - * - * @param int $id Id de la facture a charger - * @return void - */ - public function info($id) - { - $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; + /** + * Charge les informations d'ordre info dans l'objet facture + * + * @param int $id Id de la facture a charger + * @return void + */ + public function info($id) + { + $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; - $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) $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; + $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) $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); - $this->date_approve = $this->db->idate($obj->datea); - $this->date_approve2 = $this->db->idate($obj->datea2); - $this->date_validation = $this->db->idate($obj->date_validation); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $this->date_creation = $this->db->idate($obj->datec); + $this->date_modification = $this->db->idate($obj->datem); + $this->date_approve = $this->db->idate($obj->datea); + $this->date_approve2 = $this->db->idate($obj->datea2); + $this->date_validation = $this->db->idate($obj->date_validation); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Charge indicateurs this->nb de tableau de bord - * - * @return int <0 si ko, >0 si ok - */ - public function load_state_board() - { - // phpcs:enable - global $conf, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 si ko, >0 si ok + */ + public function load_state_board() + { + // phpcs:enable + global $conf, $user; - $this->nb = array(); - $clause = "WHERE"; + $this->nb = array(); + $clause = "WHERE"; - $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) - { - $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"; - } - $sql .= " ".$clause." co.entity = ".$conf->entity; + $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) + { + $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"; + } + $sql .= " ".$clause." co.entity = ".$conf->entity; - $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $this->nb["supplier_orders"] = $obj->nb; - } - $this->db->free($resql); - return 1; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + $this->nb["supplier_orders"] = $obj->nb; + } + $this->db->free($resql); + return 1; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param int $mode "opened", "awaiting" for orders awaiting reception - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - public function load_board($user, $mode = 'opened') - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param int $mode "opened", "awaiting" for orders awaiting reception + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user, $mode = 'opened') + { + // phpcs:enable + global $conf, $langs; - $clause = " WHERE"; + $clause = " WHERE"; - $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) - { - $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"; - } - $sql .= $clause." c.entity = ".$conf->entity; - if ($mode === 'awaiting') { - $sql .= " AND c.fk_statut = ".self::STATUS_ORDERSENT; - } else { - $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; - } - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; + $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) + { + $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"; + } + $sql .= $clause." c.entity = ".$conf->entity; + if ($mode === 'awaiting') { + $sql .= " AND c.fk_statut = ".self::STATUS_ORDERSENT; + } else { + $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; + } + if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; - $resql = $this->db->query($sql); - if ($resql) - { - $commandestatic = new CommandeFournisseur($this->db); + $resql = $this->db->query($sql); + if ($resql) + { + $commandestatic = new CommandeFournisseur($this->db); - $response = new WorkboardResponse(); - $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("SuppliersOrdersToProcess"); - $response->labelShort = $langs->trans("Opened"); - $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2&mainmenu=commercial&leftmenu=orders_suppliers'; - $response->img = img_object('', "order"); + $response = new WorkboardResponse(); + $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("SuppliersOrdersToProcess"); + $response->labelShort = $langs->trans("Opened"); + $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2&mainmenu=commercial&leftmenu=orders_suppliers'; + $response->img = img_object('', "order"); - if ($mode === 'awaiting') { - $response->label = $langs->trans("SuppliersOrdersAwaitingReception"); - $response->labelShort = $langs->trans("AwaitingReception"); - $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=3&mainmenu=commercial&leftmenu=orders_suppliers'; - } + if ($mode === 'awaiting') { + $response->label = $langs->trans("SuppliersOrdersAwaitingReception"); + $response->labelShort = $langs->trans("AwaitingReception"); + $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=3&mainmenu=commercial&leftmenu=orders_suppliers'; + } - while ($obj = $this->db->fetch_object($resql)) - { - $response->nbtodo++; + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; - $commandestatic->date_livraison = $this->db->jdate($obj->delivery_date); - $commandestatic->date_commande = $this->db->jdate($obj->date_commande); - $commandestatic->statut = $obj->fk_statut; + $commandestatic->date_livraison = $this->db->jdate($obj->delivery_date); + $commandestatic->date_commande = $this->db->jdate($obj->date_commande); + $commandestatic->statut = $obj->fk_statut; - if ($commandestatic->hasDelay()) { - $response->nbtodolate++; - } - } + if ($commandestatic->hasDelay()) { + $response->nbtodolate++; + } + } - return $response; - } else { - $this->error = $this->db->error(); - return -1; - } - } + return $response; + } else { + $this->error = $this->db->error(); + return -1; + } + } - /** - * Returns the translated input method of object (defined if $this->methode_commande_id > 0). - * This function make a sql request to get translation. No cache yet, try to not use it inside a loop. - * - * @return string - */ - public function getInputMethod() - { - global $db, $langs; + /** + * Returns the translated input method of object (defined if $this->methode_commande_id > 0). + * This function make a sql request to get translation. No cache yet, try to not use it inside a loop. + * + * @return string + */ + public function getInputMethod() + { + global $db, $langs; - 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 = ".$db->escape($this->methode_commande_id); + 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 = $db->query($sql); - if ($resql) - { - if ($db->num_rows($resql)) - { - $obj = $db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $string = $langs->trans($obj->code); - if ($string == $obj->code) - { - $string = $obj->label != '-' ? $obj->label : ''; - } - return $string; - } - } else dol_print_error($db); - } + $string = $langs->trans($obj->code); + if ($string == $obj->code) + { + $string = $obj->label != '-' ? $obj->label : ''; + } + return $string; + } + } else dol_print_error($this->db); + } - return ''; - } + return ''; + } /** * Create a document onto disk according to template model. @@ -2958,7 +2956,7 @@ class CommandeFournisseur extends CommonOrder * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information + * @param null|array $moreparams Array to provide more information * @return int 0 if KO, 1 if OK */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) @@ -2971,8 +2969,8 @@ class CommandeFournisseur extends CommonOrder if (!dol_strlen($modele)) { $modele = 'muscadet'; - if ($this->modelpdf) { - $modele = $this->modelpdf; + if ($this->model_pdf) { + $modele = $this->model_pdf; } elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) { $modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF; } @@ -2984,13 +2982,13 @@ class CommandeFournisseur extends CommonOrder } /** - * Return the max number delivery delay in day - * - * @param Translate $langs Language object - * @return string Translated string - */ - public function getMaxDeliveryTimeDay($langs) - { + * Return the max number delivery delay in day + * + * @param Translate $langs Language object + * @return string Translated string + */ + public function getMaxDeliveryTimeDay($langs) + { if (empty($this->lines)) return ''; $obj = new ProductFournisseur($this->db); @@ -3042,219 +3040,219 @@ class CommandeFournisseur extends CommonOrder return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } - /** - * Is the supplier order delayed? - * - * @return bool - */ - public function hasDelay() - { - global $conf; + /** + * Is the supplier order delayed? + * + * @return bool + */ + public function hasDelay() + { + global $conf; - if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility + if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility - $now = dol_now(); - $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery; + $now = dol_now(); + $date_to_test = empty($this->date_delivery) ? $this->date_commande : $this->date_delivery; - return ($this->statut > 0 && $this->statut < 4) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay); - } + return ($this->statut > 0 && $this->statut < 4) && $date_to_test && $date_to_test < ($now - $conf->commande->fournisseur->warning_delay); + } - /** - * Show the customer delayed info - * - * @return string Show delayed information - */ - public function showDelay() - { - global $conf, $langs; + /** + * Show the customer delayed info + * + * @return string Show delayed information + */ + public function showDelay() + { + global $conf, $langs; - if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility + if (empty($this->date_delivery) && !empty($this->date_livraison)) $this->date_delivery = $this->date_livraison; // For backward compatibility - if (empty($this->date_delivery)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); - else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day'); - $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); + if (empty($this->date_delivery)) $text = $langs->trans("OrderDate").' '.dol_print_date($this->date_commande, 'day'); + else $text = $text = $langs->trans("DeliveryDate").' '.dol_print_date($this->date_delivery, 'day'); + $text .= ' '.($conf->commande->fournisseur->warning_delay > 0 ? '+' : '-').' '.round(abs($conf->commande->fournisseur->warning_delay) / 3600 / 24, 1).' '.$langs->trans("days").' < '.$langs->trans("Today"); - return $text; - } + return $text; + } - /** - * Calc status regarding to dispatched stock - * - * @param User $user User action - * @param int $closeopenorder Close if received - * @param string $comment Comment - * @return int <0 if KO, 0 if not applicable, >0 if OK - */ - public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '') - { - global $conf, $langs; + /** + * Calc status regarding to dispatched stock + * + * @param User $user User action + * @param int $closeopenorder Close if received + * @param string $comment Comment + * @return int <0 if KO, 0 if not applicable, >0 if OK + */ + public function calcAndSetStatusDispatch(User $user, $closeopenorder = 1, $comment = '') + { + global $conf, $langs; - 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'; + 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(); - $qtywished = array(); + $qtydelivered = array(); + $qtywished = array(); - $supplierorderdispatch = new CommandeFournisseurDispatch($this->db); - $filter = array('t.fk_commande'=>$this->id); - if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { - $filter['t.status'] = 1; // Restrict to lines with status validated - } + $supplierorderdispatch = new CommandeFournisseurDispatch($this->db); + $filter = array('t.fk_commande'=>$this->id); + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $filter['t.status'] = 1; // Restrict to lines with status validated + } - $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter); - if ($ret < 0) - { - $this->error = $supplierorderdispatch->error; $this->errors = $supplierorderdispatch->errors; - return $ret; - } else { - if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) - { - $date_liv = dol_now(); + $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter); + if ($ret < 0) + { + $this->error = $supplierorderdispatch->error; $this->errors = $supplierorderdispatch->errors; + return $ret; + } else { + if (is_array($supplierorderdispatch->lines) && count($supplierorderdispatch->lines) > 0) + { + $date_liv = dol_now(); - // Build array with quantity deliverd by product - foreach ($supplierorderdispatch->lines as $line) { - $qtydelivered[$line->fk_product] += $line->qty; - } - foreach ($this->lines as $line) { - $qtywished[$line->fk_product] += $line->qty; - } - //Compare array - $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys. - $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys - $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys - /*var_dump(array_keys($qtydelivered)); + // Build array with quantity deliverd by product + foreach ($supplierorderdispatch->lines as $line) { + $qtydelivered[$line->fk_product] += $line->qty; + } + foreach ($this->lines as $line) { + $qtywished[$line->fk_product] += $line->qty; + } + //Compare array + $diff_array = array_diff_assoc($qtydelivered, $qtywished); // Warning: $diff_array is done only on common keys. + $keysinwishednotindelivered = array_diff(array_keys($qtywished), array_keys($qtydelivered)); // To check we also have same number of keys + $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;*/ - 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) { - return -1; - } - return 5; - } else { - //Diff => received partially - //$ret=$this->setStatus($user,4); - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret < 0) { - return -1; - } - return 4; - } - } elseif (!empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED)) { - //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...) + 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) { + return -1; + } + return 5; + } else { + //Diff => received partially + //$ret=$this->setStatus($user,4); + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { + return -1; + } + return 4; + } + } elseif (!empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED)) { + //set livraison to 'tot' if more products received than wished. (and if $closeopenorder is set to 1 of course...) - $close = 0; + $close = 0; - if (count($diff_array) > 0) - { - //there are some difference between the two arrays + if (count($diff_array) > 0) + { + //there are some difference between the two arrays - //scan the array of results - foreach ($diff_array as $key => $value) - { - //if the quantity delivered is greater or equal to wish quantity - if ($qtydelivered[$key] >= $qtywished[$key]) - { - $close++; - } - } - } + //scan the array of results + foreach ($diff_array as $key => $value) + { + //if the quantity delivered is greater or equal to wish quantity + if ($qtydelivered[$key] >= $qtywished[$key]) + { + $close++; + } + } + } - if ($close == count($diff_array)) { - //all the products are received equal or more than the wished quantity - if ($closeopenorder) { - $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret < 0) { - return -1; - } - return 5; - } else { - //Diff => received partially - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret < 0) { - return -1; - } - return 4; - } - } else { - //all the products are not received - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret < 0) { - return -1; - } - return 4; - } - } else { - //Diff => received partially - $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($ret < 0) { - return -1; - } - return 4; - } - } - return 1; - } - } - return 0; - } + if ($close == count($diff_array)) { + //all the products are received equal or more than the wished quantity + if ($closeopenorder) { + $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { + return -1; + } + return 5; + } else { + //Diff => received partially + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { + return -1; + } + return 4; + } + } else { + //all the products are not received + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { + return -1; + } + return 4; + } + } else { + //Diff => received partially + $ret = $this->Livraison($user, $date_liv, 'par', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($ret < 0) { + return -1; + } + return 4; + } + } + return 1; + } + } + return 0; + } - /** - * Load array this->receptions of lines of shipments with nb of products sent for each order line - * Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order - * - * @param int $filtre_statut Filter on shipment status - * @return int <0 if KO, Nb of lines found if OK - */ - public function loadReceptions($filtre_statut = -1) - { - $this->receptions = array(); + /** + * Load array this->receptions of lines of shipments with nb of products sent for each order line + * Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order + * + * @param int $filtre_statut Filter on shipment status + * @return int <0 if KO, Nb of lines found if OK + */ + public function loadReceptions($filtre_statut = -1) + { + $this->receptions = array(); - $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,'; - $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; - $sql .= ' WHERE'; - 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; - $sql .= ' GROUP BY cd.rowid, cd.fk_product'; + $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,'; + $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; + $sql .= ' WHERE'; + 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; + $sql .= ' GROUP BY cd.rowid, cd.fk_product'; - dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - 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++; - } - $this->db->free(); + dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + 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++; + } + $this->db->free(); - return $num; - } else { - $this->error = $this->db->lasterror(); - return -1; - } - } + return $num; + } else { + $this->error = $this->db->lasterror(); + return -1; + } + } } @@ -3264,7 +3262,7 @@ class CommandeFournisseur extends CommonOrder */ class CommandeFournisseurLigne extends CommonOrderLine { - /** + /** * @var string ID to identify managed object */ public $element = 'commande_fournisseurdet'; @@ -3274,32 +3272,32 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public $table_element = 'commande_fournisseurdet'; - public $oldline; + public $oldline; - /** - * Id of parent order - * @var int - */ - public $fk_commande; + /** + * Id of parent order + * @var int + */ + public $fk_commande; - // From llx_commande_fournisseurdet - /** - * @var int ID - */ - public $fk_parent_line; + // From llx_commande_fournisseurdet + /** + * @var int ID + */ + public $fk_parent_line; - /** - * @var int ID - */ - public $fk_facture; + /** + * @var int ID + */ + public $fk_facture; - /** - * @var string supplier order line label - */ - public $label; + /** + * @var string supplier order line label + */ + public $label; - public $rang = 0; - public $special_code = 0; + public $rang = 0; + public $special_code = 0; /** * Unit price without taxes @@ -3307,100 +3305,100 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public $pu_ht; - public $date_start; - public $date_end; + public $date_start; + public $date_end; - // From llx_product_fournisseur_price + // From llx_product_fournisseur_price /** * Supplier reference of price when we added the line. May have been changed after line was added. * @var string */ - public $ref_supplier; - public $remise; - public $product_libelle; + public $ref_supplier; + public $remise; + public $product_libelle; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Load line order - * - * @param int $rowid Id line order - * @return int <0 if KO, >0 if OK - */ - public function fetch($rowid) - { - global $conf; + /** + * Load line order + * + * @param int $rowid Id line order + * @return int <0 if KO, >0 if OK + */ + public function fetch($rowid) + { + global $conf; - $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx, cd.special_code,'; - $sql .= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,'; - $sql .= ' cd.remise, cd.remise_percent, cd.subprice,'; - $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; - $sql .= ' cd.total_localtax1, cd.total_localtax2,'; - $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,'; - $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,'; + $sql = 'SELECT cd.rowid, cd.fk_commande, cd.fk_product, cd.product_type, cd.description, cd.qty, cd.tva_tx, cd.special_code,'; + $sql .= ' cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.ref,'; + $sql .= ' cd.remise, cd.remise_percent, cd.subprice,'; + $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; + $sql .= ' cd.total_localtax1, cd.total_localtax2,'; + $sql .= ' p.ref as product_ref, p.label as product_libelle, 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)) $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'; + $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)) $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) - { - $objp = $this->db->fetch_object($result); + $sql .= ' WHERE cd.rowid = '.$rowid; + $result = $this->db->query($sql); + if ($result) + { + $objp = $this->db->fetch_object($result); - if (!empty($objp)) - { - $this->rowid = $objp->rowid; - $this->id = $objp->rowid; - $this->fk_commande = $objp->fk_commande; - $this->desc = $objp->description; - $this->qty = $objp->qty; - $this->ref_fourn = $objp->ref; - $this->ref_supplier = $objp->ref; - $this->subprice = $objp->subprice; - $this->tva_tx = $objp->tva_tx; - $this->localtax1_tx = $objp->localtax1_tx; - $this->localtax2_tx = $objp->localtax2_tx; - $this->localtax1_type = $objp->localtax1_type; - $this->localtax2_type = $objp->localtax2_type; - $this->remise = $objp->remise; - $this->remise_percent = $objp->remise_percent; - $this->fk_product = $objp->fk_product; - $this->info_bits = $objp->info_bits; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_localtax1 = $objp->total_localtax1; - $this->total_localtax2 = $objp->total_localtax2; - $this->total_ttc = $objp->total_ttc; - $this->product_type = $objp->product_type; - $this->special_code = $objp->special_code; + if (!empty($objp)) + { + $this->rowid = $objp->rowid; + $this->id = $objp->rowid; + $this->fk_commande = $objp->fk_commande; + $this->desc = $objp->description; + $this->qty = $objp->qty; + $this->ref_fourn = $objp->ref; + $this->ref_supplier = $objp->ref; + $this->subprice = $objp->subprice; + $this->tva_tx = $objp->tva_tx; + $this->localtax1_tx = $objp->localtax1_tx; + $this->localtax2_tx = $objp->localtax2_tx; + $this->localtax1_type = $objp->localtax1_type; + $this->localtax2_type = $objp->localtax2_type; + $this->remise = $objp->remise; + $this->remise_percent = $objp->remise_percent; + $this->fk_product = $objp->fk_product; + $this->info_bits = $objp->info_bits; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_localtax1 = $objp->total_localtax1; + $this->total_localtax2 = $objp->total_localtax2; + $this->total_ttc = $objp->total_ttc; + $this->product_type = $objp->product_type; + $this->special_code = $objp->special_code; - $this->ref = $objp->product_ref; - $this->product_ref = $objp->product_ref; - $this->product_libelle = $objp->product_libelle; - $this->product_desc = $objp->product_desc; + $this->ref = $objp->product_ref; + $this->product_ref = $objp->product_ref; + $this->product_libelle = $objp->product_libelle; + $this->product_desc = $objp->product_desc; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $this->packaging = $objp->packaging; $this->fk_fournprice = $objp->fk_pfp; } - $this->date_start = $this->db->jdate($objp->date_start); - $this->date_end = $this->db->jdate($objp->date_end); - $this->fk_unit = $objp->fk_unit; + $this->date_start = $this->db->jdate($objp->date_start); + $this->date_end = $this->db->jdate($objp->date_end); + $this->fk_unit = $objp->fk_unit; $this->multicurrency_subprice = $objp->multicurrency_subprice; $this->multicurrency_total_ht = $objp->multicurrency_total_ht; @@ -3409,284 +3407,284 @@ class CommandeFournisseurLigne extends CommonOrderLine $this->fetch_optionals(); - $this->db->free($result); - return 1; - } else { - $this->error = 'Supplier order line with id='.$rowid.' not found'; - dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); - return 0; - } - } else { - dol_print_error($this->db); - return -1; - } - } + $this->db->free($result); + return 1; + } else { + $this->error = 'Supplier order line with id='.$rowid.' not found'; + dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); + return 0; + } + } else { + dol_print_error($this->db); + return -1; + } + } - /** - * Insert line into database - * - * @param int $notrigger 1 = disable triggers - * @return int <0 if KO, >0 if OK - */ - public function insert($notrigger = 0) - { - global $conf, $user; + /** + * Insert line into database + * + * @param int $notrigger 1 = disable triggers + * @return int <0 if KO, >0 if OK + */ + public function insert($notrigger = 0) + { + global $conf, $user; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::insert rang=".$this->rang); + 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; + // 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; - // 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; - } + // 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; + // Check parameters + if ($this->product_type < 0) return -1; - $this->db->begin(); + $this->db->begin(); - // Insertion dans base de la ligne - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql .= " (fk_commande, label, description, date_start, date_end,"; - $sql .= " fk_product, product_type, special_code, rang,"; - $sql .= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,"; - $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,"; - $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc"; - $sql .= ")"; - $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,"; } - $sql .= "'".$this->db->escape($this->product_type)."',"; - $sql .= "'".$this->db->escape($this->special_code)."',"; - $sql .= "'".$this->db->escape($this->rang)."',"; - $sql .= "'".$this->db->escape($this->qty)."', "; - $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; - $sql .= " ".$this->tva_tx.", "; - $sql .= " ".$this->localtax1_tx.","; - $sql .= " ".$this->localtax2_tx.","; - $sql .= " '".$this->db->escape($this->localtax1_type)."',"; - $sql .= " '".$this->db->escape($this->localtax2_type)."',"; - $sql .= " ".$this->remise_percent.", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',"; - $sql .= " ".price2num($this->total_ht).","; - $sql .= " ".price2num($this->total_tva).","; - $sql .= " ".price2num($this->total_localtax1).","; - $sql .= " ".price2num($this->total_localtax2).","; - $sql .= " ".price2num($this->total_ttc).","; - $sql .= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); - $sql .= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null"); - $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql .= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0'); - $sql .= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0'); - $sql .= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0'); - $sql .= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0'); - $sql .= ")"; + // Insertion dans base de la ligne + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; + $sql .= " (fk_commande, label, description, date_start, date_end,"; + $sql .= " fk_product, product_type, special_code, rang,"; + $sql .= " qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice, ref,"; + $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_unit,"; + $sql .= " fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc"; + $sql .= ")"; + $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,"; } + $sql .= "'".$this->db->escape($this->product_type)."',"; + $sql .= "'".$this->db->escape($this->special_code)."',"; + $sql .= "'".$this->db->escape($this->rang)."',"; + $sql .= "'".$this->db->escape($this->qty)."', "; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".$this->tva_tx.", "; + $sql .= " ".$this->localtax1_tx.","; + $sql .= " ".$this->localtax2_tx.","; + $sql .= " '".$this->db->escape($this->localtax1_type)."',"; + $sql .= " '".$this->db->escape($this->localtax2_type)."',"; + $sql .= " ".$this->remise_percent.", ".price2num($this->subprice, 'MU').", '".$this->db->escape($this->ref_supplier)."',"; + $sql .= " ".price2num($this->total_ht).","; + $sql .= " ".price2num($this->total_tva).","; + $sql .= " ".price2num($this->total_localtax1).","; + $sql .= " ".price2num($this->total_localtax2).","; + $sql .= " ".price2num($this->total_ttc).","; + $sql .= ($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null"); + $sql .= ", ".($this->fk_multicurrency ? $this->fk_multicurrency : "null"); + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".($this->multicurrency_subprice ? price2num($this->multicurrency_subprice) : '0'); + $sql .= ", ".($this->multicurrency_total_ht ? price2num($this->multicurrency_total_ht) : '0'); + $sql .= ", ".($this->multicurrency_total_tva ? price2num($this->multicurrency_total_tva) : '0'); + $sql .= ", ".($this->multicurrency_total_ttc ? price2num($this->multicurrency_total_ttc) : '0'); + $sql .= ")"; - dol_syslog(get_class($this)."::insert", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->rowid = $this->id; + dol_syslog(get_class($this)."::insert", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->rowid = $this->id; - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); + if ($result < 0) $error++; + // End call triggers + } - if (!$error) { - $this->db->commit(); - return 1; - } + if (!$error) { + $this->db->commit(); + return 1; + } - foreach ($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg); - } - $this->db->rollback(); - return -1 * $error; - } else { - $this->errors[] = $this->db->error(); - $this->db->rollback(); - return -2; - } - } - /** - * Update the line object into db - * - * @param int $notrigger 1 = disable triggers - * @return int <0 si ko, >0 si ok - */ - public function update($notrigger = 0) - { - global $conf, $user; + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } else { + $this->errors[] = $this->db->error(); + $this->db->rollback(); + return -2; + } + } + /** + * Update the line object into db + * + * @param int $notrigger 1 = disable triggers + * @return int <0 si ko, >0 si ok + */ + public function update($notrigger = 0) + { + global $conf, $user; - $error = 0; + $error = 0; - $this->db->begin(); + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; - $sql .= " description='".$this->db->escape($this->desc)."'"; - $sql .= ", ref='".$this->db->escape($this->ref_supplier)."'"; - $sql .= ", subprice='".price2num($this->subprice)."'"; - //$sql.= ",remise='".price2num($remise)."'"; - $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= ", ref='".$this->db->escape($this->ref_supplier)."'"; + $sql .= ", subprice='".price2num($this->subprice)."'"; + //$sql.= ",remise='".price2num($remise)."'"; + $sql .= ", remise_percent='".price2num($this->remise_percent)."'"; $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->vat_src_code)."'"; - $sql .= ", tva_tx='".price2num($this->tva_tx)."'"; - $sql .= ", localtax1_tx='".price2num($this->total_localtax1)."'"; - $sql .= ", localtax2_tx='".price2num($this->total_localtax2)."'"; - $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; - $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql .= ", qty='".price2num($this->qty)."'"; - $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 .= ", info_bits='".$this->db->escape($this->info_bits)."'"; - $sql .= ", total_ht='".price2num($this->total_ht)."'"; - $sql .= ", total_tva='".price2num($this->total_tva)."'"; - $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; - $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; - $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; - $sql .= ", product_type=".$this->product_type; - $sql .= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0); - $sql .= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'" : ", fk_unit=null"); + $sql .= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql .= ", localtax1_tx='".price2num($this->total_localtax1)."'"; + $sql .= ", localtax2_tx='".price2num($this->total_localtax2)."'"; + $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; + $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; + $sql .= ", qty='".price2num($this->qty)."'"; + $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 .= ", info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= ", total_ht='".price2num($this->total_ht)."'"; + $sql .= ", total_tva='".price2num($this->total_tva)."'"; + $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql .= ", product_type=".$this->product_type; + $sql .= ", special_code=".(!empty($this->special_code) ? $this->special_code : 0); + $sql .= ($this->fk_unit ? ", fk_unit='".$this->db->escape($this->fk_unit)."'" : ", fk_unit=null"); - // Multicurrency - $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + // Multicurrency + $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql .= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result > 0) - { - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result > 0) + { + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - global $user; - // Call trigger - $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (!$error && !$notrigger) + { + global $user; + // Call trigger + $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Delete line in database - * - * @param int $notrigger 1=Disable call to triggers - * @return int <0 if KO, >0 if OK - */ - public function delete($notrigger = 0) - { - global $user; + /** + * Delete line in database + * + * @param int $notrigger 1=Disable call to triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($notrigger = 0) + { + global $user; - $error = 0; + $error = 0; - $this->db->begin(); + $this->db->begin(); // extrafields - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + $result = $this->deleteExtraFields(); + 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=".$this->id; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); - if ($result < 0) $error++; - // End call triggers - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); + if ($result < 0) $error++; + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } + if (!$error) + { + $this->db->commit(); + return 1; + } - 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->error = $this->db->lasterror(); - return -1; - } - } + 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->error = $this->db->lasterror(); + return -1; + } + } } diff --git a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php index d85a4e0941a..a7abed27369 100644 --- a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php +++ b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php @@ -33,10 +33,10 @@ require_once DOL_DOCUMENT_ROOT."/reception/class/reception.class.php"; */ class CommandeFournisseurDispatch extends CommonObject { - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -59,31 +59,31 @@ class CommandeFournisseurDispatch extends CommonObject public $table_element = 'commande_fournisseur_dispatch'; //!< Name of table without prefix where object is stored public $lines = array(); - /** + /** * @var int ID */ public $id; /** - * @var int ID - */ + * @var int ID + */ public $fk_commande; /** - * @var int ID - */ + * @var int ID + */ public $fk_product; /** - * @var int ID - */ + * @var int ID + */ public $fk_commandefourndet; public $qty; /** - * @var int ID - */ + * @var int ID + */ public $fk_entrepot; /** @@ -107,35 +107,35 @@ class CommandeFournisseurDispatch extends CommonObject - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct($db) - { - $this->db = $db; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct($db) + { + $this->db = $db; - // List of language codes for status - $this->statuts[0] = 'Received'; - $this->statuts[1] = 'Verified'; - $this->statuts[2] = 'Denied'; - $this->statutshort[0] = 'Received'; - $this->statutshort[1] = 'Verified'; - $this->statutshort[2] = 'Denied'; - } + // List of language codes for status + $this->statuts[0] = 'Received'; + $this->statuts[1] = 'Verified'; + $this->statuts[2] = 'Denied'; + $this->statutshort[0] = 'Received'; + $this->statutshort[1] = 'Verified'; + $this->statutshort[2] = 'Denied'; + } - /** - * Create object into database - * - * @param User $user User that creates - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - public function create($user, $notrigger = 0) - { - global $conf, $langs, $hookmanager; + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create($user, $notrigger = 0) + { + global $conf, $langs, $hookmanager; $error = 0; // Clean parameters @@ -155,7 +155,7 @@ class CommandeFournisseurDispatch extends CommonObject // Check parameters // Put here code to add control on parameters values - // Insert request + // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."("; $sql .= "fk_commande,"; $sql .= "fk_product,"; @@ -172,7 +172,7 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= "fk_reception"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " ".(!isset($this->fk_commande) ? 'NULL' : "'".$this->db->escape($this->fk_commande)."'").","; $sql .= " ".(!isset($this->fk_product) ? 'NULL' : "'".$this->db->escape($this->fk_product)."'").","; $sql .= " ".(!isset($this->fk_commandefourndet) ? 'NULL' : "'".$this->db->escape($this->fk_commandefourndet)."'").","; @@ -191,60 +191,60 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->begin(); dol_syslog(__METHOD__, LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); if (!$notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. - //// Call triggers - //$result=$this->call_trigger('MYOBJECT_CREATE',$user); - //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} - //// End call triggers + //// Call triggers + //$result=$this->call_trigger('MYOBJECT_CREATE',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} + //// End call triggers } - } + } - // Create extrafields - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) $error++; - } + // Create extrafields + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) $error++; + } - // Commit or rollback - if ($error) + // Commit or rollback + if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; } else { $this->db->commit(); - return $this->id; + return $this->id; } - } + } - /** - * Load object in memory from the database - * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $ref = '') - { - global $langs; - $sql = "SELECT"; + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $ref = '') + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.fk_commande,"; @@ -263,19 +263,19 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= " t.fk_reception"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - if ($ref) $sql .= " WHERE t.ref = '".$ref."'"; - else $sql .= " WHERE t.rowid = ".$id; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + if ($ref) $sql .= " WHERE t.ref = '".$ref."'"; + else $sql .= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch"); - $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"); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->fk_commande = $obj->fk_commande; $this->fk_product = $obj->fk_product; @@ -293,27 +293,27 @@ class CommandeFournisseurDispatch extends CommonObject $this->fk_reception = $obj->fk_reception; $this->fetch_optionals(); - } - $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; + } + } - /** - * Update object into database - * - * @param User $user User that modifies - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; // Clean parameters @@ -333,8 +333,8 @@ class CommandeFournisseurDispatch extends CommonObject // Check parameters // Put here code to add a control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; $sql .= " fk_commande=".(isset($this->fk_commande) ? $this->fk_commande : "null").","; $sql .= " fk_product=".(isset($this->fk_product) ? $this->fk_product : "null").","; @@ -351,13 +351,13 @@ 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=".$this->id; $this->db->begin(); dol_syslog(__METHOD__); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -373,20 +373,20 @@ class CommandeFournisseurDispatch extends CommonObject if (!$notrigger) { - // Uncomment this and change MYOBJECT to your own tag if you - $result = $this->call_trigger('LINERECEPTION_UPDATE', $user); - if ($result < 0) $error++; - //// End call triggers + // Uncomment this and change MYOBJECT to your own tag if you + $result = $this->call_trigger('LINERECEPTION_UPDATE', $user); + if ($result < 0) $error++; + //// End call triggers } } - // Commit or rollback + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; @@ -394,16 +394,16 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->commit(); return 1; } - } + } /** - * 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; @@ -416,16 +416,16 @@ class CommandeFournisseurDispatch extends CommonObject if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. + // want this action calls a trigger. - //// Call triggers - //$result=$this->call_trigger('MYOBJECT_DELETE',$user); - //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} - //// End call triggers + //// Call triggers + //$result=$this->call_trigger('MYOBJECT_DELETE',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} + //// End call triggers } } - // Remove extrafields + // Remove extrafields if (!$error) { $result = $this->deleteExtraFields(); if ($result < 0) @@ -437,21 +437,21 @@ class CommandeFournisseurDispatch extends CommonObject if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid=".$this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " WHERE rowid=".$this->id; - dol_syslog(__METHOD__); - $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + dol_syslog(__METHOD__); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } } - // Commit or rollback + // Commit or rollback if ($error) { foreach ($this->errors as $errmsg) { - dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); - $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; @@ -466,8 +466,8 @@ class CommandeFournisseurDispatch extends CommonObject /** * 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 + * @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) @@ -516,57 +516,57 @@ class CommandeFournisseurDispatch extends CommonObject - /** - * Return label of the status of object - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto - * @return string Label - */ - public function getLibStatut($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } + /** + * Return label of the status of object + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return label of a status - * - * @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 - * @return string Label of status - */ - public function LibStatut($status, $mode = 0) - { - // phpcs:enable - global $langs; - $langs->load('orders'); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of a status + * + * @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 + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; + $langs->load('orders'); - if ($mode == 0) - { - return $langs->trans($this->statuts[$status]); - } elseif ($mode == 1) - { - return $langs->trans($this->statutshort[$status]); - } 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 ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut0'); - elseif ($status == 1) return ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut4'); - elseif ($status == 2) return ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut8'); - } - } + if ($mode == 0) + { + return $langs->trans($this->statuts[$status]); + } elseif ($mode == 1) + { + return $langs->trans($this->statutshort[$status]); + } 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 ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut0'); + elseif ($status == 1) return ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut4'); + elseif ($status == 2) return ''.$langs->trans($this->statutshort[$status]).' '.img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } + } /** @@ -627,7 +627,7 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= " t.eatby,"; $sql .= " t.sellby"; - $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; // Manage filter $sqlwhere = array(); @@ -676,7 +676,7 @@ class CommandeFournisseurDispatch extends CommonObject $line->batch = $obj->batch; $line->eatby = $this->db->jdate($obj->eatby); $line->sellby = $this->db->jdate($obj->sellby); - $line->fetch_optionals(); + $line->fetch_optionals(); $this->lines[$line->id] = $line; } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 04525afa04d..264832cadc2 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -4,7 +4,7 @@ * Copyright (C) 2004 Christophe Combelles * Copyright (C) 2005 Marc Barilley * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2017 Juanjo Menent + * Copyright (C) 2010-2020 Juanjo Menent * Copyright (C) 2013-2019 Philippe Grand * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2016 Marcos García @@ -34,7 +34,7 @@ * \brief File of class to manage suppliers invoices */ -include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php'; +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'; @@ -43,54 +43,54 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; */ class FactureFournisseur extends CommonInvoice { - /** + /** * @var string ID to identify managed object */ public $element = 'invoice_supplier'; - /** - * @var string Name of table without prefix where object is stored - */ - public $table_element = 'facture_fourn'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'facture_fourn'; - /** - * @var int Name of subtable line - */ - public $table_element_line = 'facture_fourn_det'; + /** + * @var int Name of subtable line + */ + public $table_element_line = 'facture_fourn_det'; - /** - * @var int Field with ID of parent key if this field has a parent - */ - public $fk_element = 'fk_facture_fourn'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + public $fk_element = 'fk_facture_fourn'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'supplier_invoice'; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'supplier_invoice'; - /** - * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - * @var int - */ - public $ismultientitymanaged = 1; + /** + * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int + */ + public $ismultientitymanaged = 1; - /** - * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user - * @var integer - */ - public $restrictiononfksoc = 1; + /** + * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user + * @var integer + */ + public $restrictiononfksoc = 1; - /** - * {@inheritdoc} - */ - protected $table_ref_field = 'ref'; + /** + * {@inheritdoc} + */ + protected $table_ref_field = 'ref'; - /** + /** * @var int ID */ public $rowid; - /** + /** * @var string Ref */ public $ref; @@ -98,265 +98,257 @@ class FactureFournisseur extends CommonInvoice public $label; public $libelle; // @deprecated - public $product_ref; - public $ref_supplier; - public $socid; - //Check constants for types - public $type = self::TYPE_STANDARD; + public $product_ref; + public $ref_supplier; + public $socid; + //Check constants for types + public $type = self::TYPE_STANDARD; /** * Supplier invoice status * @var int * @see FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_PAID, FactureFournisseur::STATUS_ABANDONED */ - public $statut; + public $statut; - /** - * Set to 1 if the invoice is completely paid, otherwise is 0 - * @var int - * @deprecated Use statuses stored in self::statut - */ - public $paye; + /** + * Set to 1 if the invoice is completely paid, otherwise is 0 + * @var int + * @deprecated Use statuses stored in self::statut + */ + public $paye; - public $author; + public $author; - /** - * Date creation record (datec) - * - * @var integer - */ - public $datec; + /** + * Date creation record (datec) + * + * @var integer + */ + public $datec; - /** - * Date modification record (tms) - * - * @var integer - */ - public $tms; + /** + * Date modification record (tms) + * + * @var integer + */ + public $tms; - /** - * Invoice date (date) - * - * @var integer - */ - public $date; + /** + * Invoice date (date) + * + * @var integer + */ + public $date; - /** - * Max payment date (date_echeance) - * - * @var integer - */ - public $date_echeance; + /** + * Max payment date (date_echeance) + * + * @var integer + */ + public $date_echeance; - public $amount = 0; - public $remise = 0; - public $tva = 0; - public $localtax1; - public $localtax2; - public $total_ht = 0; - public $total_tva = 0; - public $total_localtax1 = 0; - public $total_localtax2 = 0; - public $total_ttc = 0; + public $amount = 0; + public $remise = 0; + public $tva = 0; + public $localtax1; + public $localtax2; + public $total_ht = 0; + public $total_tva = 0; + public $total_localtax1 = 0; + public $total_localtax2 = 0; + public $total_ttc = 0; /** * @deprecated * @see $note_private, $note_public */ - public $note; + public $note; - public $note_private; - public $note_public; - public $propalid; - public $cond_reglement_id; - public $cond_reglement_code; + public $note_private; + public $note_public; + public $propalid; + public $cond_reglement_id; + public $cond_reglement_code; - /** - * @var int ID - */ - public $fk_account; + /** + * @var int ID + */ + public $fk_account; - public $mode_reglement_id; - public $mode_reglement_code; + public $mode_reglement_id; + public $mode_reglement_code; /** * Invoice lines * @var SupplierInvoiceLine[] */ - public $lines = array(); + public $lines = array(); /** * @deprecated */ - public $fournisseur; + public $fournisseur; - /** - * @var int ID Incorterms - */ - public $fk_incoterms; - - public $location_incoterms; - public $label_incoterms; //Used into tooltip - - public $extraparams = array(); + public $extraparams = array(); // Multicurrency /** - * @var int ID - */ - public $fk_multicurrency; + * @var int ID + */ + public $fk_multicurrency; - public $multicurrency_code; - public $multicurrency_tx; - public $multicurrency_total_ht; - public $multicurrency_total_tva; - public $multicurrency_total_ttc; - //! id of source var_dump($$this);invoice if replacement invoice or credit note - /** - * @var int ID - */ - public $fk_facture_source; + public $multicurrency_code; + public $multicurrency_tx; + public $multicurrency_total_ht; + public $multicurrency_total_tva; + public $multicurrency_total_ttc; + //! id of source var_dump($$this);invoice if replacement invoice or credit note + /** + * @var int ID + */ + public $fk_facture_source; - public $fields = array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), - 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15), - 'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>20), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25, 'index'=>1), - 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>30), - 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35), - 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>40), - 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>45), - 'datef' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>50), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>55), - 'libelle' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'position'=>60), - 'paye' =>array('type'=>'smallint(6)', 'label'=>'Paye', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65), - 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70), - 'remise' =>array('type'=>'double(24,8)', 'label'=>'Discount', 'enabled'=>1, 'visible'=>-1, 'position'=>75), - 'close_code' =>array('type'=>'varchar(16)', 'label'=>'CloseCode', 'enabled'=>1, 'visible'=>-1, 'position'=>80), - 'close_note' =>array('type'=>'varchar(128)', 'label'=>'CloseNote', 'enabled'=>1, 'visible'=>-1, 'position'=>85), - 'tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>90), - 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>95), - 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>100), - 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>105), - 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'TotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>110), - 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>115), - 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>125), - 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>130), - 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>135), - 'fk_facture_source' =>array('type'=>'integer', 'label'=>'Fk facture source', 'enabled'=>1, 'visible'=>-1, 'position'=>140), - 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>145), - 'fk_account' =>array('type'=>'integer', 'label'=>'Account', 'enabled'=>1, 'visible'=>-1, 'position'=>150), - 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>155), - 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>160), - 'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateLimReglement', 'enabled'=>1, 'visible'=>-1, 'position'=>165), - 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>170), - 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>175), - 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>180), - 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>190), - 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>-1, 'position'=>195), - 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>-1, 'position'=>200), - 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyId', 'enabled'=>1, 'visible'=>-1, 'position'=>205), - 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>210), - 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>1, 'visible'=>-1, 'position'=>215), - 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>220), - 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>225), - 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>230), - 'date_pointoftax' =>array('type'=>'date', 'label'=>'Date pointoftax', 'enabled'=>1, 'visible'=>-1, 'position'=>235), - 'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>240), - 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>245), - 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), - ); + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15), + 'ref_supplier' =>array('type'=>'varchar(255)', 'label'=>'RefSupplier', 'enabled'=>1, 'visible'=>-1, 'position'=>20), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>25, 'index'=>1), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>30), + 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>40), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + 'datef' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>55), + 'libelle' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'paye' =>array('type'=>'smallint(6)', 'label'=>'Paye', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>65), + 'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70), + 'remise' =>array('type'=>'double(24,8)', 'label'=>'Discount', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'close_code' =>array('type'=>'varchar(16)', 'label'=>'CloseCode', 'enabled'=>1, 'visible'=>-1, 'position'=>80), + 'close_note' =>array('type'=>'varchar(128)', 'label'=>'CloseNote', 'enabled'=>1, 'visible'=>-1, 'position'=>85), + 'tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>100), + 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>105), + 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'TotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>115), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>125), + 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>130), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>135), + 'fk_facture_source' =>array('type'=>'integer', 'label'=>'Fk facture source', 'enabled'=>1, 'visible'=>-1, 'position'=>140), + 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>145), + 'fk_account' =>array('type'=>'integer', 'label'=>'Account', 'enabled'=>1, 'visible'=>-1, 'position'=>150), + 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>155), + 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>160), + 'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateLimReglement', 'enabled'=>1, 'visible'=>-1, 'position'=>165), + 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>170), + 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>175), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>180), + 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLocation', 'enabled'=>1, 'visible'=>-1, 'position'=>200), + 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyId', 'enabled'=>1, 'visible'=>-1, 'position'=>205), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>210), + 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>220), + 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>225), + 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyTotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>230), + 'date_pointoftax' =>array('type'=>'date', 'label'=>'Date pointoftax', 'enabled'=>1, 'visible'=>-1, 'position'=>235), + 'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>240), + 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>245), + 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), + ); - /** - * Standard invoice - */ - const TYPE_STANDARD = 0; + /** + * Standard invoice + */ + const TYPE_STANDARD = 0; - /** - * Replacement invoice - */ - const TYPE_REPLACEMENT = 1; + /** + * Replacement invoice + */ + const TYPE_REPLACEMENT = 1; - /** - * Credit note invoice - */ - const TYPE_CREDIT_NOTE = 2; + /** + * Credit note invoice + */ + const TYPE_CREDIT_NOTE = 2; - /** - * Deposit invoice - */ - const TYPE_DEPOSIT = 3; + /** + * Deposit invoice + */ + const TYPE_DEPOSIT = 3; - /** - * Draft - */ - const STATUS_DRAFT = 0; + /** + * Draft + */ + const STATUS_DRAFT = 0; - /** - * Validated (need to be paid) - */ - const STATUS_VALIDATED = 1; + /** + * Validated (need to be paid) + */ + const STATUS_VALIDATED = 1; - /** - * Classified paid. - * If paid partially, $this->close_code can be: - * - CLOSECODE_DISCOUNTVAT - * - CLOSECODE_BADDEBT - * If paid completelly, this->close_code will be null - */ - const STATUS_CLOSED = 2; + /** + * Classified paid. + * If paid partially, $this->close_code can be: + * - CLOSECODE_DISCOUNTVAT + * - CLOSECODE_BADDEBT + * If paid completelly, this->close_code will be null + */ + const STATUS_CLOSED = 2; - /** - * Classified abandoned and no payment done. - * $this->close_code can be: - * - CLOSECODE_BADDEBT - * - CLOSECODE_ABANDONED - * - CLOSECODE_REPLACED - */ - const STATUS_ABANDONED = 3; + /** + * Classified abandoned and no payment done. + * $this->close_code can be: + * - CLOSECODE_BADDEBT + * - CLOSECODE_ABANDONED + * - CLOSECODE_REPLACED + */ + const STATUS_ABANDONED = 3; const CLOSECODE_DISCOUNTVAT = 'discount_vat'; const CLOSECODE_BADCREDIT = 'badsupplier'; const CLOSECODE_ABANDONED = 'abandon'; const CLOSECODE_REPLACED = 'replaced'; - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; + */ + public function __construct($db) + { + $this->db = $db; - $this->products = array(); - } + $this->products = array(); + } - /** - * Create supplier invoice into database - * - * @param User $user object utilisateur qui cree - * @return int Id invoice created if OK, < 0 if KO - */ - public function create($user) - { - global $langs, $conf, $hookmanager; + /** + * Create supplier invoice into database + * + * @param User $user object utilisateur qui cree + * @return int Id invoice created if OK, < 0 if KO + */ + public function create($user) + { + global $langs, $conf, $hookmanager; $error = 0; - $now = dol_now(); + $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; + // 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; - $socid = $this->socid; - $ref_supplier = $this->ref_supplier; - $amount = $this->amount; - $remise = $this->remise; + $socid = $this->socid; + $ref_supplier = $this->ref_supplier; + $amount = $this->amount; + $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); @@ -368,73 +360,73 @@ class FactureFournisseur extends CommonInvoice $this->multicurrency_tx = 1; } - $this->db->begin(); + $this->db->begin(); - if (!$remise) $remise = 0; + if (!$remise) $remise = 0; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn ("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn ("; $sql .= "ref"; - $sql .= ", ref_supplier"; - $sql .= ", entity"; - $sql .= ", type"; - $sql .= ", libelle"; - $sql .= ", fk_soc"; - $sql .= ", datec"; - $sql .= ", datef"; + $sql .= ", ref_supplier"; + $sql .= ", entity"; + $sql .= ", type"; + $sql .= ", libelle"; + $sql .= ", fk_soc"; + $sql .= ", datec"; + $sql .= ", datef"; $sql .= ", fk_projet"; $sql .= ", fk_cond_reglement"; $sql .= ", fk_mode_reglement"; - $sql .= ", fk_account"; - $sql .= ", note_private"; - $sql .= ", note_public"; - $sql .= ", fk_user_author"; - $sql .= ", date_lim_reglement"; + $sql .= ", fk_account"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", fk_user_author"; + $sql .= ", date_lim_reglement"; $sql .= ", fk_incoterms, location_incoterms"; - $sql .= ", fk_multicurrency"; - $sql .= ", multicurrency_code"; - $sql .= ", multicurrency_tx"; - $sql .= ", fk_facture_source"; - $sql .= ")"; - $sql .= " VALUES ("; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ", fk_facture_source"; + $sql .= ")"; + $sql .= " VALUES ("; $sql .= "'(PROV)'"; - $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; - $sql .= ", ".$conf->entity; - $sql .= ", '".$this->db->escape($this->type)."'"; - $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->libelle)."'"; - $sql .= ", ".$this->socid; - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", '".$this->db->idate($this->date)."'"; + $sql .= ", '".$this->db->escape($this->ref_supplier)."'"; + $sql .= ", ".$conf->entity; + $sql .= ", '".$this->db->escape($this->type)."'"; + $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->libelle)."'"; + $sql .= ", ".$this->socid; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '".$this->db->idate($this->date)."'"; $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : "null"); $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "null"); - $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); - $sql .= ", '".$this->db->escape($this->note_private)."'"; - $sql .= ", '".$this->db->escape($this->note_public)."'"; - $sql .= ", ".$user->id.","; - $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null"; + $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", ".$user->id.","; + $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null"; $sql .= ", ".(int) $this->fk_incoterms; - $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql .= ", '".$this->db->escape($this->location_incoterms)."'"; $sql .= ", ".(int) $this->fk_multicurrency; $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql .= ", ".(double) $this->multicurrency_tx; - $sql .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL"); - $sql .= ")"; + $sql .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL"); + $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.'facture_fourn'); + 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.'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; + // 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; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) $error++; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + 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 } @@ -444,115 +436,115 @@ class FactureFournisseur extends CommonInvoice { 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) - { - dol_print_error($this->db); - $error++; - } - } - } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) - { - $origin_id = $tmp_origin_id; - $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { - dol_print_error($this->db); - $error++; - } - } + 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) + { + dol_print_error($this->db); + $error++; + } + } + } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (!$ret) + { + dol_print_error($this->db); + $error++; + } + } } } 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) - { - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; - $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; + 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) - { - $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); + $resql_insert = $this->db->query($sql); + if ($resql_insert) + { + $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); - $this->updateline( - $idligne, - $this->lines[$i]->description, - $this->lines[$i]->pu_ht, - $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''), - $this->lines[$i]->localtax1_tx, - $this->lines[$i]->localtax2_tx, - $this->lines[$i]->qty, - $this->lines[$i]->fk_product, - 'HT', - (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''), - $this->lines[$i]->product_type, - $this->lines[$i]->remise_percent, - false, - $this->lines[$i]->date_start, - $this->lines[$i]->date_end, - $this->lines[$i]->array_options, - $this->lines[$i]->fk_unit, - $this->lines[$i]->pu_ht_devise - ); - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -5; - } - } + $this->updateline( + $idligne, + $this->lines[$i]->description, + $this->lines[$i]->pu_ht, + $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''), + $this->lines[$i]->localtax1_tx, + $this->lines[$i]->localtax2_tx, + $this->lines[$i]->qty, + $this->lines[$i]->fk_product, + 'HT', + (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''), + $this->lines[$i]->product_type, + $this->lines[$i]->remise_percent, + false, + $this->lines[$i]->date_start, + $this->lines[$i]->date_end, + $this->lines[$i]->array_options, + $this->lines[$i]->fk_unit, + $this->lines[$i]->pu_ht_devise + ); + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -5; + } + } } 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) - { - $line = $this->lines[$i]; + dol_syslog("There is ".count($this->lines)." lines that are array lines"); + 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; + // 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; - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; - $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; + $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) - { - $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); + $resql_insert = $this->db->query($sql); + if ($resql_insert) + { + $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); - $this->updateline( - $idligne, - $line->description, - $line->pu_ht, - $line->tva_tx, - $line->localtax1_tx, - $line->localtax2_tx, - $line->qty, - $line->fk_product, - 'HT', - (!empty($line->info_bits) ? $line->info_bits : ''), - $line->product_type - ); - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -5; - } - } + $this->updateline( + $idligne, + $line->description, + $line->pu_ht, + $line->tva_tx, + $line->localtax1_tx, + $line->localtax2_tx, + $line->qty, + $line->fk_product, + 'HT', + (!empty($line->info_bits) ? $line->info_bits : ''), + $line->product_type + ); + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -5; + } + } } - // Update total price - $result = $this->update_price(); - if ($result > 0) - { + // Update total price + $result = $this->update_price(); + 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) @@ -563,155 +555,155 @@ class FactureFournisseur extends CommonInvoice if (!$error) { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user); + if ($result < 0) $error++; + // End call triggers } - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { - $this->db->rollback(); - return -4; - } - } else { - $this->error = $langs->trans('FailedToUpdatePrice'); - $this->db->rollback(); - return -3; - } - } else { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error = $langs->trans('ErrorRefAlreadyExists'); - $this->db->rollback(); - return -1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - } + if (!$error) + { + $this->db->commit(); + return $this->id; + } else { + $this->db->rollback(); + return -4; + } + } else { + $this->error = $langs->trans('FailedToUpdatePrice'); + $this->db->rollback(); + return -3; + } + } else { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error = $langs->trans('ErrorRefAlreadyExists'); + $this->db->rollback(); + return -1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + } - /** - * Load object in memory from database - * - * @param int $id Id supplier invoice - * @param string $ref Ref supplier invoice - * @return int <0 if KO, >0 if OK, 0 if not found - */ - public function fetch($id = '', $ref = '') - { - global $langs; + /** + * Load object in memory from database + * + * @param int $id Id supplier invoice + * @param string $ref Ref supplier invoice + * @return int <0 if KO, >0 if OK, 0 if not found + */ + public function fetch($id = '', $ref = '') + { + global $langs; - $sql = "SELECT"; - $sql .= " t.rowid,"; + $sql = "SELECT"; + $sql .= " t.rowid,"; $sql .= " t.ref,"; - $sql .= " t.ref_supplier,"; - $sql .= " t.entity,"; - $sql .= " t.type,"; - $sql .= " t.fk_soc,"; - $sql .= " t.datec,"; - $sql .= " t.datef,"; - $sql .= " t.tms,"; - $sql .= " t.libelle as label,"; - $sql .= " t.paye,"; - $sql .= " t.amount,"; - $sql .= " t.remise,"; - $sql .= " t.close_code,"; - $sql .= " t.close_note,"; - $sql .= " t.tva,"; - $sql .= " t.localtax1,"; - $sql .= " t.localtax2,"; - $sql .= " t.total_ht,"; - $sql .= " t.total_tva,"; - $sql .= " t.total_ttc,"; - $sql .= " t.fk_statut,"; - $sql .= " t.fk_user_author,"; - $sql .= " t.fk_user_valid,"; - $sql .= " t.fk_facture_source,"; - $sql .= " t.fk_projet as fk_project,"; - $sql .= " t.fk_cond_reglement,"; - $sql .= " t.fk_account,"; - $sql .= " t.fk_mode_reglement,"; - $sql .= " t.date_lim_reglement,"; - $sql .= " t.note_private,"; - $sql .= " t.note_public,"; - $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 .= ' s.nom as socnom, s.rowid as socid,'; - $sql .= ' t.fk_incoterms, t.location_incoterms,'; - $sql .= " i.libelle as label_incoterms,"; - $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t'; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; - $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 .= " t.ref_supplier,"; + $sql .= " t.entity,"; + $sql .= " t.type,"; + $sql .= " t.fk_soc,"; + $sql .= " t.datec,"; + $sql .= " t.datef,"; + $sql .= " t.tms,"; + $sql .= " t.libelle as label,"; + $sql .= " t.paye,"; + $sql .= " t.amount,"; + $sql .= " t.remise,"; + $sql .= " t.close_code,"; + $sql .= " t.close_note,"; + $sql .= " t.tva,"; + $sql .= " t.localtax1,"; + $sql .= " t.localtax2,"; + $sql .= " t.total_ht,"; + $sql .= " t.total_tva,"; + $sql .= " t.total_ttc,"; + $sql .= " t.fk_statut,"; + $sql .= " t.fk_user_author,"; + $sql .= " t.fk_user_valid,"; + $sql .= " t.fk_facture_source,"; + $sql .= " t.fk_projet as fk_project,"; + $sql .= " t.fk_cond_reglement,"; + $sql .= " t.fk_account,"; + $sql .= " t.fk_mode_reglement,"; + $sql .= " t.date_lim_reglement,"; + $sql .= " t.note_private,"; + $sql .= " t.note_public,"; + $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 .= ' s.nom as socnom, s.rowid as socid,'; + $sql .= ' t.fk_incoterms, t.location_incoterms,'; + $sql .= " i.libelle as label_incoterms,"; + $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t'; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; + $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)) - { - $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->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility + $this->id = $obj->rowid; + $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility - $this->ref_supplier = $obj->ref_supplier; - $this->entity = $obj->entity; - $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type; - $this->fk_soc = $obj->fk_soc; - $this->datec = $this->db->jdate($obj->datec); - $this->date = $this->db->jdate($obj->datef); - $this->datep = $this->db->jdate($obj->datef); - $this->tms = $this->db->jdate($obj->tms); - $this->libelle = $obj->label; // deprecated - $this->label = $obj->label; - $this->paye = $obj->paye; - $this->paid = $obj->paye; - $this->amount = $obj->amount; - $this->remise = $obj->remise; - $this->close_code = $obj->close_code; - $this->close_note = $obj->close_note; - $this->tva = $obj->tva; - $this->total_localtax1 = $obj->localtax1; - $this->total_localtax2 = $obj->localtax2; - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->total_tva; - $this->total_ttc = $obj->total_ttc; - $this->fk_statut = $obj->fk_statut; - $this->statut = $obj->fk_statut; - $this->fk_user_author = $obj->fk_user_author; - $this->author = $obj->fk_user_author; - $this->fk_user_valid = $obj->fk_user_valid; - $this->fk_facture_source = $obj->fk_facture_source; - $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->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->date_echeance = $this->db->jdate($obj->date_lim_reglement); - $this->note = $obj->note_private; // deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; - $this->import_key = $obj->import_key; + $this->ref_supplier = $obj->ref_supplier; + $this->entity = $obj->entity; + $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type; + $this->fk_soc = $obj->fk_soc; + $this->datec = $this->db->jdate($obj->datec); + $this->date = $this->db->jdate($obj->datef); + $this->datep = $this->db->jdate($obj->datef); + $this->tms = $this->db->jdate($obj->tms); + $this->libelle = $obj->label; // deprecated + $this->label = $obj->label; + $this->paye = $obj->paye; + $this->paid = $obj->paye; + $this->amount = $obj->amount; + $this->remise = $obj->remise; + $this->close_code = $obj->close_code; + $this->close_note = $obj->close_note; + $this->tva = $obj->tva; + $this->total_localtax1 = $obj->localtax1; + $this->total_localtax2 = $obj->localtax2; + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->total_tva; + $this->total_ttc = $obj->total_ttc; + $this->fk_statut = $obj->fk_statut; + $this->statut = $obj->fk_statut; + $this->fk_user_author = $obj->fk_user_author; + $this->author = $obj->fk_user_author; + $this->fk_user_valid = $obj->fk_user_valid; + $this->fk_facture_source = $obj->fk_facture_source; + $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->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->date_echeance = $this->db->jdate($obj->date_lim_reglement); + $this->note = $obj->note_private; // deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->model_pdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated + $this->import_key = $obj->import_key; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -726,112 +718,116 @@ class FactureFournisseur extends CommonInvoice $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); - $this->socid = $obj->socid; - $this->socnom = $obj->socnom; + $this->socid = $obj->socid; + $this->socnom = $obj->socnom; - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); + // Retreive all extrafield + // 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) - { - $this->error = $this->db->lasterror(); - return -3; - } - } else { - $this->error = 'Bill with id '.$id.' not found'; - dol_syslog(get_class($this).'::fetch '.$this->error); - return 0; - } + $result = $this->fetch_lines(); + if ($result < 0) + { + $this->error = $this->db->lasterror(); + return -3; + } + } else { + $this->error = 'Bill with id '.$id.' not found'; + dol_syslog(get_class($this).'::fetch '.$this->error); + return 0; + } - $this->db->free($resql); - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } + $this->db->free($resql); + return 1; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load this->lines - * - * @return int 1 si ok, < 0 si erreur - */ - public function fetch_lines() - { - // phpcs:enable - $this->lines = array(); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load this->lines + * + * @return int 1 si ok, < 0 si erreur + */ + public function fetch_lines() + { + // phpcs:enable + $this->lines = array(); - $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx'; - $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn '; - $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit'; - $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; - $sql .= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; - $sql .= ' WHERE fk_facture_fourn='.$this->id; - $sql .= ' ORDER BY f.rang, f.rowid'; + $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx'; + $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn '; + $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit'; + $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; + $sql .= ', fk_code_ventilation, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; + $sql .= ' WHERE fk_facture_fourn='.$this->id; + $sql .= ' ORDER BY f.rang, f.rowid'; - dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); - $resql_rows = $this->db->query($sql); - if ($resql_rows) - { - $num_rows = $this->db->num_rows($resql_rows); - if ($num_rows) - { - $i = 0; - while ($i < $num_rows) - { - $obj = $this->db->fetch_object($resql_rows); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); + $resql_rows = $this->db->query($sql); + if ($resql_rows) + { + $num_rows = $this->db->num_rows($resql_rows); + if ($num_rows) + { + $i = 0; + while ($i < $num_rows) + { + $obj = $this->db->fetch_object($resql_rows); - $line = new SupplierInvoiceLine($this->db); + $line = new SupplierInvoiceLine($this->db); - $line->id = $obj->rowid; - $line->rowid = $obj->rowid; - $line->description = $obj->description; - $line->date_start = $obj->date_start; - $line->date_end = $obj->date_end; + $line->id = $obj->rowid; + $line->rowid = $obj->rowid; + $line->description = $obj->description; + $line->date_start = $obj->date_start; + $line->date_end = $obj->date_end; - $line->product_ref = $obj->product_ref; - $line->ref = $obj->product_ref; - $line->ref_supplier = $obj->ref_supplier; - $line->libelle = $obj->label; - $line->label = $obj->label; - $line->product_desc = $obj->product_desc; - $line->subprice = $obj->pu_ht; - $line->pu_ht = $obj->pu_ht; - $line->pu_ttc = $obj->pu_ttc; + $line->product_ref = $obj->product_ref; + $line->ref = $obj->product_ref; + $line->ref_supplier = $obj->ref_supplier; + $line->libelle = $obj->label; + $line->label = $obj->label; + $line->product_desc = $obj->product_desc; + $line->subprice = $obj->pu_ht; + $line->pu_ht = $obj->pu_ht; + $line->pu_ttc = $obj->pu_ttc; - $line->vat_src_code = $obj->vat_src_code; - $line->tva_tx = $obj->tva_tx; - $line->localtax1_tx = $obj->localtax1_tx; - $line->localtax2_tx = $obj->localtax2_tx; - $line->localtax1_type = $obj->localtax1_type; - $line->localtax2_type = $obj->localtax2_type; - $line->qty = $obj->qty; - $line->remise_percent = $obj->remise_percent; - $line->tva = $obj->total_tva; // deprecated - $line->total_ht = $obj->total_ht; - $line->total_ttc = $obj->total_ttc; - $line->total_tva = $obj->total_tva; - $line->total_localtax1 = $obj->total_localtax1; - $line->total_localtax2 = $obj->total_localtax2; - $line->fk_facture_fourn = $obj->fk_facture_fourn; - $line->fk_product = $obj->fk_product; - $line->product_type = $obj->product_type; - $line->product_label = $obj->label; - $line->info_bits = $obj->info_bits; - $line->fk_parent_line = $obj->fk_parent_line; - $line->special_code = $obj->special_code; - $line->rang = $obj->rang; - $line->fk_unit = $obj->fk_unit; + $line->vat_src_code = $obj->vat_src_code; + $line->tva_tx = $obj->tva_tx; + $line->localtax1_tx = $obj->localtax1_tx; + $line->localtax2_tx = $obj->localtax2_tx; + $line->localtax1_type = $obj->localtax1_type; + $line->localtax2_type = $obj->localtax2_type; + $line->qty = $obj->qty; + $line->remise_percent = $obj->remise_percent; + $line->tva = $obj->total_tva; // deprecated + $line->total_ht = $obj->total_ht; + $line->total_ttc = $obj->total_ttc; + $line->total_tva = $obj->total_tva; + $line->total_localtax1 = $obj->total_localtax1; + $line->total_localtax2 = $obj->total_localtax2; + $line->fk_facture_fourn = $obj->fk_facture_fourn; + $line->fk_product = $obj->fk_product; + $line->product_type = $obj->product_type; + $line->product_label = $obj->label; + $line->info_bits = $obj->info_bits; + $line->fk_parent_line = $obj->fk_parent_line; + $line->special_code = $obj->special_code; + $line->rang = $obj->rang; + $line->fk_unit = $obj->fk_unit; + + // Accountancy + $line->code_ventilation = $obj->fk_code_ventilation; + $line->fk_accounting_account = $obj->fk_code_ventilation; // Multicurrency $line->fk_multicurrency = $obj->fk_multicurrency; @@ -841,121 +837,121 @@ class FactureFournisseur extends CommonInvoice $line->multicurrency_total_tva = $obj->multicurrency_total_tva; $line->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - // Extra fields + // Extra fields $line->fetch_optionals(); $this->lines[$i] = $line; - $i++; - } - } - $this->db->free($resql_rows); - return 1; - } else { - $this->error = $this->db->error(); - return -3; - } - } + $i++; + } + } + $this->db->free($resql_rows); + return 1; + } else { + $this->error = $this->db->error(); + return -3; + } + } - /** - * Update database - * - * @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 = null, $notrigger = 0) - { - global $conf, $langs; - $error = 0; + /** + * Update database + * + * @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 = null, $notrigger = 0) + { + global $conf, $langs; + $error = 0; - // Clean parameters - if (empty($this->type)) $this->type = self::TYPE_STANDARD; + // 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 (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->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); - // Check parameters - // Put here code to add control on parameters values + // Check parameters + // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn 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 .= " entity=".(isset($this->entity) ? $this->entity : "null").","; - $sql .= " type=".(isset($this->type) ? $this->type : "null").","; - $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').","; - $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").","; - $sql .= " remise=".(isset($this->remise) ? $this->remise : "null").","; - $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").","; - $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").","; - $sql .= " tva=".(isset($this->tva) ? $this->tva : "null").","; - $sql .= " localtax1=".(isset($this->localtax1) ? $this->localtax1 : "null").","; - $sql .= " localtax2=".(isset($this->localtax2) ? $this->localtax2 : "null").","; - $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; - $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "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->author) ? $this->author : "null").","; - $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").","; - $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "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 .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : '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=".$this->id; + $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").","; + $sql .= " entity=".(isset($this->entity) ? $this->entity : "null").","; + $sql .= " type=".(isset($this->type) ? $this->type : "null").","; + $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').","; + $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").","; + $sql .= " remise=".(isset($this->remise) ? $this->remise : "null").","; + $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").","; + $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").","; + $sql .= " tva=".(isset($this->tva) ? $this->tva : "null").","; + $sql .= " localtax1=".(isset($this->localtax1) ? $this->localtax1 : "null").","; + $sql .= " localtax2=".(isset($this->localtax2) ? $this->localtax2 : "null").","; + $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").","; + $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "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->author) ? $this->author : "null").","; + $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").","; + $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "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 .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : '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=".$this->id; - $this->db->begin(); + $this->db->begin(); - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); - if (!$resql) { - $error++; + if (!$resql) { + $error++; - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $this->errors[] = $langs->trans('ErrorRefAlreadyExists'); - } else { - $this->errors[] = "Error ".$this->db->lasterror(); - } - } + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $this->errors[] = $langs->trans('ErrorRefAlreadyExists'); + } else { + $this->errors[] = "Error ".$this->db->lasterror(); + } + } if (!$error) { @@ -966,162 +962,162 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { - if (!$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user); - if ($result < 0) $error++; - // End call triggers - } - } + if (!$error) + { + if (!$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $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; - } - } + // 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; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) - * - * @param int $idremise Id of absolute discount - * @return int >0 if OK, <0 if KO - */ - public function insert_discount($idremise) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) + * + * @param int $idremise Id of absolute discount + * @return int >0 if OK, <0 if KO + */ + public function insert_discount($idremise) + { + // phpcs:enable + global $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - $this->db->begin(); + $this->db->begin(); - $remise = new DiscountAbsolute($this->db); - $result = $remise->fetch($idremise); + $remise = new DiscountAbsolute($this->db); + $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_invoice_supplier) // Protection against multiple submission - { - $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); - $this->db->rollback(); - return -5; - } + if ($result > 0) + { + if ($remise->fk_invoice_supplier) // Protection against multiple submission + { + $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); + $this->db->rollback(); + return -5; + } - $facligne = new SupplierInvoiceLine($this->db); - $facligne->fk_facture_fourn = $this->id; - $facligne->fk_remise_except = $remise->id; - $facligne->desc = $remise->description; // Description ligne - $facligne->vat_src_code = $remise->vat_src_code; - $facligne->tva_tx = $remise->tva_tx; - $facligne->subprice = -$remise->amount_ht; - $facligne->fk_product = 0; // Id produit predefini - $facligne->product_type = 0; - $facligne->qty = 1; - $facligne->remise_percent = 0; - $facligne->rang = -1; - $facligne->info_bits = 2; + $facligne = new SupplierInvoiceLine($this->db); + $facligne->fk_facture_fourn = $this->id; + $facligne->fk_remise_except = $remise->id; + $facligne->desc = $remise->description; // Description ligne + $facligne->vat_src_code = $remise->vat_src_code; + $facligne->tva_tx = $remise->tva_tx; + $facligne->subprice = -$remise->amount_ht; + $facligne->fk_product = 0; // Id produit predefini + $facligne->product_type = 0; + $facligne->qty = 1; + $facligne->remise_percent = 0; + $facligne->rang = -1; + $facligne->info_bits = 2; - // Get buy/cost price of invoice that is source of discount - if ($remise->fk_invoice_supplier_source > 0) - { - $srcinvoice = new FactureFournisseur($this->db); - $srcinvoice->fetch($remise->fk_invoice_supplier_source); - $totalcostpriceofinvoice = 0; - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject - $formmargin = new FormMargin($this->db); - $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); - $facligne->pa_ht = $arraytmp['pa_total']; - } + // Get buy/cost price of invoice that is source of discount + if ($remise->fk_invoice_supplier_source > 0) + { + $srcinvoice = new FactureFournisseur($this->db); + $srcinvoice->fetch($remise->fk_invoice_supplier_source); + $totalcostpriceofinvoice = 0; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject + $formmargin = new FormMargin($this->db); + $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false); + $facligne->pa_ht = $arraytmp['pa_total']; + } - $facligne->total_ht = -$remise->amount_ht; - $facligne->total_tva = -$remise->amount_tva; - $facligne->total_ttc = -$remise->amount_ttc; + $facligne->total_ht = -$remise->amount_ht; + $facligne->total_tva = -$remise->amount_tva; + $facligne->total_ttc = -$remise->amount_ttc; - $facligne->multicurrency_subprice = -$remise->multicurrency_subprice; - $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht; - $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva; - $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; + $facligne->multicurrency_subprice = -$remise->multicurrency_subprice; + $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht; + $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva; + $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; - $lineid = $facligne->insert(); - if ($lineid > 0) - { - $result = $this->update_price(1); - if ($result > 0) - { - // Create link between discount and invoice line - $result = $remise->link_to_invoice($lineid, 0, 'supplier'); - if ($result < 0) - { - $this->error = $remise->error; - $this->db->rollback(); - return -4; - } + $lineid = $facligne->insert(); + if ($lineid > 0) + { + $result = $this->update_price(1); + if ($result > 0) + { + // Create link between discount and invoice line + $result = $remise->link_to_invoice($lineid, 0, 'supplier'); + if ($result < 0) + { + $this->error = $remise->error; + $this->db->rollback(); + return -4; + } - $this->db->commit(); - return 1; - } else { - $this->error = $facligne->error; - $this->db->rollback(); - return -1; - } - } else { - $this->error = $facligne->error; - $this->db->rollback(); - return -2; - } - } else { - $this->db->rollback(); - return -3; - } - } + $this->db->commit(); + return 1; + } else { + $this->error = $facligne->error; + $this->db->rollback(); + return -1; + } + } else { + $this->error = $facligne->error; + $this->db->rollback(); + return -2; + } + } else { + $this->db->rollback(); + return -3; + } + } - /** - * Delete invoice from database - * - * @param User $user User object - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function delete(User $user, $notrigger = 0) - { - global $langs, $conf; + /** + * Delete invoice from database + * + * @param User $user User object + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0) + { + global $langs, $conf; - $rowid = $this->id; + $rowid = $this->id; - dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG); + dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG); - // TODO Test if there is at least on payment. If yes, refuse to delete. + // TODO Test if there is at least on payment. If yes, refuse to delete. - $error = 0; - $this->db->begin(); + $error = 0; + $this->db->begin(); - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // Fin appel triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // Fin appel triggers + } if (!$error) { // If invoice was converted into a discount not yet consumed, we remove discount @@ -1150,27 +1146,27 @@ class FactureFournisseur extends CommonInvoice } } - 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)"; - $resqlef = $this->db->query($sqlef); - $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) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql2 = $this->db->query($sql); - if (!$resql2) { - $error++; - } - } else { - $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)"; + $resqlef = $this->db->query($sqlef); + $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) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql2 = $this->db->query($sql); + if (!$resql2) { + $error++; + } + } else { + $error++; + } + } if (!$error) { @@ -1179,437 +1175,441 @@ class FactureFournisseur extends CommonInvoice if ($res < 0) $error++; } - if (!$error) - { - // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; - } + if (!$error) + { + // Delete linked object + $res = $this->deleteObjectLinked(); + if ($res < 0) $error++; + } - if (!$error) - { - // We remove directory - if ($conf->fournisseur->facture->dir_output) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if (!$error) + { + // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive + $this->deleteEcmFiles(); - $ref = dol_sanitizeFileName($this->ref); - $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref; - $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { - $this->error = 'ErrorFailToDeleteFile'; - $error++; - } - } - if (file_exists($dir)) - { - $res = @dol_delete_dir_recursive($dir); + // We remove directory + if ($conf->fournisseur->facture->dir_output) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (!$res) - { - $this->error = 'ErrorFailToDeleteDir'; - $error++; - } - } - } - } + $ref = dol_sanitizeFileName($this->ref); + $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref; + $file = $dir."/".$ref.".pdf"; + if (file_exists($file)) + { + if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers + { + $this->error = 'ErrorFailToDeleteFile'; + $error++; + } + } + if (file_exists($dir)) + { + $res = @dol_delete_dir_recursive($dir); - // Remove extrafields - if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + if (!$res) + { + $this->error = 'ErrorFailToDeleteDir'; + $error++; + } + } + } + } - if (!$error) - { - dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->lasterror(); - $this->db->rollback(); - return -$error; - } - } + // Remove extrafields + if (!$error) + { + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } + + if (!$error) + { + dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return -$error; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Tag invoice as a payed invoice - * - * @param User $user Object user - * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet. - * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet. - * @return int <0 si ko, >0 si ok - */ - public function set_paid($user, $close_code = '', $close_note = '') - { - // phpcs:enable - global $conf, $langs; - $error = 0; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Tag invoice as a payed invoice + * + * @param User $user Object user + * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet. + * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet. + * @return int <0 si ko, >0 si ok + */ + public function set_paid($user, $close_code = '', $close_note = '') + { + // phpcs:enable + global $conf, $langs; + $error = 0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; - $sql .= ' SET paye = 1, fk_statut = '.self::STATUS_CLOSED; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; + $sql .= ' SET paye = 1, fk_statut = '.self::STATUS_CLOSED; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user); - if ($result < 0) $error++; - // End call triggers - } else { - $error++; - $this->error = $this->db->error(); - dol_print_error($this->db); - } + dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user); + if ($result < 0) $error++; + // End call triggers + } else { + $error++; + $this->error = $this->db->error(); + dol_print_error($this->db); + } - 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; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED - * Fonction utilisee quand un paiement prelevement est refuse, - * ou quand une facture annulee et reouverte. - * - * @param User $user Object user that change status - * @return int <0 si ok, >0 si ok - */ - public function set_unpaid($user) - { - // phpcs:enable - global $conf, $langs; - $error = 0; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED + * Fonction utilisee quand un paiement prelevement est refuse, + * ou quand une facture annulee et reouverte. + * + * @param User $user Object user that change status + * @return int <0 si ok, >0 si ok + */ + public function set_unpaid($user) + { + // phpcs:enable + global $conf, $langs; + $error = 0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; - $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; - $sql .= ' WHERE rowid = '.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn'; + $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; + $sql .= ' WHERE rowid = '.$this->id; - dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); - if ($result < 0) $error++; - // End call triggers - } else { - $error++; - $this->error = $this->db->lasterror(); - dol_syslog("FactureFournisseur::set_unpaid ".$this->error); - } + dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); + if ($result < 0) $error++; + // End call triggers + } else { + $error++; + $this->error = $this->db->lasterror(); + dol_syslog("FactureFournisseur::set_unpaid ".$this->error); + } - 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 invoice as validated + call trigger BILL_VALIDATE - * - * @param User $user Object user that validate - * @param string $force_number Reference to force on invoice - * @param int $idwarehouse Id of warehouse for stock change - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, =0 if nothing to do, >0 if OK - */ - public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0) - { - global $conf, $langs; + /** + * Tag invoice as validated + call trigger BILL_VALIDATE + * + * @param User $user Object user that validate + * @param string $force_number Reference to force on invoice + * @param int $idwarehouse Id of warehouse for stock change + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, =0 if nothing to do, >0 if OK + */ + public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0) + { + global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $now = dol_now(); + $now = dol_now(); - $error = 0; - dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse); + $error = 0; + dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse); - // Force to have object complete for checks - $this->fetch_thirdparty(); - $this->fetch_lines(); + // Force to have object complete for checks + $this->fetch_thirdparty(); + $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) - { - dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); - return 0; - } - 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) - { - $langs->load("errors"); - $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); - return -1; - } + // Check parameters + 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)) + { + $langs->load("errors"); + $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf")); + return -1; + } + if (count($this->lines) <= 0) + { + $langs->load("errors"); + $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); + return -1; + } - $this->db->begin(); + $this->db->begin(); - // Define new ref - 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 - { - $num = $this->getNextNumRef($this->thirdparty); - } else { - $num = $this->ref; - } - $this->newref = dol_sanitizeFileName($num); + // Define new ref + 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 + { + $num = $this->getNextNumRef($this->thirdparty); + } else { + $num = $this->ref; + } + $this->newref = dol_sanitizeFileName($num); - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; - $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::validate", LOG_DEBUG); - $resql = $this->db->query($sql); - 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)) - { - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; - $langs->load("agenda"); + dol_syslog(get_class($this)."::validate", LOG_DEBUG); + $resql = $this->db->query($sql); + 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)) + { + 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) - { - $this->line = $this->lines[$i]; - $mouvP = new MouvementStock($this->db); + $cpt = count($this->lines); + 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++; } - unset($this->line); - } - } - } + // 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++; } + unset($this->line); + } + } + } - // Triggers call - if (!$error && empty($notrigger)) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); - if ($result < 0) $error++; - // End call triggers - } + // Triggers call + if (!$error && empty($notrigger)) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers + } - if (!$error) - { - $this->oldref = $this->ref; + if (!$error) + { + $this->oldref = $this->ref; - // Rename directory if dir was a temporary 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(); } + // Rename directory if dir was a temporary 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(); } - // 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)) - { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + // 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)) + { + dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$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) - { - $dirsource = $fileentry['name']; - $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); - $dirsource = $fileentry['path'].'/'.$dirsource; - $dirdest = $fileentry['path'].'/'.$dirdest; - @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) + { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } - // Set new ref and define current statut - if (!$error) - { - $this->ref = $num; - $this->statut = self::STATUS_VALIDATED; - //$this->date_validation=$now; this is stored into log table - } + // Set new ref and define current statut + if (!$error) + { + $this->ref = $num; + $this->statut = self::STATUS_VALIDATED; + //$this->date_validation=$now; this is stored into log table + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + if (!$error) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Set draft status - * - * @param User $user Object user that modify - * @param int $idwarehouse Id warehouse to use for stock change. - * @return int <0 if KO, >0 if OK - */ - public function setDraft($user, $idwarehouse = -1) - { - // phpcs:enable - global $conf, $langs; + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $idwarehouse Id warehouse to use for stock change. + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user, $idwarehouse = -1) + { + // phpcs:enable + global $conf, $langs; - $error = 0; + $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { - dol_syslog(__METHOD__." already draft status", LOG_WARNING); - return 0; - } + if ($this->statut == self::STATUS_DRAFT) + { + dol_syslog(__METHOD__." already draft status", LOG_WARNING); + return 0; + } - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; - $sql .= " SET fk_statut = ".self::STATUS_DRAFT; - $sql .= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result) - { - if (!$error) - { - $this->oldcopy = clone $this; - } + $result = $this->db->query($sql); + 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)) - { - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; - $langs->load("agenda"); + // 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)) + { + 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) - { - $mouvP = new MouvementStock($this->db); - $mouvP->origin = &$this; + $cpt = count($this->lines); + 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)); - } - } - } - // Triggers call - if (!$error && empty($notrigger)) - { - // Call trigger - $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); - if ($result < 0) $error++; - // End call triggers - } - if ($error == 0) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + 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)) + { + // Call trigger + $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); + if ($result < 0) $error++; + // End call triggers + } + if ($error == 0) + { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Ajoute une ligne de facture (associe a aucun produit/service predefini) - * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel - * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini - * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod) - * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue). - * - * @param string $desc Description de la ligne - * @param double $pu Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note) - * @param double $txtva Force Vat rate to use, -1 for auto. - * @param double $txlocaltax1 LocalTax1 Rate - * @param double $txlocaltax2 LocalTax2 Rate - * @param double $qty Quantite - * @param int $fk_product Product/Service ID predefined - * @param double $remise_percent Percentage discount of the line - * @param integer $date_start Date de debut de validite du service - * @param integer $date_end Date de fin de validite du service - * @param string $ventil Code de ventilation comptable - * @param int $info_bits Bits de type de lines - * @param string $price_base_type HT ou TTC - * @param int $type Type of line (0=product, 1=service) - * @param int $rang Position of line - * @param int $notrigger Disable triggers + /** + * Ajoute une ligne de facture (associe a aucun produit/service predefini) + * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel + * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini + * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod) + * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue). + * + * @param string $desc Description de la ligne + * @param double $pu Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note) + * @param double $txtva Force Vat rate to use, -1 for auto. + * @param double $txlocaltax1 LocalTax1 Rate + * @param double $txlocaltax2 LocalTax2 Rate + * @param double $qty Quantite + * @param int $fk_product Product/Service ID predefined + * @param double $remise_percent Percentage discount of the line + * @param integer $date_start Date de debut de validite du service + * @param integer $date_end Date de fin de validite du service + * @param string $ventil Code de ventilation comptable + * @param int $info_bits Bits de type de lines + * @param string $price_base_type HT ou TTC + * @param int $type Type of line (0=product, 1=service) + * @param int $rang Position of line + * @param int $notrigger Disable triggers * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param int $origin_id id origin document + * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param int $origin_id id origin document * @param double $pu_ht_devise Amount in currency * @param string $ref_supplier Supplier ref * @param string $special_code Special code - * @return int >0 if OK, <0 if KO - */ - public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_ht_devise = 0, $ref_supplier = '', $special_code = '') - { - global $langs, $mysoc, $conf; + * @param int $fk_parent_line Parent line id + * @return int >0 if OK, <0 if KO + */ + public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_ht_devise = 0, $ref_supplier = '', $special_code = '', $fk_parent_line = 0) + { + global $langs, $mysoc, $conf; - 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'; + 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) { @@ -1638,93 +1638,93 @@ class FactureFournisseur extends CommonInvoice return -1; } - $this->db->begin(); + $this->db->begin(); - 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) - { - $product_type = $prod->type; - $label = $prod->label; - $fk_prod_fourn_price = 0; + 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) + { + $product_type = $prod->type; + $label = $prod->label; + $fk_prod_fourn_price = 0; - // 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 - $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 ($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(); - dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); - //$pu = $prod->fourn_pu; // We do not overwrite unit price - //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price - return -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) - { - $this->error = $prod->error; - $this->db->rollback(); - dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); - return -1; - } - } else { - $this->error = $prod->error; - $this->db->rollback(); - return -1; - } - } - } else { - $product_type = $type; - } + // 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 + $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 ($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(); + dol_syslog(get_class($this)."::addline we did not found supplier price, so we can't guess unit price"); + //$pu = $prod->fourn_pu; // We do not overwrite unit price + //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price + return -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) + { + $this->error = $prod->error; + $this->db->rollback(); + dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); + return -1; + } + } else { + $this->error = $prod->error; + $this->db->rollback(); + return -1; + } + } + } else { + $product_type = $type; + } - if ($conf->multicurrency->enabled && $pu_ht_devise > 0) { - $pu = 0; - } + if ($conf->multicurrency->enabled && $pu_ht_devise > 0) { + $pu = 0; + } - $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $mysoc, $this->thirdparty); - // Clean vat code - $reg = array(); - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $reg = array(); + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; // MultiCurrency @@ -1778,7 +1778,7 @@ class FactureFournisseur extends CommonInvoice $this->line->info_bits = $info_bits; $this->line->special_code = ((string) $special_code != '' ? $special_code : $this->special_code); - $this->line->fk_parent_line = $this->fk_parent_line; + $this->line->fk_parent_line = $fk_parent_line; $this->line->origin = $this->origin; $this->line->origin_id = $origin_id; $this->line->fk_unit = $fk_unit; @@ -1818,184 +1818,184 @@ class FactureFournisseur extends CommonInvoice $this->db->rollback(); return -2; } - } else { - return 0; - } - } + } else { + return 0; + } + } - /** - * Update a line detail into database - * - * @param int $id Id of line invoice - * @param string $desc Description of line - * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) - * @param double $vatrate VAT Rate (Can be '8.5', '8.5 (ABC)') - * @param double $txlocaltax1 LocalTax1 Rate - * @param double $txlocaltax2 LocalTax2 Rate - * @param double $qty Quantity - * @param int $idproduct Id produit - * @param double $price_base_type HT or TTC - * @param int $info_bits Miscellaneous informations of line - * @param int $type Type of line (0=product, 1=service) - * @param double $remise_percent Percentage discount of the line - * @param int $notrigger Disable triggers - * @param integer $date_start Date start of service - * @param integer $date_end Date end of service + /** + * Update a line detail into database + * + * @param int $id Id of line invoice + * @param string $desc Description of line + * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) + * @param double $vatrate VAT Rate (Can be '8.5', '8.5 (ABC)') + * @param double $txlocaltax1 LocalTax1 Rate + * @param double $txlocaltax2 LocalTax2 Rate + * @param double $qty Quantity + * @param int $idproduct Id produit + * @param double $price_base_type HT or TTC + * @param int $info_bits Miscellaneous informations of line + * @param int $type Type of line (0=product, 1=service) + * @param double $remise_percent Percentage discount of the line + * @param int $notrigger Disable triggers + * @param integer $date_start Date start of service + * @param integer $date_end Date end of service * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Amount in currency * @param string $ref_supplier Supplier ref - * @return int <0 if KO, >0 if OK - */ - public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1 = 0, $txlocaltax2 = 0, $qty = 1, $idproduct = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $remise_percent = 0, $notrigger = false, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $ref_supplier = '') - { - global $mysoc, $langs; - dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$notrigger,$date_start,$date_end,$fk_unit,$pu_ht_devise,$ref_supplier", LOG_DEBUG); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + * @return int <0 if KO, >0 if OK + */ + public function updateline($id, $desc, $pu, $vatrate, $txlocaltax1 = 0, $txlocaltax2 = 0, $qty = 1, $idproduct = 0, $price_base_type = 'HT', $info_bits = 0, $type = 0, $remise_percent = 0, $notrigger = false, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $ref_supplier = '') + { + global $mysoc, $langs; + dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent,$notrigger,$date_start,$date_end,$fk_unit,$pu_ht_devise,$ref_supplier", LOG_DEBUG); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - $pu = price2num($pu); - $qty = price2num($qty); + $pu = price2num($pu); + $qty = price2num($qty); $remise_percent = price2num($remise_percent); $pu_ht_devise = price2num($pu_ht_devise); - // Check parameters - //if (! is_numeric($pu) || ! is_numeric($qty)) return -1; - if ($type < 0) return -1; + // Check parameters + //if (! is_numeric($pu) || ! is_numeric($qty)) return -1; + if ($type < 0) return -1; - if ($date_start && $date_end && $date_start > $date_end) { - $langs->load("errors"); - $this->error = $langs->trans('ErrorStartDateGreaterEnd'); - return -1; - } + if ($date_start && $date_end && $date_start > $date_end) { + $langs->load("errors"); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); + return -1; + } - // Clean parameters + // Clean parameters if (empty($vatrate)) $vatrate = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($txlocaltax1)) $txlocaltax1 = 0; + if (empty($txlocaltax2)) $txlocaltax2 = 0; - $txlocaltax1 = price2num($txlocaltax1); - $txlocaltax2 = price2num($txlocaltax2); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); - $localtaxes_type = array($txlocaltax1, $txlocaltax2); + $localtaxes_type = array($txlocaltax1, $txlocaltax2); - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty); + $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $mysoc, $this->thirdparty); - $reg = array(); + $reg = array(); - // Clean vat code - $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { - $vat_src_code = $reg[1]; - $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code = ''; + if (preg_match('/\((.*)\)/', $vatrate, $reg)) + { + $vat_src_code = $reg[1]; + $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. + } - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $pu_ht = $tabprice[3]; - $pu_tva = $tabprice[4]; - $pu_ttc = $tabprice[5]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $pu_ht = $tabprice[3]; + $pu_tva = $tabprice[4]; + $pu_ttc = $tabprice[5]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $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) - { - $product = new Product($this->db); - $result = $product->fetch($idproduct); - $product_type = $product->type; - } else { - $product_type = $type; - } + if ($idproduct) + { + $product = new Product($this->db); + $result = $product->fetch($idproduct); + $product_type = $product->type; + } else { + $product_type = $type; + } - //Fetch current line from the database and then clone the object and set it in $oldline property - $line = new SupplierInvoiceLine($this->db); - $line->fetch($id); - $line->fetch_optionals(); + //Fetch current line from the database and then clone the object and set it in $oldline property + $line = new SupplierInvoiceLine($this->db); + $line->fetch($id); + $line->fetch_optionals(); - $staticline = clone $line; + $staticline = clone $line; - $line->oldline = $staticline; - $line->context = $this->context; + $line->oldline = $staticline; + $line->context = $this->context; - $line->description = $desc; - $line->subprice = $pu_ht; - $line->pu_ht = $pu_ht; - $line->pu_ttc = $pu_ttc; - $line->qty = $qty; - $line->remise_percent = $remise_percent; - $line->ref_supplier = $ref_supplier; + $line->description = $desc; + $line->subprice = $pu_ht; + $line->pu_ht = $pu_ht; + $line->pu_ttc = $pu_ttc; + $line->qty = $qty; + $line->remise_percent = $remise_percent; + $line->ref_supplier = $ref_supplier; - $line->date_start = $date_start; - $line->date_end = $date_end; + $line->date_start = $date_start; + $line->date_end = $date_end; - $line->vat_src_code = $vat_src_code; - $line->tva_tx = $vatrate; - $line->localtax1_tx = $txlocaltax1; - $line->localtax2_tx = $txlocaltax2; + $line->vat_src_code = $vat_src_code; + $line->tva_tx = $vatrate; + $line->localtax1_tx = $txlocaltax1; + $line->localtax2_tx = $txlocaltax2; $line->localtax1_type = $localtaxes_type[0]; $line->localtax2_type = $localtaxes_type[2]; $line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); $line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva); - $line->total_localtax1 = $total_localtax1; - $line->total_localtax2 = $total_localtax2; - $line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); - $line->fk_product = $idproduct; - $line->product_type = $product_type; - $line->info_bits = $info_bits; - $line->fk_unit = $fk_unit; + $line->total_localtax1 = $total_localtax1; + $line->total_localtax2 = $total_localtax2; + $line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); + $line->fk_product = $idproduct; + $line->product_type = $product_type; + $line->info_bits = $info_bits; + $line->fk_unit = $fk_unit; - if (is_array($array_options) && count($array_options) > 0) { - // We replace values in this->line->array_options only for entries defined into $array_options - foreach ($array_options as $key => $value) { - $line->array_options[$key] = $array_options[$key]; - } - } + if (is_array($array_options) && count($array_options) > 0) { + // We replace values in this->line->array_options only for entries defined into $array_options + foreach ($array_options as $key => $value) { + $line->array_options[$key] = $array_options[$key]; + } + } - // Multicurrency + // Multicurrency $line->multicurrency_subprice = $pu_ht_devise; $line->multicurrency_total_ht = $multicurrency_total_ht; - $line->multicurrency_total_tva = $multicurrency_total_tva; - $line->multicurrency_total_ttc = $multicurrency_total_ttc; + $line->multicurrency_total_tva = $multicurrency_total_tva; + $line->multicurrency_total_ttc = $multicurrency_total_ttc; - $res = $line->update($notrigger); + $res = $line->update($notrigger); - if ($res < 1) { - $this->errors[] = $line->error; - } else { - // Update total price into invoice record - $res = $this->update_price('', 'auto', 0, $this->thirdparty); - } + if ($res < 1) { + $this->errors[] = $line->error; + } else { + // Update total price into invoice record + $res = $this->update_price('', 'auto', 0, $this->thirdparty); + } - return $res; - } + return $res; + } - /** - * Delete a detail line from database - * - * @param int $rowid Id of line to delete - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - public function deleteline($rowid, $notrigger = 0) - { - if (!$rowid) { - $rowid = $this->id; - } + /** + * Delete a detail line from database + * + * @param int $rowid Id of line to delete + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + public function deleteline($rowid, $notrigger = 0) + { + if (!$rowid) { + $rowid = $this->id; + } $this->db->begin(); @@ -2013,19 +2013,19 @@ class FactureFournisseur extends CommonInvoice return -2; } - $line = new SupplierInvoiceLine($this->db); + $line = new SupplierInvoiceLine($this->db); - if ($line->fetch($rowid) < 1) { - return -1; - } + if ($line->fetch($rowid) < 1) { + return -1; + } - $res = $line->delete($notrigger); + $res = $line->delete($notrigger); - if ($res < 1) { + if ($res < 1) { $this->errors[] = $line->error; $this->db->rollback(); return -3; - } else { + } else { $res = $this->update_price(); if ($res > 0) @@ -2037,70 +2037,70 @@ class FactureFournisseur extends CommonInvoice $this->error = $this->db->lasterror(); return -4; } - } - } + } + } - /** - * Charge les informations d'ordre info dans l'objet facture - * - * @param int $id Id de la facture a charger - * @return void - */ - public function info($id) - { - $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; + /** + * Charge les informations d'ordre info dans l'objet facture + * + * @param int $id Id de la facture a charger + * @return void + */ + public function info($id) + { + $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; - $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; - } - 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) - { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_modif); - $this->user_modification = $muser; - } - $this->date_creation = $this->db->idate($obj->datec); - $this->date_modification = $this->db->idate($obj->datem); - //$this->date_validation = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders) - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } + $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; + } + 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) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } + $this->date_creation = $this->db->idate($obj->datec); + $this->date_modification = $this->db->idate($obj->datem); + //$this->date_validation = $obj->datev; // This field is not available. Should be store into log table and using this function should be replaced with showing content of log (like for supplier orders) + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** * Renvoi liste des factures remplacables * Statut validee ou abandonnee pour raison autre + non payee + aucun paiement + pas deja remplacee * * @param int $socid Id societe * @return array|int Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) - * <0 if error - */ - public function list_replacable_supplier_invoices($socid = 0) + * <0 if error + */ + public function list_replacable_supplier_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -2125,10 +2125,10 @@ class FactureFournisseur extends CommonInvoice while ($obj = $this->db->fetch_object($resql)) { $return[$obj->rowid] = array( - 'id' => $obj->rowid, - 'ref' => $obj->ref, - 'status' => $obj->fk_statut - ); + 'id' => $obj->rowid, + 'ref' => $obj->ref, + 'status' => $obj->fk_statut + ); } //print_r($return); return $return; @@ -2138,7 +2138,7 @@ class FactureFournisseur extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Renvoi liste des factures qualifiables pour correction par avoir * Les factures qui respectent les regles suivantes sont retournees: @@ -2146,11 +2146,11 @@ class FactureFournisseur extends CommonInvoice * * @param int $socid Id societe * @return array|int Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) - * <0 if error + * <0 if error */ - public function list_qualified_avoir_supplier_invoices($socid = 0) + public function list_qualified_avoir_supplier_invoices($socid = 0) { - // phpcs:enable + // phpcs:enable global $conf; $return = array(); @@ -2160,8 +2160,8 @@ class FactureFournisseur extends CommonInvoice $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_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; - $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 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; $sql .= " ORDER BY f.ref"; @@ -2189,334 +2189,334 @@ class FactureFournisseur extends CommonInvoice } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Object user - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - public function load_board($user) - { - // phpcs:enable - global $conf, $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Object user + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + public function load_board($user) + { + // phpcs:enable + global $conf, $langs; - $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"; - $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; + $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"; + $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; - $resql = $this->db->query($sql); - if ($resql) - { - $langs->load("bills"); - $now = dol_now(); - - $response = new WorkboardResponse(); - $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24; - $response->label = $langs->trans("SupplierBillsToPay"); - $response->labelShort = $langs->trans("StatusToPay"); - - $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills'; - $response->img = img_object($langs->trans("Bills"), "bill"); - - $facturestatic = new FactureFournisseur($this->db); - - while ($obj = $this->db->fetch_object($resql)) - { - $response->nbtodo++; - - $facturestatic->date_echeance = $this->db->jdate($obj->datefin); - $facturestatic->statut = $obj->fk_statut; - - if ($facturestatic->hasDelay()) { - $response->nbtodolate++; - $response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?option=late&mainmenu=billing&leftmenu=suppliers_bills'; - } - } - $this->db->free($resql); - return $response; - } else { - dol_print_error($this->db); - $this->error = $this->db->error(); - return -1; - } - } - - - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option Where point the link - * @param int $max Max length of shown ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param int $addlinktonotes Add link to show notes - * @return string String with URL - */ - public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) - { - global $langs, $conf, $user; - - $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 ($short) return $url; - - 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'; - } - - $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 - - $label = ''.$langs->trans("SupplierInvoice").''; - if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").''; - elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; - elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; - if (!empty($this->ref)) - $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_supplier)) - $label .= '
    '.$langs->trans('RefSupplier').': '.$this->ref_supplier; - if (!empty($this->label)) - $label .= '
    '.$langs->trans('Label').': '.$this->label; - if (!empty($this->date)) - $label .= '
    '.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); - 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)) - $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - 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 (isset($this->statut) && isset($this->alreadypaid)) { - $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); - } - - $ref = $this->ref; - if (empty($ref)) $ref = $this->id; - - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowSupplierInvoice"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; - } - - $linkstart = ''; - $linkend = ''; - - $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); - $result .= $linkend; - - if ($addlinktonotes) - { - $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { - $notetoshow = $langs->trans("ViewPrivateNote").':
    '.dol_string_nohtmltag($txttoshow, 1); - $result .= ' '; - $result .= ''; - $result .= img_picto('', 'note'); - $result .= ''; - //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); - //$result.=''; - $result .= ''; - } - } - - return $result; - } - - /** - * Return next reference of supplier invoice not already used (or last reference) - * according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER - * - * @param Societe $soc Thirdparty object - * @param string $mode 'next' for next value or 'last' for last value - * @return string free ref or last ref - */ - public function getNextNumRef($soc, $mode = 'next') - { - global $db, $langs, $conf; - $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'; - - $mybool = false; - - $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php"; - $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER; - - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_invoice/"); - - // Load file with numbering class (if found) - $mybool |= @include_once $dir.$file; - } - - if ($mybool === false) { - dol_print_error('', "Failed to include file ".$file); - return ''; - } - - $obj = new $classname(); - $numref = ""; - $numref = $obj->getNumRef($soc, $this, $mode); - - if ($numref != "") - { - return $numref; - } else { - $this->error = $obj->error; - //dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error); - return false; - } - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines - * @return void - */ - public function initAsSpecimen($option = '') - { - global $langs, $conf; - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - - $now = dol_now(); - - // Load array of products prodids - $num_prods = 0; - $prodids = array(); - - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."product"; - $sql .= " WHERE entity IN (".getEntity('product').")"; - - $resql = $this->db->query($sql); - if ($resql) - { - $num_prods = $this->db->num_rows($resql); - $i = 0; - while ($i < $num_prods) - { - $i++; - $row = $this->db->fetch_row($resql); - $prodids[$i] = $row[0]; - } - } - - // Initialise parametres - $this->id = 0; - $this->ref = 'SPECIMEN'; - $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN'; - $this->specimen = 1; - $this->socid = 1; - $this->date = $now; - $this->date_lim_reglement = $this->date + 3600 * 24 * 30; - $this->cond_reglement_code = 'RECEP'; - $this->mode_reglement_code = 'CHQ'; - - $this->note_public = 'This is a comment (public)'; - $this->note_private = 'This is a comment (private)'; - - $this->multicurrency_tx = 1; - $this->multicurrency_code = $conf->currency; - - if (empty($option) || $option != 'nolines') + $resql = $this->db->query($sql); + if ($resql) { - // Lines - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) - { - $line = new FactureLigne($this->db); - $line->desc = $langs->trans("Description")." ".$xnbp; - $line->qty = 1; - $line->subprice = 100; - $line->pu_ht = 100; // the canelle template use pu_ht and not subprice - $line->price = 100; - $line->tva_tx = 19.6; - $line->localtax1_tx = 0; - $line->localtax2_tx = 0; - if ($xnbp == 2) - { - $line->total_ht = 50; - $line->total_ttc = 59.8; - $line->total_tva = 9.8; - $line->remise_percent = 50; - } else { - $line->total_ht = 100; - $line->total_ttc = 119.6; - $line->total_tva = 19.6; - $line->remise_percent = 0; + $langs->load("bills"); + $now = dol_now(); + + $response = new WorkboardResponse(); + $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24; + $response->label = $langs->trans("SupplierBillsToPay"); + $response->labelShort = $langs->trans("StatusToPay"); + + $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills'; + $response->img = img_object($langs->trans("Bills"), "bill"); + + $facturestatic = new FactureFournisseur($this->db); + + while ($obj = $this->db->fetch_object($resql)) + { + $response->nbtodo++; + + $facturestatic->date_echeance = $this->db->jdate($obj->datefin); + $facturestatic->statut = $obj->fk_statut; + + if ($facturestatic->hasDelay()) { + $response->nbtodolate++; + $response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?option=late&mainmenu=billing&leftmenu=suppliers_bills'; } + } + $this->db->free($resql); + return $response; + } else { + dol_print_error($this->db); + $this->error = $this->db->error(); + return -1; + } + } - if ($num_prods > 0) - { - $prodid = mt_rand(1, $num_prods); - $line->fk_product = $prodids[$prodid]; - } - $line->product_type = 0; - $this->lines[$xnbp] = $line; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option Where point the link + * @param int $max Max length of shown ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @param int $addlinktonotes Add link to show notes + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) + { + global $langs, $conf, $user; - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; + $result = ''; - $xnbp++; - } + 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 ($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'; } - $this->amount_ht = $xnbp * 100; - $this->total_ht = $xnbp * 100; - $this->total_tva = $xnbp * 19.6; - $this->total_ttc = $xnbp * 119.6; - } + $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 - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + $label = img_picto('', $this->picto).' '.$langs->trans("SupplierInvoice").''; + if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").''; + elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; + elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; + if (!empty($this->ref)) + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_supplier)) + $label .= '
    '.$langs->trans('RefSupplier').': '.$this->ref_supplier; + if (!empty($this->label)) + $label .= '
    '.$langs->trans('Label').': '.$this->label; + if (!empty($this->date)) + $label .= '
    '.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); + 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)) + $label .= '
    '.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + 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 (isset($this->statut) && isset($this->alreadypaid)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); + } + + $ref = $this->ref; + if (empty($ref)) $ref = $this->id; + + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowSupplierInvoice"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend = ''; + + $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); + $result .= $linkend; + + if ($addlinktonotes) + { + $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); + if ($txttoshow) + { + $notetoshow = $langs->trans("ViewPrivateNote").':
    '.dol_string_nohtmltag($txttoshow, 1); + $result .= ' '; + $result .= ''; + $result .= img_picto('', 'note'); + $result .= ''; + //$result.=img_picto($langs->trans("ViewNote"),'object_generic'); + //$result.=''; + $result .= ''; + } + } + + return $result; + } + + /** + * Return next reference of supplier invoice not already used (or last reference) + * according to numbering module defined into constant INVOICE_SUPPLIER_ADDON_NUMBER + * + * @param Societe $soc Thirdparty object + * @param string $mode 'next' for next value or 'last' for last value + * @return string free ref or last ref + */ + public function getNextNumRef($soc, $mode = 'next') + { + global $db, $langs, $conf; + $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'; + + $mybool = false; + + $file = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER.".php"; + $classname = $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/supplier_invoice/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + $obj = new $classname(); + $numref = ""; + $numref = $obj->getNumRef($soc, $this, $mode); + + if ($numref != "") + { + return $numref; + } else { + $this->error = $obj->error; + return false; + } + } + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines + * @return void + */ + public function initAsSpecimen($option = '') + { + global $langs, $conf; + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + + $now = dol_now(); + + // Load array of products prodids + $num_prods = 0; + $prodids = array(); + + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; + $sql .= $this->db->plimit(100); + + $resql = $this->db->query($sql); + if ($resql) + { + $num_prods = $this->db->num_rows($resql); + $i = 0; + while ($i < $num_prods) + { + $i++; + $row = $this->db->fetch_row($resql); + $prodids[$i] = $row[0]; + } + } + + // Initialise parametres + $this->id = 0; + $this->ref = 'SPECIMEN'; + $this->ref_supplier = 'SUPPLIER_REF_SPECIMEN'; + $this->specimen = 1; + $this->socid = 1; + $this->date = $now; + $this->date_lim_reglement = $this->date + 3600 * 24 * 30; + $this->cond_reglement_code = 'RECEP'; + $this->mode_reglement_code = 'CHQ'; + + $this->note_public = 'This is a comment (public)'; + $this->note_private = 'This is a comment (private)'; + + $this->multicurrency_tx = 1; + $this->multicurrency_code = $conf->currency; + + if (empty($option) || $option != 'nolines') + { + // Lines + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) + { + $line = new FactureLigne($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 100; + $line->pu_ht = 100; // the canelle template use pu_ht and not subprice + $line->price = 100; + $line->tva_tx = 19.6; + $line->localtax1_tx = 0; + $line->localtax2_tx = 0; + if ($xnbp == 2) + { + $line->total_ht = 50; + $line->total_ttc = 59.8; + $line->total_tva = 9.8; + $line->remise_percent = 50; + } else { + $line->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 0; + } + + if ($num_prods > 0) + { + $prodid = mt_rand(1, $num_prods); + $line->fk_product = $prodids[$prodid]; + } + $line->product_type = 0; + + $this->lines[$xnbp] = $line; + + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + + $xnbp++; + } + } + + $this->amount_ht = $xnbp * 100; + $this->total_ht = $xnbp * 100; + $this->total_tva = $xnbp * 19.6; + $this->total_ttc = $xnbp * 119.6; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @return int <0 if KO, >0 if OK - */ - public function load_state_board() + */ + public function load_state_board() { - // phpcs:enable + // phpcs:enable global $conf, $user; $this->nb = array(); @@ -2541,7 +2541,7 @@ class FactureFournisseur extends CommonInvoice { $this->nb["supplier_invoices"] = $obj->nb; } - $this->db->free($resql); + $this->db->free($resql); return 1; } else { dol_print_error($this->db); @@ -2550,81 +2550,81 @@ class FactureFournisseur extends CommonInvoice } } - /** - * Load an object from its id and create a new one in database - * - * @param User $user User that clone - * @param int $fromid Id of object to clone - * @param int $invertdetail Reverse sign of amounts for lines - * @return int New id of clone - */ - public function createFromClone(User $user, $fromid, $invertdetail = 0) - { - global $langs; + /** + * Load an object from its id and create a new one in database + * + * @param User $user User that clone + * @param int $fromid Id of object to clone + * @param int $invertdetail Reverse sign of amounts for lines + * @return int New id of clone + */ + public function createFromClone(User $user, $fromid, $invertdetail = 0) + { + global $langs; - $error = 0; + $error = 0; - $object = new FactureFournisseur($this->db); + $object = new FactureFournisseur($this->db); $this->db->begin(); - // Load source object - $object->fetch($fromid); - $object->id = 0; - $object->statut = self::STATUS_DRAFT; + // Load source object + $object->fetch($fromid); + $object->id = 0; + $object->statut = self::STATUS_DRAFT; - $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor + $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor - // Clear fields - $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier); - $object->author = $user->id; - $object->user_valid = ''; - $object->fk_facture_source = 0; - $object->date_creation = ''; - $object->date_validation = ''; - $object->date = (empty($this->date) ? '' : $this->date); - $object->date_echeance = ''; - $object->ref_client = ''; - $object->close_code = ''; - $object->close_note = ''; + // Clear fields + $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier); + $object->author = $user->id; + $object->user_valid = ''; + $object->fk_facture_source = 0; + $object->date_creation = ''; + $object->date_validation = ''; + $object->date = (empty($this->date) ? '' : $this->date); + $object->date_echeance = ''; + $object->ref_client = ''; + $object->close_code = ''; + $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 - { - unset($object->lines[$i]); - } - } + // 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 + { + unset($object->lines[$i]); + } + } - // Create clone - $object->context['createfromclone'] = 'createfromclone'; - $result = $object->create($user); + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->create($user); - // Other options - if ($result < 0) - { - $this->error = $object->error; - $this->errors = $object->errors; - $error++; - } + // Other options + if ($result < 0) + { + $this->error = $object->error; + $this->errors = $object->errors; + $error++; + } - if (!$error) - { - } + if (!$error) + { + } - unset($object->context['createfromclone']); + unset($object->context['createfromclone']); - // End - if (!$error) - { - $this->db->commit(); - return $object->id; - } else { - $this->db->rollback(); - return -1; - } - } + // End + if (!$error) + { + $this->db->commit(); + return $object->id; + } else { + $this->db->rollback(); + return -1; + } + } /** * Create a document onto disk according to template model. @@ -2634,7 +2634,7 @@ class FactureFournisseur extends CommonInvoice * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref - * @param null|array $moreparams Array to provide more information + * @param null|array $moreparams Array to provide more information * @return int <0 if KO, 0 if nothing done, >0 if OK */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) @@ -2657,11 +2657,11 @@ class FactureFournisseur extends CommonInvoice if (empty($modele)) { - return 0; + return 0; } else { - $modelpath = "core/modules/supplier_invoice/doc/"; + $modelpath = "core/modules/supplier_invoice/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } } @@ -2693,44 +2693,42 @@ class FactureFournisseur extends CommonInvoice return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } - /** - * Is the payment of the supplier invoice having a delay? - * - * @return bool - */ - public function hasDelay() - { - global $conf; + /** + * Is the payment of the supplier invoice having a delay? + * + * @return bool + */ + public function hasDelay() + { + global $conf; - $now = dol_now(); + $now = dol_now(); - if (!$this->date_echeance) { - return false; - } + if (!$this->date_echeance) { + return false; + } - return ($this->statut == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay)); - } + return ($this->statut == self::STATUS_VALIDATED) && ($this->date_echeance < ($now - $conf->facture->fournisseur->warning_delay)); + } - /** - * Is credit note used - * - * @return bool - */ - public function isCreditNoteUsed() - { - global $db; + /** + * Is credit note used + * + * @return bool + */ + public function isCreditNoteUsed() + { + $isUsed = false; - $isUsed = false; + $sql = "SELECT fk_invoice_supplier FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_invoice_supplier_source=".$this->id; + $resql = $this->db->query($sql); + if (!empty($resql)) { + $obj = $this->db->fetch_object($resql); + if (!empty($obj->fk_invoice_supplier)) $isUsed = true; + } - $sql = "SELECT fk_invoice_supplier FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_invoice_supplier_source=".$this->id; - $resql = $db->query($sql); - if (!empty($resql)) { - $obj = $db->fetch_object($resql); - if (!empty($obj->fk_invoice_supplier))$isUsed = true; - } - - return $isUsed; - } + return $isUsed; + } } @@ -2844,63 +2842,63 @@ class SupplierInvoiceLine extends CommonObjectLine */ public $tva_tx; - /** + /** * Local tax 1 % * @var float */ public $localtax1_tx; - /** + /** * Local tax 2 % * @var float */ public $localtax2_tx; - /** + /** * Quantity * @var double */ public $qty; - /** + /** * Percent of discount * @var float */ public $remise_percent; - /** + /** * Total amount without taxes * @var float */ public $total_ht; - /** + /** * Total amount with taxes * @var float */ public $total_ttc; - /** + /** * Total amount of taxes * @var float */ public $total_tva; - /** + /** * Total local tax 1 amount * @var float */ public $total_localtax1; - /** + /** * Total local tax 2 amount * @var float */ public $total_localtax2; /** - * @var int ID - */ + * @var int ID + */ public $fk_product; /** @@ -2909,13 +2907,13 @@ class SupplierInvoiceLine extends CommonObjectLine */ public $product_type; - /** + /** * Label of the product * @var string */ public $product_label; - /** + /** * List of cumulative options: * Bit 0: 0 si TVA normal - 1 si TVA NPR * Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except) @@ -2924,24 +2922,24 @@ class SupplierInvoiceLine extends CommonObjectLine public $info_bits; /** - * @var int ID - */ + * @var int ID + */ public $fk_parent_line; public $special_code; /** - * @var int rank of line - */ + * @var int rank of line + */ public $rang; - /** + /** * Total local tax 1 amount * @var float */ public $localtax1_type; - /** + /** * Total local tax 2 amount * @var float */ @@ -2949,8 +2947,8 @@ class SupplierInvoiceLine extends CommonObjectLine // Multicurrency /** - * @var int ID - */ + * @var int ID + */ public $fk_multicurrency; public $multicurrency_code; @@ -2960,14 +2958,14 @@ class SupplierInvoiceLine extends CommonObjectLine public $multicurrency_total_ttc; /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } /** * Retrieves a supplier invoice line @@ -3072,15 +3070,15 @@ class SupplierInvoiceLine extends CommonObjectLine $this->deleteObjectLinked(); // Remove extrafields - if (!$error) - { - $result = $this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + if (!$error) + { + $result = $this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } if (!$error) { // Supprime ligne @@ -3142,7 +3140,7 @@ class SupplierInvoiceLine extends CommonObjectLine if (empty($this->fk_unit)) { $fk_unit = "null"; } else { - $fk_unit = "'".$this->db->escape($this->fk_unit)."'"; + $fk_unit = "'".$this->db->escape($this->fk_unit)."'"; } $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; @@ -3172,9 +3170,9 @@ class SupplierInvoiceLine extends CommonObjectLine // Multicurrency $sql .= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql .= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql .= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql .= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql .= " WHERE rowid = ".$this->id; @@ -3220,178 +3218,178 @@ class SupplierInvoiceLine extends CommonObjectLine return 1; } - /** - * Insert line into database - * - * @param int $notrigger 1 no triggers - * @return int <0 if KO, >0 if OK - */ - public function insert($notrigger = 0) - { - global $user, $conf; + /** + * Insert line into database + * + * @param int $notrigger 1 no triggers + * @return int <0 if KO, >0 if OK + */ + public function insert($notrigger = 0) + { + global $user, $conf; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); + dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG); - // 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; + // 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->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) - { - $this->error = 'ErrorProductTypeMustBe0orMore'; - return -1; - } - if (!empty($this->fk_product)) - { - // Check product exists - $result = Product::isExistingObject('product', $this->fk_product); - if ($result <= 0) - { - $this->error = 'ErrorProductIdDoesNotExists'; - return -1; - } - } + // Check parameters + if ($this->product_type < 0) + { + $this->error = 'ErrorProductTypeMustBe0orMore'; + return -1; + } + if (!empty($this->fk_product)) + { + // Check product exists + $result = Product::isExistingObject('product', $this->fk_product); + if ($result <= 0) + { + $this->error = 'ErrorProductIdDoesNotExists'; + return -1; + } + } - $this->db->begin(); + $this->db->begin(); - // Insertion dans base de la ligne - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' (fk_facture_fourn, fk_parent_line, label, description, ref, qty,'; - $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql .= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,'; - $sql .= ' date_start, date_end, fk_code_ventilation, rang, special_code,'; - $sql .= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit'; - $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql .= ')'; - $sql .= " VALUES (".$this->fk_facture_fourn.","; - $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").","; - $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; - $sql .= " '".$this->db->escape($this->desc ? $this->desc : $this->description)."',"; - $sql .= " '".$this->db->escape($this->ref_supplier)."',"; - $sql .= " ".price2num($this->qty).","; + // Insertion dans base de la ligne + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' (fk_facture_fourn, fk_parent_line, label, description, ref, qty,'; + $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql .= ' fk_product, product_type, remise_percent, pu_ht, pu_ttc,'; + $sql .= ' date_start, date_end, fk_code_ventilation, rang, special_code,'; + $sql .= ' info_bits, total_ht, tva, total_ttc, total_localtax1, total_localtax2, fk_unit'; + $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; + $sql .= ')'; + $sql .= " VALUES (".$this->fk_facture_fourn.","; + $sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").","; + $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; + $sql .= " '".$this->db->escape($this->desc ? $this->desc : $this->description)."',"; + $sql .= " '".$this->db->escape($this->ref_supplier)."',"; + $sql .= " ".price2num($this->qty).","; - $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; - $sql .= " ".price2num($this->tva_tx).","; - $sql .= " ".price2num($this->localtax1_tx).","; - $sql .= " ".price2num($this->localtax2_tx).","; - $sql .= " '".$this->db->escape($this->localtax1_type)."',"; - $sql .= " '".$this->db->escape($this->localtax2_type)."',"; - $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").','; - $sql .= " ".$this->product_type.","; - $sql .= " ".price2num($this->remise_percent).","; - $sql .= " ".price2num($this->subprice).","; - $sql .= " ".(!empty($this->qty) ?price2num($this->total_ttc / $this->qty) : price2num($this->total_ttc)).","; - $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").","; - $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").","; - $sql .= ' '.(!empty($this->fk_code_ventilation) ? $this->fk_code_ventilation : 0).','; - $sql .= ' '.$this->rang.','; - $sql .= ' '.$this->special_code.','; - $sql .= " '".$this->db->escape($this->info_bits)."',"; - $sql .= " ".price2num($this->total_ht).","; - $sql .= " ".price2num($this->total_tva).","; - $sql .= " ".price2num($this->total_ttc).","; - $sql .= " ".price2num($this->total_localtax1).","; - $sql .= " ".price2num($this->total_localtax2); - $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); - $sql .= ", ".(int) $this->fk_multicurrency; - $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql .= ", ".price2num($this->multicurrency_subprice); - $sql .= ", ".price2num($this->multicurrency_total_ht); - $sql .= ", ".price2num($this->multicurrency_total_tva); - $sql .= ", ".price2num($this->multicurrency_total_ttc); - $sql .= ')'; + $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").","; + $sql .= " ".price2num($this->tva_tx).","; + $sql .= " ".price2num($this->localtax1_tx).","; + $sql .= " ".price2num($this->localtax2_tx).","; + $sql .= " '".$this->db->escape($this->localtax1_type)."',"; + $sql .= " '".$this->db->escape($this->localtax2_type)."',"; + $sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").','; + $sql .= " ".$this->product_type.","; + $sql .= " ".price2num($this->remise_percent).","; + $sql .= " ".price2num($this->subprice).","; + $sql .= " ".(!empty($this->qty) ?price2num($this->total_ttc / $this->qty) : price2num($this->total_ttc)).","; + $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").","; + $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").","; + $sql .= ' '.(!empty($this->fk_code_ventilation) ? $this->fk_code_ventilation : 0).','; + $sql .= ' '.$this->rang.','; + $sql .= ' '.$this->special_code.','; + $sql .= " '".$this->db->escape($this->info_bits)."',"; + $sql .= " ".price2num($this->total_ht).","; + $sql .= " ".price2num($this->total_tva).","; + $sql .= " ".price2num($this->total_ttc).","; + $sql .= " ".price2num($this->total_localtax1).","; + $sql .= " ".price2num($this->total_localtax2); + $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".price2num($this->multicurrency_subprice); + $sql .= ", ".price2num($this->multicurrency_total_ht); + $sql .= ", ".price2num($this->multicurrency_total_tva); + $sql .= ", ".price2num($this->multicurrency_total_ttc); + $sql .= ')'; - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - $this->rowid = $this->id; // backward compatibility + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + $this->rowid = $this->id; // backward compatibility - if (!$error) - { - $result = $this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (!$error) + { + $result = $this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -2; - } - // End call triggers - } + if (!$error && !$notrigger) + { + // Call trigger + $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } - $this->db->commit(); - return $this->id; - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -2; - } - } + $this->db->commit(); + return $this->id; + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -2; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Mise a jour de l'objet ligne de commande en base - * - * @return int <0 si ko, >0 si ok - */ - public function update_total() - { - // phpcs:enable - $this->db->begin(); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Mise a jour de l'objet ligne de commande en base + * + * @return int <0 si ko, >0 si ok + */ + public function update_total() + { + // phpcs:enable + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; - $sql .= " total_ht='".price2num($this->total_ht)."'"; - $sql .= ", tva='".price2num($this->total_tva)."'"; - $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; - $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; - $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; - $sql .= " WHERE rowid = ".$this->rowid; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; + $sql .= " total_ht='".price2num($this->total_ht)."'"; + $sql .= ", tva='".price2num($this->total_tva)."'"; + $sql .= ", total_localtax1='".price2num($this->total_localtax1)."'"; + $sql .= ", total_localtax2='".price2num($this->total_localtax2)."'"; + $sql .= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql .= " WHERE rowid = ".$this->rowid; - dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG); + dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -2; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index b3c4514f5ff..8752d17a5d8 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -349,8 +349,8 @@ class ProductFournisseur extends Product // TODO Add localtax1 and localtax2 //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').","; //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').","; - //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$localtaxtype1."'":"'0'").","; - //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$localtaxtype2."'":"'0'").","; + //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$this->db->escape($localtaxtype1)."'":"'0'").","; + //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$this->db->escape($localtaxtype2)."'":"'0'").","; $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").","; $sql .= " info_bits = ".$newnpr.","; $sql .= " charges = ".$charges.","; // deprecated diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index e6795593721..67133ed97b2 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -119,7 +119,6 @@ class PaiementFourn extends Paiement $this->entity = $obj->entity; $this->date = $this->db->jdate($obj->dp); $this->datepaye = $this->db->jdate($obj->dp); - $this->num_paiement = $obj->num_payment; $this->num_payment = $obj->num_payment; $this->bank_account = $obj->fk_account; $this->fk_account = $obj->fk_account; @@ -177,7 +176,7 @@ class PaiementFourn extends Paiement foreach ($amounts as $key => $value) { - $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value, $way, 'facture_fourn'); + $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value? $value : 0, $way, 'facture_fourn'); $totalamount_converted += $value_converted; $amounts_to_update[$key] = price2num($value_converted, 'MT'); @@ -207,7 +206,7 @@ class PaiementFourn extends Paiement $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn ('; $sql .= 'ref, entity, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_author, fk_bank)'; $sql .= " VALUES ('".$this->db->escape($ref)."', ".$conf->entity.", '".$this->db->idate($now)."',"; - $sql .= " '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->db->escape($this->num_paiement)."', '".$this->db->escape($this->note)."', ".$user->id.", 0)"; + $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) @@ -256,7 +255,7 @@ class PaiementFourn extends Paiement $outputlangs->setDefaultLang($newlang); } $ret = $invoice->fetch($facid); // Reload to get new records - $result = $invoice->generateDocument($invoice->modelpdf, $outputlangs); + $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs); if ($result < 0) { setEventMessages($invoice->error, $invoice->errors, 'errors'); $error++; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 7a50a189e44..7cbe020142f 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -214,66 +214,66 @@ if (empty($reshook)) 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) - { - $new_socid = GETPOST('new_socid', 'int'); - if (!empty($new_socid) && $new_socid != $object->thirdparty->id) { - $db->begin(); + // Edit Thirdparty + 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(); - // Update supplier - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql .= ' SET fk_soc='.$new_socid; - $sql .= ' WHERE fk_soc='.$object->thirdparty->id; - $sql .= ' AND rowid='.$object->id; + // Update supplier + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql .= ' SET fk_soc='.$new_socid; + $sql .= ' WHERE fk_soc='.$object->thirdparty->id; + $sql .= ' AND rowid='.$object->id; - $res = $db->query($sql); + $res = $db->query($sql); - if (!$res) $db->rollback(); - else { - $db->commit(); + if (!$res) $db->rollback(); + else { + $db->commit(); - // Replace prices for each lines by new supplier prices - foreach ($object->lines as $l) { - $sql = 'SELECT price, unitprice, tva_tx, ref_fourn'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price'; - $sql .= ' WHERE fk_product='.$l->fk_product; - $sql .= ' AND fk_soc='.$new_socid; - $sql .= ' ORDER BY unitprice ASC'; + // Replace prices for each lines by new supplier prices + foreach ($object->lines as $l) { + $sql = 'SELECT price, unitprice, tva_tx, ref_fourn'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price'; + $sql .= ' WHERE fk_product='.$l->fk_product; + $sql .= ' AND fk_soc='.$new_socid; + $sql .= ' ORDER BY unitprice ASC'; - $resql = $db->query($sql); - if ($resql) { - $num_row = $db->num_rows($resql); - if (empty($num_row)) { - // No product price for this supplier ! - $l->subprice = 0; - $l->total_ht = 0; - $l->total_tva = 0; - $l->total_ttc = 0; - $l->ref_supplier = ''; - $l->update(); - } else { - // No need for loop to keep best supplier price - $obj = $db->fetch_object($resql); - $l->subprice = $obj->unitprice; - $l->total_ht = $obj->price; - $l->tva_tx = $obj->tva_tx; - $l->total_tva = $l->total_ht * ($obj->tva_tx / 100); - $l->total_ttc = $l->total_ht + $l->total_tva; - $l->ref_supplier = $obj->ref_fourn; - $l->update(); - } - } else { - dol_print_error($db); - } - $db->free($resql); - } - $object->update_price(); - } - } - header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); - exit; - } + $resql = $db->query($sql); + if ($resql) { + $num_row = $db->num_rows($resql); + if (empty($num_row)) { + // No product price for this supplier ! + $l->subprice = 0; + $l->total_ht = 0; + $l->total_tva = 0; + $l->total_ttc = 0; + $l->ref_supplier = ''; + $l->update(); + } else { + // No need for loop to keep best supplier price + $obj = $db->fetch_object($resql); + $l->subprice = $obj->unitprice; + $l->total_ht = $obj->price; + $l->tva_tx = $obj->tva_tx; + $l->total_tva = $l->total_ht * ($obj->tva_tx / 100); + $l->total_ttc = $l->total_ht + $l->total_tva; + $l->ref_supplier = $obj->ref_fourn; + $l->update(); + } + } else { + dol_print_error($db); + } + $db->free($resql); + } + $object->update_price(); + } + } + header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); + exit; + } if ($action == 'setremisepercent' && $usercancreate) { @@ -406,7 +406,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (!GETPOST('qty')) + if (GETPOST('qty', 'int') == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; @@ -481,7 +481,7 @@ if (empty($reshook)) } // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { - $desc = $productsupplier->desc_supplier; + $desc = $productsupplier->desc_supplier; } if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); @@ -601,7 +601,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -652,7 +652,9 @@ if (empty($reshook)) */ if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { - $vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0); + $db->begin(); + + $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if ($lineid) { @@ -664,7 +666,7 @@ if (empty($reshook)) $productsupplier = new ProductFournisseur($db); if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { - if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) + if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty', 'int')), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } @@ -679,7 +681,7 @@ if (empty($reshook)) $info_bits |= 0x01; } - // Define vat_rate + // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); @@ -717,7 +719,7 @@ if (empty($reshook)) $lineid, $_POST['product_desc'], $ht, - $_POST['qty'], + GETPOST('qty', 'int'), $_POST['remise_percent'], $vat_rate, $localtax1_rate, @@ -774,13 +776,17 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $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); } + + $db->commit(); } else { + $db->rollback(); + dol_print_error($db, $object->error); exit; } @@ -789,6 +795,8 @@ if (empty($reshook)) // Remove a product line if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + $db->begin(); + $result = $object->deleteline($lineid); if ($result > 0) { @@ -805,21 +813,30 @@ if (empty($reshook)) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } + } else { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + // Reset action to avoid asking again confirmation on failure + $action = ''; + } + + if (!$error) { + $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { - setEventMessages($object->error, $object->errors, 'errors'); - /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ - $action = ''; + $db->rollback(); } } // Validate if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { + $db->begin(); + $object->date_commande = dol_now(); $result = $object->valid($user); if ($result >= 0) @@ -835,25 +852,37 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $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) { + $error++; + dol_print_error($db, $result); + } } } else { + $error++; setEventMessages($object->error, $object->errors, 'errors'); } // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (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 } + + if (! $error) { + $db->commit(); + } else { + $db->rollback(); + } } if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) { + $db->begin(); + $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; @@ -889,14 +918,22 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; } else { + $error++; setEventMessages($object->error, $object->errors, 'errors'); } } + + if (!$error) { + $db->commit(); + + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } else { + $db->rollback(); + } } if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) @@ -912,17 +949,19 @@ if (empty($reshook)) } // Force mandatory order method - if ($action == 'commande') { - $methodecommande = GETPOST('methodecommande', 'int'); + if ($action == 'commande') { + $methodecommande = GETPOST('methodecommande', 'int'); - if ($methodecommande <= 0) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("OrderMode")), null, 'errors'); - $action = 'makeorder'; - } - } + if ($methodecommande <= 0) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("OrderMode")), null, 'errors'); + $action = 'makeorder'; + } + } if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) { + $db->begin(); + $result = $object->commande($user, GETPOST("datecommande"), GETPOST("methode", 'int'), GETPOST('comment', 'alphanohtml')); if ($result > 0) { @@ -936,13 +975,21 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } $action = ''; + } else { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + + if (!$error) { + $db->commit(); + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } else { - setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); } } @@ -987,6 +1034,8 @@ if (empty($reshook)) // Set status of reception (complete, partial, ...) if ($action == 'livraison' && $usercanreceived) { + $db->begin(); + if (GETPOST("type") != '') { $date_liv = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear")); @@ -999,13 +1048,22 @@ if (empty($reshook)) $action = ''; } elseif ($result == -3) { + $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { + $error++; setEventMessages($object->error, $object->errors, 'errors'); } } else { + $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors'); } + + if (! $error) { + $db->commit(); + } else { + $db->rollback(); + } } if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) @@ -1040,7 +1098,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -1067,7 +1125,7 @@ if (empty($reshook)) if ($action == 'add' && $usercancreate) { $error = 0; - $selectedLines = GETPOST('toselect', 'array'); + $selectedLines = GETPOST('toselect', 'array'); if ($socid < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); @@ -1085,8 +1143,8 @@ if (empty($reshook)) $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); - $object->note_private = GETPOST('note_private', 'none'); - $object->note_public = GETPOST('note_public', 'none'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); $object->date_livraison = $datelivraison; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); @@ -1218,7 +1276,7 @@ if (empty($reshook)) '', null, null, - $array_option, + $array_option, $lines[$i]->fk_unit, 0, $element, @@ -1426,8 +1484,8 @@ 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') { print load_fiche_titre($langs->trans('NewOrderSupplier'), '', 'supplier_order'); @@ -1645,7 +1703,7 @@ if ($action == 'create') print '
    '; print ''; //print ''; @@ -1653,7 +1711,7 @@ if ($action == 'create') print ''; print ''; //print ''; @@ -1727,9 +1785,8 @@ if ($action == 'create') print '
    '; - print ''; // ancre - print $langs->trans('Description').''.$langs->trans('Date').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').' 
    '; + print ''; // ancre + print $langs->trans('Description').''.$langs->trans('Date').''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').' 
    '; - // editeur wysiwyg - if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'alpha'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); - $doleditor->Create(); - } - print ''; + // No. + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''.($i + 1).''; + // editeur wysiwyg + if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); + $doleditor->Create(); + } + print ''; $now = dol_now(); $timearray = dol_getdate($now); if (!GETPOST('diday', 'int')) { - $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); - } else { - $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); - } - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); - } else { - print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); - } + $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); + } else { + $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); + } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); + } else { + print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); + } print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { - $selectmode = 'text'; - } - $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); - } - print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { + $selectmode = 'text'; + } + $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); + } + print '
    '; print ''; + print ''; + print ''; + print dol_escape_htmltag($obj->note_public); + print ''; + print dol_escape_htmltag($obj->note_private); + print '
    '.$langs->trans('NotePublic').''; - $doleditor = new DolEditor('note_public', isset($note_public) ? $note_public : GETPOST('note_public', 'none'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', isset($note_public) ? $note_public : GETPOST('note_public', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print '
    '.$langs->trans('NotePrivate').''; - $doleditor = new DolEditor('note_private', isset($note_private) ? $note_private : GETPOST('note_private', 'none'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', isset($note_private) ? $note_private : GETPOST('note_private', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print '
    '; } - print "\n"; -} elseif (!empty($object->id)) -{ + print "\n"; +} elseif (!empty($object->id)) { $result = $object->fetch($id, $ref); $societe = new Fournisseur($db); @@ -1878,53 +1935,53 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty'); - if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') { - $morehtmlref .= ' : '; - $morehtmlref .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $form->select_company($object->thirdparty->id, 'new_socid', 's.fournisseur=1', '', 0, 0, array(), 0, 'minwidth300'); - $morehtmlref .= ''; - $morehtmlref .= '
    '; - } - if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { - if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).''; - } - $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; - } + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') { + $morehtmlref .= ' : '; + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $form->select_company($object->thirdparty->id, 'new_socid', 's.fournisseur=1', '', 0, 0, array(), 0, 'minwidth300'); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } + if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') { + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).''; + } + $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; + } // Project - if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - 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 .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $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 .= ''; - } - } - } + if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + 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 .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1, 0, 'maxwidth500'); + $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 .= '
    '; @@ -2134,7 +2191,7 @@ if ($action == 'create') print ''; if ($action != 'editincoterm') { - print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); + 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); } @@ -2502,7 +2559,7 @@ if ($action == 'create') // Delete if (!empty($usercandelete) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($usercancreate))) { - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; } } @@ -2527,8 +2584,8 @@ if ($action == 'create') print $form->selectDate($date_com, '', 1, 1, '', "commande", 1, 1); print ''; - // Force mandatory order method - print ''.$langs->trans("OrderMode").''; + // Force mandatory order method + print ''.$langs->trans("OrderMode").''; $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); print ''; @@ -2557,7 +2614,7 @@ if ($action == 'create') $genallowed = $usercanread; $delallowed = $usercancreate; - print $formfile->showdocuments('commande_fournisseur', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang); + print $formfile->showdocuments('commande_fournisseur', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang); $somethingshown = $formfile->numoffiles; // Show links to link elements diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index b3d2e3aa664..683658c791e 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -38,7 +38,7 @@ $langs->loadLangs(array("facture", "orders", "sendings", "companies")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index c64d158ac2c..7a11d22aa53 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -565,36 +565,36 @@ if ($id > 0 || !empty($ref)) { // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { - if ($action != 'classify') { - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->fournisseur->commande->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 .= ''; - } - } + } + 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 .= '
    '; @@ -625,8 +625,8 @@ if ($id > 0 || !empty($ref)) { print ''.$author->getNomUrl(1, '', 0, 0, 0).''; print ''; - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print ""; @@ -656,7 +656,7 @@ if ($id > 0 || !empty($ref)) { if (empty($conf->reception->enabled))print '
    '; - else print ''; + else print ''; print ''; if (empty($conf->reception->enabled))print ''; @@ -691,16 +691,16 @@ if ($id > 0 || !empty($ref)) { $sql = "SELECT l.rowid, l.fk_product, l.subprice, l.remise_percent, l.ref AS sref, SUM(l.qty) as qty,"; $sql .= " p.ref, p.label, p.tobatch, p.fk_default_warehouse"; - // Enable hooks to alter the SQL query (SELECT) - $parameters = array(); - $reshook = $hookmanager->executeHooks( - 'printFieldListSelect', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $sql .= $hookmanager->resPrint; + // Enable hooks to alter the SQL query (SELECT) + $parameters = array(); + $reshook = $hookmanager->executeHooks( + 'printFieldListSelect', + $parameters, + $object, + $action + ); + 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"; @@ -708,16 +708,16 @@ if ($id > 0 || !empty($ref)) { if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND l.product_type = 0"; - // Enable hooks to alter the SQL query (WHERE) - $parameters = array(); - $reshook = $hookmanager->executeHooks( - 'printFieldListWhere', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $sql .= $hookmanager->resPrint; + // Enable hooks to alter the SQL query (WHERE) + $parameters = array(); + $reshook = $hookmanager->executeHooks( + 'printFieldListWhere', + $parameters, + $object, + $action + ); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $sql .= $hookmanager->resPrint; $sql .= " GROUP BY p.ref, p.label, p.tobatch, l.rowid, l.fk_product, l.subprice, l.remise_percent, p.fk_default_warehouse"; // Calculation of amount dispatched is done per fk_product so we must group by fk_product $sql .= " ORDER BY p.ref, p.label"; @@ -733,8 +733,12 @@ if ($id > 0 || !empty($ref)) { print ''.$langs->trans("Description").''; if (!empty($conf->productbatch->enabled)) { print ''.$langs->trans("batch_number").''; - print ''.$langs->trans("EatByDate").''; - print ''.$langs->trans("SellByDate").''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''.$langs->trans("EatByDate").''; + } + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print ''.$langs->trans("SellByDate").''; + } } else { print ''; print ''; @@ -744,7 +748,7 @@ if ($id > 0 || !empty($ref)) { print ''.$langs->trans("QtyOrdered").''; print ''.$langs->trans("QtyDispatchedShort").''; print ' '.$langs->trans("QtyToDispatchShort"); - print '
    '.$langs->trans("Reset").''; + print '
    '.$langs->trans("Reset").''; print ''; if (!empty($conf->global->SUPPLIER_ORDER_CAN_UPDATE_BUYINGPRICE_DURING_RECEIPT)) { @@ -766,16 +770,16 @@ if ($id > 0 || !empty($ref)) { print ''; - // Enable hooks to append additional columns - $parameters = array(); - $reshook = $hookmanager->executeHooks( - 'printFieldListTitle', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - print $hookmanager->resPrint; + // Enable hooks to append additional columns + $parameters = array(); + $reshook = $hookmanager->executeHooks( + 'printFieldListTitle', + $parameters, + $object, + $action + ); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print $hookmanager->resPrint; print "\n"; } @@ -819,8 +823,12 @@ if ($id > 0 || !empty($ref)) { print $linktoprod; print ""; print ''; - print ''; - print ''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''; + } + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print ''; + } } else { print ''; print $linktoprod; @@ -828,8 +836,12 @@ if ($id > 0 || !empty($ref)) { print ''; print $langs->trans("ProductDoesNotUseBatchSerial"); print ''; - print ''; - print ''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''; + } + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print ''; + } } } else { print ''; @@ -860,21 +872,21 @@ if ($id > 0 || !empty($ref)) { print ''; // Dispatch column print ''; // Warehouse column - // Enable hooks to append additional columns - $parameters = array( - 'is_information_row' => true, // allows hook to distinguish between the - // rows with information and the rows with - // dispatch form input - 'objp' => $objp - ); - $reshook = $hookmanager->executeHooks( - 'printFieldListValue', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - print $hookmanager->resPrint; + // Enable hooks to append additional columns + $parameters = array( + 'is_information_row' => true, // allows hook to distinguish between the + // rows with information and the rows with + // dispatch form input + 'objp' => $objp + ); + $reshook = $hookmanager->executeHooks( + 'printFieldListValue', + $parameters, + $object, + $action + ); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print $hookmanager->resPrint; print ''; @@ -886,9 +898,9 @@ if ($id > 0 || !empty($ref)) { print ''; if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! { - print $langs->trans("BuyingPrice").': '; + print $langs->trans("BuyingPrice").': '; } else { - print ''; + print ''; } print ''; @@ -896,17 +908,24 @@ if ($id > 0 || !empty($ref)) { print ''; print ''; print ''; - print ''; - $dlcdatesuffix = dol_mktime(0, 0, 0, GETPOST('dlc'.$suffix.'month'), GETPOST('dlc'.$suffix.'day'), GETPOST('dlc'.$suffix.'year')); - print $form->selectDate($dlcdatesuffix, 'dlc'.$suffix, '', '', 1, ''); - print ''; - print ''; - $dluodatesuffix = dol_mktime(0, 0, 0, GETPOST('dluo'.$suffix.'month'), GETPOST('dluo'.$suffix.'day'), GETPOST('dluo'.$suffix.'year')); - print $form->selectDate($dluodatesuffix, 'dluo'.$suffix, '', '', 1, ''); - print ''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''; + $dlcdatesuffix = dol_mktime(0, 0, 0, GETPOST('dlc' . $suffix . 'month'), GETPOST('dlc' . $suffix . 'day'), GETPOST('dlc' . $suffix . 'year')); + print $form->selectDate($dlcdatesuffix, 'dlc' . $suffix, '', '', 1, ''); + print ''; + } + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''; + $dluodatesuffix = dol_mktime(0, 0, 0, GETPOST('dluo'.$suffix.'month'), GETPOST('dluo'.$suffix.'day'), GETPOST('dluo'.$suffix.'year')); + print $form->selectDate($dluodatesuffix, 'dluo'.$suffix, '', '', 1, ''); + print ''; + } print ' '; // Supplier ref + Qty ordered + qty already dispatched } else { $type = 'dispatch'; + $colspan = 7; + $colspan = (!empty($conf->global->PRODUCT_DISABLE_EATBY)) ? --$colspan : $colspan; + $colspan = (!empty($conf->global->PRODUCT_DISABLE_SELLBY)) ? --$colspan : $colspan; print ''; print ''; // Qty to dispatch print ''; @@ -914,35 +933,35 @@ if ($id > 0 || !empty($ref)) { print ''; // Dispatch column print ''; // Warehouse column - // Enable hooks to append additional columns - $parameters = array( - 'is_information_row' => true, // allows hook to distinguish between the - // rows with information and the rows with - // dispatch form input - 'objp' => $objp - ); - $reshook = $hookmanager->executeHooks( - 'printFieldListValue', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - print $hookmanager->resPrint; + // Enable hooks to append additional columns + $parameters = array( + 'is_information_row' => true, // allows hook to distinguish between the + // rows with information and the rows with + // dispatch form input + 'objp' => $objp + ); + $reshook = $hookmanager->executeHooks( + 'printFieldListValue', + $parameters, + $object, + $action + ); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print $hookmanager->resPrint; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! { - print $langs->trans("BuyingPrice").': '; + print $langs->trans("BuyingPrice").': '; } else { - print ''; + print ''; } print ''; @@ -955,11 +974,11 @@ if ($id > 0 || !empty($ref)) { print ''; if (!empty($conf->productbatch->enabled) && $objp->tobatch == 1) { - $type = 'batch'; - print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$i.', \''.$type.'\')"'); + $type = 'batch'; + print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$i.', \''.$type.'\')"'); } else { - $type = 'dispatch'; - print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$i.', \''.$type.'\')"'); + $type = 'dispatch'; + print img_picto($langs->trans('AddStockLocationLine'), 'split.png', 'class="splitbutton" onClick="addDispatchLine('.$i.', \''.$type.'\')"'); } print ''; @@ -994,18 +1013,18 @@ if ($id > 0 || !empty($ref)) { } print "\n"; - // Enable hooks to append additional columns - $parameters = array( - 'is_information_row' => false // this is a dispatch form row - ); - $reshook = $hookmanager->executeHooks( - 'printFieldListValue', - $parameters, - $object, - $action - ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - print $hookmanager->resPrint; + // Enable hooks to append additional columns + $parameters = array( + 'is_information_row' => false // this is a dispatch form row + ); + $reshook = $hookmanager->executeHooks( + 'printFieldListValue', + $parameters, + $object, + $action + ); + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print $hookmanager->resPrint; print "\n"; } @@ -1030,20 +1049,20 @@ if ($id > 0 || !empty($ref)) { // modified by hook if (empty($reshook)) { - if (empty($conf->reception->enabled)) { - print $langs->trans("Comment").' : '; - print 'trans("DispatchSupplierOrder", $object->ref); - // print ' / '.$object->ref_supplier; // Not yet available - print '" class="flat">
    '; + if (empty($conf->reception->enabled)) { + print $langs->trans("Comment").' : '; + print 'trans("DispatchSupplierOrder", $object->ref); + // print ' / '.$object->ref_supplier; // Not yet available + print '" class="flat">
    '; - print ' '.$checkboxlabel; - } + print ' '.$checkboxlabel; + } - $dispatchBt = empty($conf->reception->enabled) ? $langs->trans("Receive") : $langs->trans("CreateReception"); + $dispatchBt = empty($conf->reception->enabled) ? $langs->trans("Receive") : $langs->trans("CreateReception"); - print '
    '; } @@ -1052,8 +1071,8 @@ if ($id > 0 || !empty($ref)) { // Message if nothing to dispatch if (!$nbproduct) { - print "
    \n"; - if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) + print "
    \n"; + if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) print '
    '.$langs->trans("NoPredefinedProductToDispatch").'
    '; // No predefined line at all else print '
    '.$langs->trans("NoMorePredefinedProductToDispatch").'
    '; // No predefined line that remain to be dispatched. } @@ -1070,14 +1089,14 @@ if ($id > 0 || !empty($ref)) { var fk_default_warehouse = $("option:selected", this).val(); $("select[name^=entrepot_]").val(fk_default_warehouse).change(); }); - + jQuery("#autoreset").click(function() {'; - $i = 0; - while ($i < $nbproduct) { - print ' jQuery("#qty_0_'.$i.'").val("");'; - $i++; - } - print ' + $i = 0; + while ($i < $nbproduct) { + print ' jQuery("#qty_0_'.$i.'").val("");'; + $i++; + } + print ' }); }); '; @@ -1118,8 +1137,12 @@ if ($id > 0 || !empty($ref)) { print ''.$langs->trans("DateDeliveryPlanned").''; if (!empty($conf->productbatch->enabled)) { print ''.$langs->trans("batch_number").''; - print ''.$langs->trans("EatByDate").''; - print ''.$langs->trans("SellByDate").''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print '' . $langs->trans("EatByDate") . ''; + } + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print '' . $langs->trans("SellByDate") . ''; + } } print ''.$langs->trans("QtyDispatched").''; print ''.$langs->trans("Warehouse").''; @@ -1174,8 +1197,12 @@ if ($id > 0 || !empty($ref)) { $lot=new Productlot($db); $lot->fetch(0, $objp->pid, $objp->batch); print ''.$lot->getNomUrl(1).''; - print ''.dol_print_date($lot->eatby, 'day').''; - print ''.dol_print_date($lot->sellby, 'day').''; + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print '' . dol_print_date($lot->eatby, 'day') . ''; + } + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print '' . dol_print_date($lot->sellby, 'day') . ''; + } } else { print ''; print ''; diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index 56516b440f7..e266a466e87 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -43,7 +43,7 @@ $langs->loadLangs(array("bills", "orders", "sendings", "companies", "deliveries" $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check diff --git a/htdocs/fourn/commande/info.php b/htdocs/fourn/commande/info.php index 195e87e5b5d..07c84a8fa12 100644 --- a/htdocs/fourn/commande/info.php +++ b/htdocs/fourn/commande/info.php @@ -38,7 +38,7 @@ $langs->loadLangs(array("suppliers", "orders", "companies", "stocks")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index a792d68fc6b..fb2e18a0de2 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -7,7 +7,7 @@ * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2018 Frédéric France - * Copyright (C) 2018 Charlene Benke + * Copyright (C) 2018-2020 Charlene Benke * Copyright (C) 2019 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify @@ -35,6 +35,7 @@ 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.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; @@ -66,7 +67,7 @@ $search_refsupp = GETPOST('search_refsupp', 'alpha'); $search_company = GETPOST('search_company', 'alpha'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); -$search_state = trim(GETPOST("search_state", 'alpha')); +$search_state = GETPOST("search_state", 'alpha'); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_user = GETPOST('search_user', 'int'); @@ -130,6 +131,9 @@ $fieldstosearchall = array( 'cf.ref_supplier'=>'RefSupplierOrder', 'pd.description'=>'Description', 's.nom'=>"ThirdParty", + 's.name_alias'=>"AliasNameShort", + 's.zip'=>"Zip", + 's.town'=>"Town", 'cf.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["cf.note_private"] = "NotePrivate"; @@ -180,7 +184,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $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 @@ -244,7 +248,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // TODO Move this into mass action include - if ($massaction == 'confirm_createbills') + if ($massaction == 'confirm_createsupplierbills') { $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); @@ -258,34 +262,36 @@ if (empty($reshook)) $db->begin(); foreach ($orders as $id_order) { - $cmd = new Commande($db); + $cmd = new CommandeFournisseur($db); if ($cmd->fetch($id_order) <= 0) continue; - $object = new Facture($db); - if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + $objecttmp = new FactureFournisseur($db); + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. else { - $object->socid = $cmd->socid; - $object->type = Facture::TYPE_STANDARD; - $object->cond_reglement_id = $cmd->cond_reglement_id; - $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; + $objecttmp->socid = $cmd->socid; + $objecttmp->type = $objecttmp::TYPE_STANDARD; + $objecttmp->cond_reglement_id = $cmd->cond_reglement_id; + $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; - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (empty($datefacture)) { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + $datefacture = dol_now(); } - $object->date = $datefacture; - $object->origin = 'commande'; - $object->origin_id = $id_order; + $objecttmp->date = $datefacture; + $objecttmp->origin = 'order_supplier'; + $objecttmp->origin_id = $id_order; - $res = $object->create($user); + $res = $objecttmp->create($user); if ($res > 0) $nb_bills_created++; } - if ($object->id > 0) + if ($objecttmp->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql .= "fk_source"; @@ -294,9 +300,9 @@ if (empty($reshook)) $sql .= ", targettype"; $sql .= ") VALUES ("; $sql .= $id_order; - $sql .= ", '".$object->origin."'"; - $sql .= ", ".$object->id; - $sql .= ", '".$object->element."'"; + $sql .= ", '".$db->escape($objecttmp->origin)."'"; + $sql .= ", ".$objecttmp->id; + $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; if (!$db->query($sql)) @@ -323,7 +329,7 @@ if (empty($reshook)) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); - $discount->fk_soc = $object->socid; + $discount->fk_soc = $objecttmp->socid; $discount->amount_ht = abs($lines[$i]->total_ht); $discount->amount_tva = abs($lines[$i]->total_tva); $discount->amount_ttc = abs($lines[$i]->total_ttc); @@ -333,7 +339,7 @@ if (empty($reshook)) $discountid = $discount->create($user); if ($discountid > 0) { - $result = $object->insert_discount($discountid); + $result = $objecttmp->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { setEventMessages($discount->error, $discount->errors, 'errors'); @@ -358,32 +364,31 @@ if (empty($reshook)) { $fk_parent_line = 0; } - $result = $object->addline( + $result = $objecttmp->addline( $desc, $lines[$i]->subprice, - $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, + $lines[$i]->qty, $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, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, + $lines[$i]->rang, + false, + $lines[$i]->array_options, + $lines[$i]->fk_unit, + $objecttmp->origin_id, $lines[$i]->pa_ht, - $lines[$i]->label - ); + $lines[$i]->ref_supplier, + $lines[$i]->special_code, + $fk_parent_line + ); if ($result > 0) { $lineid = $result; @@ -404,8 +409,8 @@ 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] = $object; - else $TFact[$object->id] = $object; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp; + else $TFact[$objecttmp->id] = $objecttmp; } // Build doc with all invoices @@ -415,38 +420,67 @@ if (empty($reshook)) if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$object) + foreach ($TAllFact as &$objecttmp) { - $object->validate($user); + $objecttmp->validate($user); if ($result <= 0) { $error++; - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); break; } - $id = $object->id; // For builddoc action + $id = $objecttmp->id; // For builddoc action // Fac builddoc $donotredirect = 1; - $upload_dir = $conf->facture->dir_output; - $permissiontoadd = $user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + $upload_dir = $conf->fournisseur->facture->dir_output; + $permissiontoadd = $user->rights->fournisseur->facture->creer; + //include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } - $massaction = $action = 'confirm_createbills'; + $massaction = $action = 'confirm_createsupplierbills'; } if (!$error) { $db->commit(); setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs'); + + // 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); + + header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); + exit; } else { $db->rollback(); $action = 'create'; $_GET["origin"] = $_POST["origin"]; $_GET["originid"] = $_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages("Error", null, 'errors'); $error++; } } @@ -503,7 +537,7 @@ if (!empty($extrafields->attributes[$object->table_element]['label'])) { } // Add fields from hooks $parameters = array(); -$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; @@ -522,6 +556,9 @@ if ($search_user > 0) $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook +$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; @@ -535,16 +572,16 @@ if ($search_billed != '' && $search_billed >= 0) $sql .= " AND cf.billed = ".$db 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') !== '') - $sql .= " AND cf.fk_statut IN (".$db->escape($db->escape(GETPOST('statut', 'intcomma'))).")"; + $sql .= " AND cf.fk_statut IN (".$db->sanitize($db->escape(GETPOST('statut', 'intcomma'))).")"; if ($search_status != '' && $search_status >= 0) - $sql .= " AND cf.fk_statut IN (".$db->escape($search_status).")"; + $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->escape($search_country).')'; -if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$db->escape($search_type_thirdparty).')'; +if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +if ($search_type_thirdparty) $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); @@ -561,11 +598,12 @@ if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_r 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 +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); +// Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -579,6 +617,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } $sql .= $db->plimit($limit + 1, $offset); +//print $sql; $resql = $db->query($sql); if ($resql) @@ -607,23 +646,24 @@ if ($resql) llxHeader('', $title, $help_url); $param = ''; - if ($socid > 0) $param .= '&socid='.$socid; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; - if ($sall) $param .= "&search_all=".$sall; - if ($search_orderday) $param .= '&search_orderday='.$search_orderday; - if ($search_ordermonth) $param .= '&search_ordermonth='.$search_ordermonth; - if ($search_orderyear) $param .= '&search_orderyear='.$search_orderyear; - if ($search_deliveryday) $param .= '&search_deliveryday='.$search_deliveryday; - if ($search_deliverymonth) $param .= '&search_deliverymonth='.$search_deliverymonth; - if ($search_deliveryyear) $param .= '&search_deliveryyear='.$search_deliveryyear; - if ($search_ref) $param .= '&search_ref='.$search_ref; - if ($search_company) $param .= '&search_company='.$search_company; - if ($search_user > 0) $param .= '&search_user='.$search_user; - if ($search_request_author) $param .= '&search_request_author='.$search_request_author; - if ($search_sale > 0) $param .= '&search_sale='.$search_sale; - if ($search_total_ht != '') $param .= '&search_total_ht='.$search_total_ht; - if ($search_total_ttc != '') $param .= "&search_total_ttc=".$search_total_ttc; + 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); @@ -638,32 +678,35 @@ if ($resql) // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + $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( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), - 'presend'=>$langs->trans("SendByMail"), + 'presend'=>$langs->trans("SendByMail"), ); - //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); + if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton = ''; - if ($user->rights->fournisseur->commande->creer) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/commande/card.php?action=create'); - } + $url = DOL_URL_ROOT.'/fourn/commande/card.php?action=create'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->commande->creer); - // Fields title search - print ''; + // Lines of title fields + print ''; if ($optioncss != '') print ''; print ''; print ''; print ''; - print ''; print ''; print ''; + print ''; + print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'supplier_order', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -676,11 +719,11 @@ if ($resql) if ($massaction == 'createbills') { //var_dump($_REQUEST); - print ''; + print ''; - print ''; + print '
    '; print ''; - print ''; print '
    '; + print ''; print $langs->trans('DateInvoice'); print ''; @@ -739,7 +782,7 @@ if ($resql) $moreforfilter .= ''; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($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 .= '
    '; @@ -762,7 +805,17 @@ 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); + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + + if (GETPOST('autoselectall', 'int')) { + $selectedfields .= ''; + } print '
    '; print ''."\n"; @@ -771,17 +824,17 @@ if ($resql) // Ref if (!empty($arrayfields['cf.ref']['checked'])) { - print ''; + print ''; } // Ref customer if (!empty($arrayfields['cf.ref_supplier']['checked'])) { - print ''; + print ''; } // Project ref if (!empty($arrayfields['p.project_ref']['checked'])) { - print ''; + print ''; } // Request author if (!empty($arrayfields['u.login']['checked'])) @@ -935,9 +988,10 @@ if ($resql) print "\n"; + // Fields title print ''; 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); + 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); @@ -985,6 +1039,12 @@ if ($resql) { $obj = $db->fetch_object($resql); + $notshippable = 0; + $warning = 0; + $text_info = ''; + $text_warning = ''; + $nbprod = 0; + $objectstatic->id = $obj->rowid; $objectstatic->ref = $obj->ref; $objectstatic->ref_supplier = $obj->ref_supplier; @@ -1222,23 +1282,26 @@ if ($resql) if (!$i) $totalarray['nbfield']++; print "\n"; + + $total += $obj->total_ht; + $subtotal += $obj->total_ht; $i++; } // Show total line include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - - $parameters = array('arrayfields'=>$arrayfields, '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 "\n"; - $db->free($resql); + $parameters = array('arrayfields'=>$arrayfields, '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 ''."\n"; + $hidegeneratedfilelistifempty = 1; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; diff --git a/htdocs/fourn/commande/orderstoinvoice.php b/htdocs/fourn/commande/orderstoinvoice.php deleted file mode 100644 index d7f8ef489ab..00000000000 --- a/htdocs/fourn/commande/orderstoinvoice.php +++ /dev/null @@ -1,635 +0,0 @@ - - * Copyright (C) 2004-2013 Laurent Destailleur - * Copyright (C) 2005 Marc Barilley / Ocebo - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2012 Andreu Bisquerra Gaya - * Copyright (C) 2012 David Rodriguez Martinez - * Copyright (C) 2012-2017 Juanjo Menent - * Copyright (C) 2014 Florian Henry - * Copyright (C) 2015 Marcos García - * Copyright (C) 2018 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 htdocs/fourn/commande/orderstoinvoice.php - * \ingroup commande - * \brief Page to invoice multiple supplier orders - */ -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; -if (!empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; -} - -// Load translation files required by the page -$langs->loadLangs(array("orders", "companies", "deliveries")); - -if (!$user->rights->fournisseur->facture->creer) - accessforbidden(); - -$id = (GETPOST('id') ? GETPOST('id', 'int') : GETPOST("facid")); // For backward compatibility -$ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); -$confirm = GETPOST('confirm', 'alpha'); -$sref = GETPOST('sref'); -$sref_client = GETPOST('sref_client'); -$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$socid = GETPOST('socid', 'int'); -$selected = GETPOST('orders_to_invoice'); -$sortfield = GETPOST("sortfield", 'alpha'); -$sortorder = GETPOST("sortorder", 'alpha'); -$search_status = GETPOST('search_status'); - -if (!$sortfield) - $sortfield = 'c.rowid'; -if (!$sortorder) - $sortorder = 'DESC'; - -$now = dol_now(); -$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server -$date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]); -$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server -$date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]); - -$extrafields = new ExtraFields($db); - -$object = new FactureFournisseur($db); - -// fetch optionals attributes and labels -$extrafields->fetch_name_optionals_label($object->table_element); - -if ($action == 'create') -{ - if (!GETPOST('createbill')) - { - $action = ''; - } else { - if (!is_array($selected)) - { - //$error++; - setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors'); - $action = ''; - } else { - $origin = GETPOST('origin', 'alpha'); - $originid = GETPOST('originid', 'int'); - } - } -} - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; -$hookmanager = new HookManager($db); -$hookmanager->initHooks(array('orderstoinvoicesupplier')); - - -/* - * Actions - */ - -if (($action == 'create' || $action == 'add') && !$error) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.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("bills", "main", "products")); - - if (isset($_GET['orders_to_invoice'])) { - $orders_id = GETPOST('orders_to_invoice', '', 1); - $n = count($orders_id); - $i = 0; - - $originid = $orders_id[0]; - $_GET['originid'] = $orders_id[0]; - } - if (isset($_POST['orders_to_invoice'])) { - $orders_id = GETPOST('orders_to_invoice', '', 2); - $nn = count($orders_id); - $ii = 0; - - $originid = $orders_id[0]; - $_POST['originid'] = $orders_id[0]; - } - - $projectid = GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0; - $lineid = GETPOST('lineid', 'int'); - $userid = GETPOST('userid', 'int'); - $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref') : GETPOST('search_ref'); - - // Security check - if ($user->socid) - $socid = $user->socid; - $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); - - $usehm = $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE; - $object = new FactureFournisseur($db); - - // Insert new invoice in database - if ($action == 'add' && $user->rights->fournisseur->facture->creer) { - $object->socid = GETPOST('socid'); - $db->begin(); - $error = 0; - - // Standard or deposit or proforma invoice - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } - if (!$error) { - $object->ref = GETPOST('ref', 'nohtml'); - $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); - $object->socid = GETPOST('socid', 'int'); - $object->libelle = (GETPOSTISSET('libelle') ? GETPOST('libelle', 'nohtml') : GETPOST('label', 'nohtml')); - $object->label = (GETPOSTISSET('libelle') ? GETPOST('libelle', 'nohtml') : GETPOST('label', 'nohtml')); - $object->date = $datefacture; - $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); - $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $projectid = GETPOST('projectid', 'int'); - if ($projectid > 0) - $object->fk_project = $projectid; - - // Auto calculation of date due if not filled by user - if (empty($object->date_echeance)) - $object->date_echeance = $object->calculate_date_lim_reglement(); - - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - - if ($_POST['origin'] && $_POST['originid']) { - $linked_orders_ids = array(); - foreach ($orders_id as $origin => $origin_id) { - $origin_id = (!empty($origin_id) ? $origin_id : $orders_id[$ii]); - $linked_orders_ids[] = $origin_id; - } - $object->linked_objects = array(GETPOST('origin')=>$linked_orders_ids); - $id = $object->create($user); - - if ($id > 0) { - while ($ii < $nn) { - $objectsrc = new CommandeFournisseur($db); - dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result = $objectsrc->fetch($orders_id[$ii]); - if ($result > 0) { - $lines = $objectsrc->lines; - if (empty($lines) && method_exists($objectsrc, 'fetch_lines')) { - $objectsrc->fetch_lines(); - $lines = $objectsrc->lines; - } - $fk_parent_line = 0; - $num = count($lines); - for ($i = 0; $i < $num; $i++) { - $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - - $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); - - // 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; - $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) { - $fk_parent_line = 0; - } - // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example. - $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->qty, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, 'HT', $product_type, -1, false, 0, $lines[$i]->fk_unit, $line[$i]->id); - - if ($result > 0) { - $lineid = $result; - } else { - $lineid = 0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) { - $fk_parent_line = $result; - } - } - } else { - $mesgs[] = $objectsrc->error; - $error++; - } - $ii++; - } - } else { - $mesgs[] = $object->error; - $error++; - } - } - } - - // End of object creation, we show it - if ($id > 0 && !$error) { - foreach ($orders_id as $fk_supplier_order) { - $supplier_order = new CommandeFournisseur($db); - if ($supplier_order->fetch($fk_supplier_order) > 0 && $supplier_order->statut == 5) - { - if ($supplier_order->classifyBilled($user) < 0) - { - $db->rollback(); - $action = 'create'; - $_GET["origin"] = $_POST["origin"]; - $_GET["originid"] = $_POST["originid"]; - $mesgs[] = '
    '.$object->error.'
    '; - - $error++; - break; - } - } - } - - if (!$error) { - $db->commit(); - header('Location: '.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$id); - exit(); - } - } else { - $db->rollback(); - $action = 'create'; - $_GET["origin"] = $_POST["origin"]; - $_GET["originid"] = $_POST["originid"]; - $mesgs[] = '
    '.$object->error.'
    '; - } - } -} - -/* - * View - */ - -$html = new Form($db); -$htmlother = new FormOther($db); -$formfile = new FormFile($db); - -// Mode creation -if ($action == 'create' && !$error) { - llxHeader(); - print load_fiche_titre($langs->trans('NewBill')); - - $soc = new Societe($db); - if ($socid) - $res = $soc->fetch($socid); - if ($res) { - $cond_reglement_id = $soc->cond_reglement_supplier_id; - $mode_reglement_id = $soc->mode_reglement_supplier_id; - } - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ? -1 : ''; - - $objectsrc = new CommandeFournisseur($db); - $listoforders = array(); - foreach ($selected as $sel) { - $result = $objectsrc->fetch($sel); - if ($result > 0) { - $listoforders[] = $objectsrc->ref; - } - - if (empty($cond_reglement_id)) $cond_reglement_id = $objectsrc->cond_reglement_id; - if (empty($mode_reglement_id)) $mode_reglement_id = $objectsrc->mode_reglement_id; - } - - print '
    '; - print ''; - print ''; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - - print ''; - - // Ref - print ''; - - // Ref supplier - print ''; - print ''; - - // Date invoice - print ''; - // Payment term - print ''; - // Payment mode - print ''; - // Project - if (!empty($conf->projet->enabled)) { - $formproject = new FormProjets($db); - - $langs->load('projects'); - print ''; - } - - // Other attributes - $parameters = array( - 'objectsrc' => $objectsrc, - 'idsrc' => $listoforders - ); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - if (empty($reshook)) - { - $object = new FactureFournisseur($db); - print $object->showOptionals($extrafields, 'edit'); - } - - // Modele PDF - print ''; - print '"; - - // Public note - print ''; - print ''; - print ''; - - // Private note - if (empty($user->socid)) { - print ''; - print ''; - print ''; - } - - print '
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('Date').''; - print $html->selectDate('', '', '', '', '', "add", 1, 1); - print '
    '.$langs->trans('PaymentConditionsShort').''; - $html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); - print '
    '.$langs->trans('PaymentMode').''; - $html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); - print '
    '.$langs->trans('Project').''; - $formproject->select_projects($soc->id, $projectid, 'projectid'); - print '
    '.$langs->trans('Model').''; - $liste = ModelePDFSuppliersInvoices::liste_modeles($db); - print $html->selectarray('model', $liste, $conf->global->INVOICE_SUPPLIER_ADDON_PDF); - print "
    '.$langs->trans('NotePublic').''; - print '
    '.$langs->trans('NotePrivate').''; - print '
    '; - - while ($i < $n) { - print ''; - - $i++; - } - - // Button "Create Draft" - print '
    '; - print "
    \n"; - - print ''; - print "\n"; -} - -// Mode liste -if (($action != 'create' && $action != 'add') && !$error) { - llxHeader(); - ?> - - rights->societe->client->voir && !$socid) - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ' WHERE c.entity = '.$conf->entity; - $sql .= ' AND c.fk_soc = s.rowid'; - - // Show orders we can bill - if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) - { - $sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY.")"; // Must match filter in htdocs/fourn/card.php - } else { - // CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.", ".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY - $sql .= " AND c.fk_statut IN (".$db->escape($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS).")"; - } - - $sql .= " AND c.billed = 0"; - - // Find order that are not already invoiced - //No need due to the billed status - //$sql .= " AND c.rowid NOT IN (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE targettype='invoice_supplier')"; - - 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 ($sref) { - $sql .= natural_search("c.ref", $sref); - } - if ($sall) { - $sql .= natural_search(array("c.ref", "c.note"), $sall); - } - - // Date filter - //$sql.= dolSqlDateFilter("c.date_commande", GETPOST("date_startday", 'int'), GETPOST("date_startmonth", 'int'), GETPOST("date_startyear", 'int')); - //$sql.= dolSqlDateFilter("c.date_livraison", $search_deliveryday, $search_deliverymonth, $search_deliveryyear); - if ($date_start) - $sql .= " AND c.date_commande >= '".$db->idate($date_start)."'"; - if ($date_end) - $sql .= " AND c.date_commande <= '".$db->idate($date_end)."'"; - if ($date_starty) - $sql .= " AND c.date_livraison >= '".$db->idate($date_starty)."'"; - if ($date_endy) - $sql .= " AND c.date_livraison <= '".$db->idate($date_endy)."'"; - - if (!empty($sref_client)) { - $sql .= natural_search('c.ref_supplier', $sref_client); - } - $sql .= ' ORDER BY '.$sortfield.' '.$sortorder; - dol_syslog('fourn/commande/ordertoinvoice.php sql='.$sql); - $resql = $db->query($sql); - - if ($resql) { - if ($socid) { - $soc = new Societe($db); - $soc->fetch($socid); - } - $title = $langs->trans('ListOfSupplierOrders'); - $title .= ' - '.$langs->trans('StatusOrderReceivedAllShort'); - $title .= ' - '.$soc->getNomUrl(1, 'supplier'); - - $num = $db->num_rows($resql); - - print load_fiche_titre($title); - - $i = 0; - $period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0); - $periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0); - - print '
    '; - print ''; - print ''; - - - print ''; - print ''; - print_liste_field_titre('Ref', 'orderstoinvoice.php', 'c.ref', '', '&socid='.$socid, '', $sortfield, $sortorder); - print_liste_field_titre('RefSupplier', 'orderstoinvoice.php', 'c.ref_supplier', '', '&socid='.$socid, '', $sortfield, $sortorder); - print_liste_field_titre('OrderDate', 'orderstoinvoice.php', 'c.date_commande', '', '&socid='.$socid, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre('DeliveryDate', 'orderstoinvoice.php', 'c.date_livraison', '', '&socid='.$socid, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre('Status', '', '', '', '', '', '', '', 'right '); - print_liste_field_titre('GenerateBill', '', '', '', '', '', '', '', 'center '); - print "\n"; - - // Fields title search - print ''; - - print ''; - - // print ''; - - // DATE ORDER - print ''; - - // DATE DELIVERY - print ''; - - // SEARCH BUTTON - print ''; - - // ALL/NONE - print ''; - - print ''; - - $generic_commande = new CommandeFournisseur($db); - - while ($i < $num) { - $objp = $db->fetch_object($resql); - - print ''; - print ''; - - print ''; - - // Order date - print ''; - - // Delivery date - print ''; - - // Statut - print ''; - - // Checkbox - print ''; - - print ''; - - $total = $total + $objp->price; - $subtotal = $subtotal + $objp->price; - $i++; - } - print '
    '; - // REF - print ''; - print ''; - print ''; - print ''; - print ''; - print $period; - print ''; - print $periodely; - print ''; - print ''; - print ''; - if ($conf->use_javascript_ajax) - print ''.$langs->trans("All").' / '.$langs->trans("None").''; - print '
    '; - - $generic_commande->id = $objp->rowid; - $generic_commande->ref = $objp->ref; - - print ''; - print ''; - - print '
    '; - print $generic_commande->getNomUrl(1, $objp->fk_statut); - print ''; - $filename = dol_sanitizeFileName($objp->ref); - $filedir = $conf->fournisseur->commande->dir_output.'/'.dol_sanitizeFileName($objp->ref); - $urlsource = $_SERVER['PHP_SELF'].'?id='.$objp->rowid; - print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); - print '
    '; - print '
    '.$objp->ref_supplier.''; - print dol_print_date($db->jdate($objp->date_commande), 'day'); - print ''; - print dol_print_date($db->jdate($objp->date_livraison), 'day'); - print ''.$generic_commande->LibStatut($objp->fk_statut, 5).''; - print ''; - print '
    '; - - /* - * Boutons actions - */ - print '
    '; - print '
    '; - print ''; - print ''; - print '
    '; - // print ''.$langs->trans("GoBack").''; - print ''; - print '
    '; - print '
    '; - - print '
    '; - - $db->free($resql); - } else { - dol_print_error($db); - } -} - -dol_htmloutput_mesg($mesg, $mesgs); - -// End of page -llxFooter(); -$db->close(); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index b98405c4130..c42bf1c3991 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -153,21 +153,21 @@ if (empty($reshook)) // Action clone object 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 = 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'); - $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); + 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) - { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); - exit; - } else { - $langs->load("errors"); - setEventMessages($objectutil->error, $objectutil->errors, 'errors'); - $action = ''; - } + $result = $objectutil->createFromClone($user, $id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } else { + $langs->load("errors"); + setEventMessages($objectutil->error, $objectutil->errors, 'errors'); + $action = ''; + } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse'); @@ -212,7 +212,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -259,7 +259,7 @@ if (empty($reshook)) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -309,7 +309,7 @@ if (empty($reshook)) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } } @@ -446,7 +446,7 @@ if (empty($reshook)) } $ret = $object->fetch($id); // Reload to get new records - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } } @@ -657,8 +657,8 @@ if (empty($reshook)) $object->libelle = GETPOST('label', 'nohtml'); $object->date = $datefacture; $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); + $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->note_private = GETPOST('note_private', 'restricthtml'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); @@ -723,8 +723,8 @@ if (empty($reshook)) $object->label = GETPOST('label', 'nohtml'); $object->date = $datefacture; $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); + $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->note_private = GETPOST('note_private', 'restricthtml'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); @@ -836,8 +836,8 @@ if (empty($reshook)) $object->libelle = $_POST['label']; $object->date = $datefacture; $object->date_echeance = $datedue; - $object->note_public = GETPOST('note_public', 'none'); - $object->note_private = GETPOST('note_private', 'none'); + $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->note_private = GETPOST('note_private', 'restricthtml'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); $object->fk_account = GETPOST('fk_account', 'int'); @@ -1029,7 +1029,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) { dol_print_error($db, $object->error, $object->errors); @@ -1050,7 +1050,7 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if (GETPOST('price_ht') != '') { @@ -1066,7 +1066,7 @@ if (empty($reshook)) $productsupplier = new ProductFournisseur($db); if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { - if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), GETPOST('productid'), 'none', GETPOST('socid', 'int')) < 0) + 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'); } @@ -1086,17 +1086,17 @@ 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')); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $tva_tx)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $tva_tx)) + $info_bits |= 0x01; - // Define vat_rate - $tva_tx = str_replace('*', '', $tva_tx); - $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + // Define vat_rate + $tva_tx = str_replace('*', '', $tva_tx); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $remise_percent = GETPOST('remise_percent'); + $remise_percent = GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); // Extrafields Lines @@ -1109,12 +1109,12 @@ if (empty($reshook)) } } - $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); - if ($result >= 0) - { - unset($_POST['label']); - unset($_POST['fourn_ref']); - unset($_POST['date_starthour']); + $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); + if ($result >= 0) + { + unset($_POST['label']); + unset($_POST['fourn_ref']); + unset($_POST['date_starthour']); unset($_POST['date_startmin']); unset($_POST['date_startsec']); unset($_POST['date_startday']); @@ -1259,7 +1259,7 @@ if (empty($reshook)) // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { - $desc = $productsupplier->desc_supplier; + $desc = $productsupplier->desc_supplier; } else $desc = $productsupplier->description; if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); @@ -1310,8 +1310,8 @@ if (empty($reshook)) $array_options, $productsupplier->fk_unit, 0, - $pu_ht_devise, - $ref_supplier, + $pu_ht_devise, + $ref_supplier, '' ); } @@ -1375,7 +1375,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -1439,34 +1439,34 @@ if (empty($reshook)) if (!$ventilExportCompta) { - // On verifie si aucun paiement n'a ete effectue + // On verifie si aucun paiement n'a ete effectue if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) - { - $idwarehouse = GETPOST('idwarehouse'); + { + $idwarehouse = GETPOST('idwarehouse'); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $qualified_for_stock_change = 0; - 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 = 0; + 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) - { - $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action = ''; - } - } + // 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) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action = ''; + } + } - $object->setDraft($user, $idwarehouse); + $object->setDraft($user, $idwarehouse); // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) @@ -1479,7 +1479,7 @@ if (empty($reshook)) $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $model = $object->modelpdf; + $model = $object->model_pdf; $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); @@ -1543,7 +1543,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -1782,7 +1782,9 @@ if ($action == 'create') print ''; // Ref supplier - print ''.$langs->trans('RefSupplier').''; + print ''.$langs->trans('RefSupplier').'id > 0) print ' autofocus'; + print '>'; print ''; print ''.$langs->trans('Type').''; @@ -2024,9 +2026,12 @@ if ($action == 'create') print ''; // Bank Account - print ''.$langs->trans('BankAccount').''; - $form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1); - print ''; + if (!empty($conf->banque->enabled)) + { + print ''.$langs->trans('BankAccount').''; + $form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1); + print ''; + } // Multicurrency if (!empty($conf->multicurrency->enabled)) @@ -2071,16 +2076,16 @@ if ($action == 'create') // Public note print ''.$langs->trans('NotePublic').''; print ''; - $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'none') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print ''; - // print ''; + // print ''; print ''; // Private note print ''.$langs->trans('NotePrivate').''; print ''; - $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'none') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'restricthtml') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print ''; // print ''; @@ -2256,8 +2261,8 @@ if ($action == 'create') { // Create an array for form $formquestion = array( - array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), - array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) + array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), + array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) ); // Ask confirmation to clone $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250); @@ -2294,59 +2299,59 @@ 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) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } + 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); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1); - } + } - // Confirmation edit (back to draft) - if ($action == 'edit') - { - $formquestion = array(); + // Confirmation edit (back to draft) + if ($action == 'edit') + { + $formquestion = array(); - $qualified_for_stock_change = 0; - 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) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); + $qualified_for_stock_change = 0; + 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) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); } // Confirmation set paid @@ -2360,7 +2365,7 @@ if ($action == 'create') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); } - if ($action == 'deletepaiement') + 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); @@ -2384,109 +2389,109 @@ if ($action == 'create') print $formconfirm; - // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + // Supplier invoice card + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
    '; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, '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 .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - 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 .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $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 .= '
    '; + $morehtmlref = '
    '; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, '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 .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + 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 .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $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 .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - // Type - print ''; + $facidavoir = $object->getListIdAvoirFromInvoice(); + if (count($facidavoir) > 0) + { + print ' ('.$langs->transnoentities("InvoiceHasAvoir"); + $i = 0; + 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) + { + $facthatreplace = new FactureFournisseur($db); + $facthatreplace->fetch($facidnext); + print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $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')).'
    '; + } + } + print ''; - // Relative and absolute discounts + // Relative and absolute discounts print ''; - // Label - print ''; - print ''; - print ''; - print ''; + // Label + print ''; + print ''; + print ''; + print ''; - $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); + $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); - // Date - print ''; + // Date + print ''; // Default terms of the settlement $langs->load('bills'); @@ -2607,21 +2612,24 @@ if ($action == 'create') } // Bank Account - print '"; + print ''; } - print ""; - print ''; // Incoterms if (!empty($conf->incoterm->enabled)) @@ -2749,7 +2757,7 @@ if ($action == 'create') if ($societe->localtax1_assuj == "1") $nbrows++; if ($societe->localtax2_assuj == "1") $nbrows++; - $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; + $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,'; $sql .= ' pf.amount,'; $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; @@ -2787,7 +2795,7 @@ if ($action == 'create') $paymentstatic->id = $objp->rowid; $paymentstatic->datepaye = $db->jdate($objp->dp); $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid); - $paymentstatic->num_paiement = $objp->num_paiement; + $paymentstatic->num_payment = $objp->num_payment; $paymentstatic->payment_code = $objp->payment_code; print ''; @@ -2796,7 +2804,7 @@ if ($action == 'create') print ''; print ''; print ''; if (!empty($conf->banque->enabled)) { @@ -2821,7 +2829,7 @@ if ($action == 'create') print ''; + print ''; print ''; print ''; } - if ($societe->localtax2_assuj == "1") //Localtax2 + if ($mysoc->localtax2_assuj == "1") //Localtax2 { - print ''; + print ''; print ''; print ''; } @@ -252,9 +252,26 @@ if ($object->id > 0) $permission = $user->rights->fournisseur->facture->creer; $permtoedit = $user->rights->fournisseur->facture->creer; $param = '&facid='.$object->id; - include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; + + $defaulttpldir = '/core/tpl'; + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) + { + if (!empty($module)) { + $tpl = dol_buildpath($reldir.'/document_actions_post_headers.tpl.php'); + } else { + $tpl = DOL_DOCUMENT_ROOT.$reldir.'/document_actions_post_headers.tpl.php'; + } + + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; + } else { + $res = include $tpl; // for debug + } + if ($res) break; + } } else { - print $langs->trans('ErrorUnknown'); + print $langs->trans('ErrorUnknown'); } // End of page diff --git a/htdocs/fourn/facture/impayees.php b/htdocs/fourn/facture/impayees.php index b37de34301d..804a78079d3 100644 --- a/htdocs/fourn/facture/impayees.php +++ b/htdocs/fourn/facture/impayees.php @@ -116,26 +116,26 @@ if ($user->rights->fournisseur->facture->lire) if ($search_ref) { - $sql .= " AND f.ref LIKE '%".$search_ref."%'"; + $sql .= " AND f.ref LIKE '%".$db->escape($search_ref)."%'"; } if ($search_ref_supplier) { - $sql .= " AND f.ref_supplier LIKE '%".$search_ref_supplier."%'"; + $sql .= " AND f.ref_supplier LIKE '%".$db->escape($search_ref_supplier)."%'"; } if ($search_company) { - $sql .= " AND s.nom LIKE '%".$search_company."%'"; + $sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'"; } if ($search_amount_no_tax) { - $sql .= " AND f.total_ht = '".$search_amount_no_tax."'"; + $sql .= " AND f.total_ht = '".$db->escape($search_amount_no_tax)."'"; } if ($search_amount_all_tax) { - $sql .= " AND f.total_ttc = '".$search_amount_all_tax."'"; + $sql .= " AND f.total_ttc = '".$db->escape($search_amount_all_tax)."'"; } if (dol_strlen(GETPOST('sf_re')) > 0) diff --git a/htdocs/fourn/facture/index.php b/htdocs/fourn/facture/index.php index df32ee1b19a..c3272544371 100644 --- a/htdocs/fourn/facture/index.php +++ b/htdocs/fourn/facture/index.php @@ -51,7 +51,7 @@ $maxOpenCount = empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->glob llxHeader("", $langs->trans("SupplierInvoicesArea"), 'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); -print load_fiche_titre($langs->trans("SupplierInvoicesArea"), '', 'invoicing'); +print load_fiche_titre($langs->trans("SupplierInvoicesArea"), '', 'bill'); print '
    '; diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 16fffbcbea4..2a63e040434 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -49,7 +49,7 @@ if (!$user->rights->fournisseur->facture->lire) accessforbidden(); // Load translation files required by the page $langs->loadLangs(array('products', 'bills', 'companies', 'projects')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); @@ -67,7 +67,7 @@ if ($user->socid > 0) $socid = $user->socid; } -$mode = GETPOST("mode"); +$mode = GETPOST("mode", 'aZ09'); $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_label = GETPOST("search_label", "alpha"); @@ -92,9 +92,10 @@ $search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', $search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $search_status = GETPOST('search_status', 'int'); $search_paymentmode = GETPOST('search_paymentmode', 'int'); +$search_paymentcond = GETPOST('search_paymentcond', 'int'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); -$search_state = trim(GETPOST("search_state")); +$search_state = GETPOST("search_state"); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_user = GETPOST('search_user', 'int'); @@ -165,12 +166,13 @@ $arrayfields = array( 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj == "1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj == "1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>1, 'position'=>50), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1, 'position'=>52), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1, 'position'=>105), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0, 'position'=>110), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj == "1", 'position'=>95), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj == "1", 'position'=>100), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0, 'position'=>115), 'u.login'=>array('label'=>"Author", 'checked'=>1), 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), @@ -240,6 +242,7 @@ if (empty($reshook)) $search_multicurrency_montant_ttc = ''; $search_status = ''; $search_paymentmode = ''; + $search_paymentcond = ''; $search_town = ''; $search_zip = ""; $search_state = ""; @@ -318,6 +321,7 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count 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"; @@ -326,7 +330,6 @@ if ($search_user > 0) $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } -$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user AS u ON f.fk_user_author = u.rowid'; $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; @@ -367,7 +370,8 @@ if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurr 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 = ".$search_paymentmode.""; +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)."'"; @@ -385,7 +389,7 @@ if ($filter && $filter != -1) $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 = ".$db->escape($search_sale); +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; @@ -508,11 +512,9 @@ if ($resql) if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton = ''; - if ($user->rights->fournisseur->facture->creer) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/fourn/facture/card.php?action=create'); - } + $url = DOL_URL_ROOT.'/fourn/facture/card.php?action=create'; + if (!empty($socid)) $url .= '&socid='.$socid; + $newcardbutton = dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->facture->creer); $i = 0; print '
    '."\n"; @@ -597,7 +599,7 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($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 .= '
    '; @@ -722,11 +724,18 @@ if ($resql) 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)); print ''; } + // Condition of payment + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + print '
    '; + } // Payment mode if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''; } if (!empty($arrayfields['f.total_ht']['checked'])) @@ -875,6 +884,7 @@ if ($resql) 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 '); @@ -1098,6 +1108,14 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } + // Payment condition + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Payment mode if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index 48d84a3161b..57a0cd103ab 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -37,7 +37,7 @@ $langs->loadLangs(array("bills", "companies")); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index db5bc9acfb5..8c2fdbdb5b6 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -129,7 +129,8 @@ if (empty($reshook)) $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $paiement_id = 0; $totalpayment = 0; - $atleastonepaymentnotnull = 0; + $atleastonepaymentnotnull = 0; + $multicurrency_totalpayment = 0; // Generate payment array and check if there is payment higher than invoice and payment date before invoice date $tmpinvoice = new FactureFournisseur($db); @@ -138,7 +139,7 @@ if (empty($reshook)) if (substr($key, 0, 7) == 'amount_') { $cursorfacid = substr($key, 7); - $amounts[$cursorfacid] = price2num(trim(GETPOST($key))); + $amounts[$cursorfacid] = price2num(GETPOST($key)); if (!empty($amounts[$cursorfacid])) { $atleastonepaymentnotnull++; if (is_numeric($amounts[$cursorfacid])) { @@ -171,7 +172,7 @@ if (empty($reshook)) } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); - $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key))); + $multicurrency_amounts[$cursorfacid] = (GETPOST($key) ? price2num(GETPOST($key)) : 0); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; $result = $tmpinvoice->fetch($cursorfacid); @@ -300,9 +301,7 @@ if (empty($reshook)) $paiement->num_payment = GETPOST('num_paiement', 'alphanohtml'); $paiement->note_private = GETPOST('comment', 'alpha'); - $paiement->num_paiement = $paiement->num_payment; // For backward compatibility $paiement->num_payment = $paiement->num_payment; - $paiement->note = $paiement->note_private; // For backward compatibility $paiement->note_private = $paiement->note_private; if (!$error) @@ -788,255 +787,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } else dol_print_error($db); } -/* - * Show list - */ -if (empty($action) || $action == 'list') -{ - $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; } - $offset = $limit * $page; - $pageprev = $page - 1; - $pagenext = $page + 1; - if (!$sortorder) $sortorder = 'DESC'; - if (!$sortfield) $sortfield = 'p.datep'; - - $sql = 'SELECT p.rowid as pid, p.ref, p.datep as dp, p.amount as pamount, p.num_paiement,'; - $sql .= ' s.rowid as socid, s.nom as name,'; - $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,'; - $sql .= ' SUM(pf.amount)'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; - $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"; - $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; - $sql .= dolSqlDateFilter('p.datep', $day, $month, $year); - if ($search_ref) $sql .= natural_search('p.rowid', $search_ref); - if ($search_account > 0) $sql .= " AND b.fk_account=".$search_account; - if ($search_paymenttype != "") $sql .= " AND c.code='".$db->escape($search_paymenttype)."'"; - if ($search_payment_num != '') $sql .= natural_search('p.num_paiement', $search_payment_num); - if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); - if ($search_company) $sql .= natural_search('s.nom', $search_company); - 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"; - // Add where from extra fields - - $sql .= $db->order($sortfield, $sortorder); - - $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; - } - } - - $sql .= $db->plimit($limit + 1, $offset); - - $resql = $db->query($sql); - 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 ($day) $param .= ($day ? "&day=".urlencode($day) : ""); - if ($month) $param .= ($month ? "&month=".urlencode($month) : ""); - if ($year) $param .= ($year ? "&year=".urlencode($year) : ""); - if ($search_ref) $param .= ($search_ref ? "&search_ref=".urlencode($search_ref) : ""); - if ($search_company) $param .= ($search_company ? "&search_company=".urlencode($search_company) : ""); - if ($search_amount != '') $param .= ($search_amount ? "&search_amount=".urlencode($search_amount) : ""); - if ($search_payment_num) $param .= ($search_payment_num ? "&search_payment_num=".urlencode($search_payment_num) : ""); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - - $massactionbutton = $form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 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 ($moreforfilter) - { - print '
    '; - print $moreforfilter; - print '
    '; - } - - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
    '; - print '
    '.$langs->trans('Type').''; - print $object->getLibType(); - 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) - { - $facusing = new FactureFournisseur($db); - $facusing->fetch($object->fk_facture_source); - print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; - } + // Type + print '
    '.$langs->trans('Type').''; + print $object->getLibType(); + 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) + { + $facusing = new FactureFournisseur($db); + $facusing->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; + } - $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { - print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i = 0; - 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) - { - $facthatreplace = new FactureFournisseur($db); - $facthatreplace->fetch($facidnext); - print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; - } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $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')).'
    '; - } - } - print '
    '.$langs->trans('Discounts'); print ''; @@ -2497,18 +2502,18 @@ if ($action == 'create') print '
    '.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
    '.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
    '.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; - print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); - print '
    '.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; + print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); + print '
    '; - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $usercancreate) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
    '; - print '
    '; - 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'); + if (!empty($conf->banque->enabled)) + { + print '
    '; + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $usercancreate) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
    '; + print '
    '; + 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 "
    '.dol_print_date($db->jdate($objp->dp), 'day').''; - print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_paiement; + print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment; print ''; if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { - print 'rowid.'">'; + print 'rowid.'">'; print img_delete(); print ''; } @@ -3065,7 +3073,7 @@ if ($action == 'create') // modified by hook if (empty($reshook)) { - // Modify a validated invoice with no payments + // Modify a validated invoice with no payments 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 @@ -3110,17 +3118,17 @@ if ($action == 'create') } } - // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { - print ''; // must use facid because id is for payment id not invoice - } + // Make payments + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; // 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) - { - print ''; + // Classify paid + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; //print ''.$langs->trans('ClassifyPaid').''; } @@ -3156,21 +3164,21 @@ if ($action == 'create') } } - // Validate - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { + // Validate + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + { + if (count($object->lines)) + { if ($usercanvalidate) - { - print ''; - } else { - print ''; - } - } - } + { + print ''; + } else { + print ''; + } + } + } // 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. @@ -3193,30 +3201,30 @@ if ($action == 'create') } } - // Delete + // 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) - { - //var_dump($isErasable); - if ($isErasable == -4) { - print ''; - } elseif ($isErasable == -3) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -2) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -1) { - print ''; - } elseif ($isErasable <= 0) // Any other cases - { - print ''; - } else { - print ''; - } - } - print ''; + { + //var_dump($isErasable); + if ($isErasable == -4) { + print ''; + } elseif ($isErasable == -3) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -2) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -1) { + print ''; + } elseif ($isErasable <= 0) // Any other cases + { + print ''; + } else { + print ''; + } + } + print ''; - if ($action != 'confirm_edit') - { + if ($action != 'confirm_edit') + { print '
    '; /* @@ -3228,7 +3236,7 @@ if ($action == 'create') $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id; $genallowed = $usercanread; $delallowed = $usercancreate; - $modelpdf = (!empty($object->modelpdf) ? $object->modelpdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF)); + $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF)); print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang); $somethingshown = $formfile->numoffiles; diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php index 477086b3ca3..9be956b32ae 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -38,7 +38,7 @@ $langs->loadLangs(array("bills", "other", "companies")); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Security check if ($user->socid) $socid = $user->socid; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 3b06f1276d6..f43ef300b01 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -41,7 +41,7 @@ if (!empty($conf->projet->enabled)) { $langs->loadLangs(array('bills', 'other', 'companies')); $id = GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $ref = GETPOST('ref', 'alpha'); @@ -94,56 +94,56 @@ if ($object->id > 0) $totalpaye = $object->getSommePaiement(); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
    '; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, '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 .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->facture->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 .= '
    '; + $morehtmlref = '
    '; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, '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 .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->facture->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 .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); - print '
    '; - print '
    '; + print '
    '; + print '
    '; // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); @@ -215,15 +215,15 @@ 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 ($mysoc->localtax1_assuj == "1") //Localtax1 { - print '
    '.$langs->transcountry("AmountLT1", $societe->country_code).'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '; + $form->select_conditions_paiements($search_paymentcond, 'search_paymentcond', -1, 1, 1, 'maxwidth100'); + print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10); + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 20, 1, 'maxwidth100'); print ''; + $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', '', -1); + print '
    '."\n"; - - // Lines for filters fields - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->banque->enabled)) - { - print ''; - } - print ''; - print ''; - print "\n"; - - print ''; - print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Date", $_SERVER["PHP_SELF"], 'dp', '', $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Type", $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Numero", $_SERVER["PHP_SELF"], "p.num_paiement", "", $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("Amount", $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); - - $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; - - print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; - - $paymentfournstatic = new PaiementFourn($db); - - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); - - $paymentfournstatic->id = $objp->pid; - $paymentfournstatic->ref = $objp->ref; - $paymentfournstatic->datepaye = $objp->dp; - - print ''; - - // Ref payment - print ''; - if (!$i) $totalarray['nbfield']++; - - // Date - $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Thirdparty - print ''; - if (!$i) $totalarray['nbfield']++; - - // Type - $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Payment number - print ''; - if (!$i) $totalarray['nbfield']++; - - // Account - if (!empty($conf->banque->enabled)) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Amount - print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'amount'; - $totalarray['val']['amount'] += $objp->pamount; - - // Ref invoice - /*$invoicesupplierstatic->ref=$objp->ref_supplier; - $invoicesupplierstatic->id=$objp->facid; - print '';*/ - - print ''; - if (!$i) $totalarray['nbfield']++; - - print ''; - $i++; - } - - // Show total line - include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - - print "
    '; - print ''; - print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); - print ''; - print ''; - print ''; - $form->select_types_paiements($search_paymenttype, 'search_paymenttype', '', 2, 1, 1); - print ''; - print ''; - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); - print ''; - print ''; - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
    '; - print $paymentfournstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), $dateformatforpayment)."'; - if ($objp->socid) print ''.img_object($langs->trans('ShowCompany'), 'company').' '.dol_trunc($objp->name, 32).''; - else print ' '; - print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32)."'.$objp->num_paiement.''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; - else print ' '; - print ''.price($objp->pamount).''; - print $invoicesupplierstatic->getNomUrl(1); - print '
    "; - print "
    "; - print "\n"; - } else { - dol_print_error($db); - } -} - // End of page llxFooter(); $db->close(); diff --git a/htdocs/fourn/facture/rapport.php b/htdocs/fourn/facture/rapport.php index 7873dd81b2d..1c068e19b7d 100644 --- a/htdocs/fourn/facture/rapport.php +++ b/htdocs/fourn/facture/rapport.php @@ -47,7 +47,7 @@ if ($user->socid > 0) $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 -$year = $_GET["year"]; +$year = GETPOST("year", 'int'); if (!$year) { $year = date("Y"); } @@ -69,7 +69,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, $_POST["remonth"], $_POST["reyear"], $outputlangs) > 0) + if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0) { $outputlangs->charset_output = $sav_charset_output; } else { @@ -77,7 +77,7 @@ if ($action == 'builddoc') dol_print_error($db, $obj->error); } - $year = $_POST["reyear"]; + $year = GETPOST("reyear", 'int'); } diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 28020e40811..25256c7e20b 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -54,7 +54,7 @@ if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) $db->begin(); $object->fetch($id); - $result = $object->update_note(GETPOST('note', 'none')); + $result = $object->update_note(GETPOST('note', 'restricthtml')); if ($result > 0) { $db->commit(); @@ -74,7 +74,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse if ($result > 0) { $db->commit(); - header('Location: '.DOL_URL_ROOT.'/fourn/facture/paiement.php'); + header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -166,7 +166,7 @@ if ($result > 0) print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide'); } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref'); @@ -345,7 +345,7 @@ if ($result > 0) { if ($allow_delete) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; } @@ -367,7 +367,7 @@ if ($result > 0) $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id; $genallowed = $user->rights->fournisseur->facture->lire; $delallowed = $user->rights->fournisseur->facture->creer; - $modelpdf = (!empty($object->modelpdf) ? $object->modelpdf : (empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF) ? '' : $conf->global->SUPPLIER_PAYMENT_ADDON_PDF)); + $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF) ? '' : $conf->global->SUPPLIER_PAYMENT_ADDON_PDF)); print $formfile->showdocuments('supplier_payment', $ref, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang); $somethingshown = $formfile->numoffiles; diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php new file mode 100644 index 00000000000..1a89e7f6906 --- /dev/null +++ b/htdocs/fourn/paiement/list.php @@ -0,0 +1,429 @@ + + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2004-2020 Laurent Destailleur + * Copyright (C) 2004 Christophe Combelles + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> + * Copyright (C) 2015 Marcos García + * Copyright (C) 2015 Juanjo Menent + * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Frédéric France + * Copyright (C) 2020 Tobias Sekan + * + * 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/fourn/paiment/list.php +* \ingroup fournisseur,facture + * \brief Payment list for supplier invoices + */ + +require '../../main.inc.php'; + +// Security check +if ($user->socid) $socid = $user->socid; + +// doesn't work :-( +// restrictedArea($user, 'fournisseur'); + +// doesn't work :-( +// require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +// $object = new PaiementFourn($db); +// restrictedArea($user, $object->element); + +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} + +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + + +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills', 'banks', 'compta')); + +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'vendorpaymentlist'; + +$socid = GETPOST('socid', 'int'); + +$search_ref = GETPOST('search_ref', 'alpha'); +$search_day = GETPOST('search_day', 'int'); +$search_month = GETPOST('search_month', 'int'); +$search_year = GETPOST('search_year', 'int'); +$search_company = GETPOST('search_company', 'alpha'); +$search_payment_type = GETPOST('search_payment_type'); +$search_cheque_num = GETPOST('search_cheque_num', 'alpha'); +$search_bank_account = GETPOST('search_bank_account', 'int'); +$search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on '< x' + +$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 = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "p.datep"; + +// TODO: add global search for this list + +$arrayfields = array( + 'p.ref' =>array('label'=>"RefPayment", 'checked'=>1, 'position'=>10), + 'p.datep' =>array('label'=>"Date", 'checked'=>1, 'position'=>20), + 's.nom' =>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30), + 'c.libelle' =>array('label'=>"Type", 'checked'=>1, 'position'=>40), + 'p.num_paiement' =>array('label'=>"Numero", 'checked'=>1, 'position'=>50, 'tooltip'=>"ChequeOrTransferNumber"), + 'ba.label' =>array('label'=>"Account", 'checked'=>1, 'position'=>60, 'enable'=>(!empty($conf->banque->enabled))), + 'p.amount' =>array('label'=>"Amount", 'checked'=>1, 'position'=>70), +); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +$hookmanager->initHooks(array('paymentsupplierlist')); +$object = new PaiementFourn($db); + +/* +* Actions +*/ + +$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)) { + 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 + $search_ref = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; + $search_company = ''; + $search_payment_type = ''; + $search_cheque_num = ''; + $search_bank_account = ''; + $search_amount = ''; + } +} + +/* + * View + */ + +llxHeader('', $langs->trans('ListPayment')); + +$form = new Form($db); +$formother = new FormOther($db); +$companystatic = new Societe($db); +$paymentfournstatic = new PaiementFourn($db); + +$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'; +$sql .= ', SUM(pf.amount)'; + +$sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; +$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'; + +$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); +$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."'"; + +// 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 .= $db->order($sortfield, $sortorder); + +$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; + } +} + +$sql .= $db->plimit($limit + 1, $offset); + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + llxFooter(); + $db->close(); + exit; +} + +$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_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 '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 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 ($moreforfilter) { + print '
    '; + print $moreforfilter; + 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); + +print '
    '; +print ''; + +print ''; + +// Filter: Ref +if (!empty($arrayfields['p.ref']['checked'])) { + print ''; +} + +// Filter: Date +if (!empty($arrayfields['p.datep']['checked'])) { + print ''; +} + +// Filter: Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print ''; +} + +// Filter: Payment type +if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; +} + +// Filter: Cheque number (fund transfer) +if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; +} + +// Filter: Bank account +if (!empty($arrayfields['ba.label']['checked'])) { + print ''; +} + +// Filter: Amount +if (!empty($arrayfields['p.amount']['checked'])) { + print ''; +} + +// 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; + +// Buttons +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['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); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print_liste_field_titre($selectedfields, $_SERVER['PHP_SELF'], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); +print ''; + +$checkedCount = 0; +foreach ($arrayfields as $column) { + if ($column['checked']) { + $checkedCount++; + } +} + +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $objp = $db->fetch_object($resql); + + $paymentfournstatic->id = $objp->rowid; + $paymentfournstatic->ref = $objp->ref; + $paymentfournstatic->datepaye = $objp->datep; + + $companystatic->id = $objp->socid; + $companystatic->name = $objp->name; + $companystatic->email = $objp->email; + + print ''; + + // No + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Ref + if (!empty($arrayfields['p.ref']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Date + if (!empty($arrayfields['p.datep']['checked'])) { + $dateformatforpayment = 'day'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Thirdparty + if (!empty($arrayfields['s.nom']['checked'])) { + print ''; + 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 ''; + if (!$i) $totalarray['nbfield']++; + } + + // Cheque number (fund transfer) + if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Account + if (!empty($arrayfields['ba.label']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Amount + if (!empty($arrayfields['p.amount']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + $totalarray['pos'][$checkedCount] = 'amount'; + $totalarray['val']['amount'] += $objp->pamount; + } + + // Buttons + print ''; + if (!$i) $totalarray['nbfield']++; + + print ''; + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +print '
    '; + print ''; + print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year ? $search_year : -1, 'search_year', 1, 20, 5); + print ''; + print ''; + print ''; + $form->select_types_paiements($search_payment_type, 'search_payment_type', '', 2, 1, 1); + print ''; + print ''; + print ''; + $form->select_comptes($search_bank_account, 'search_bank_account', 0, '', 1); + print ''; + print ''; + print ''; +print $form->showFilterAndCheckAddButtons(0); +print '
    '.(($offset * $limit) + $i).''.$paymentfournstatic->getNomUrl(1).''.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).''; + if ($objp->socid > 0) { + print $companystatic->getNomUrl(1, '', 24); + } + print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32).''.$objp->num_paiement.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; + else print ' '; + print ''.price($objp->pamount).'
    '; +print '
    '; +print '
    '; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/fourn/product/list.php b/htdocs/fourn/product/list.php index 91cd3636bbe..e3d2b5b91d2 100644 --- a/htdocs/fourn/product/list.php +++ b/htdocs/fourn/product/list.php @@ -43,8 +43,8 @@ $optioncss = GETPOST('optioncss', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -127,7 +127,7 @@ if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = $massactionbutton = $form->selectMassAction('', $arrayofmassactions); -$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type, p.entity,"; +$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type, p.entity, tosell, tobuy,"; $sql .= " ppf.fk_soc, ppf.ref_fourn, ppf.price as price, ppf.quantity as qty, ppf.unitprice,"; $sql .= " s.rowid as socid, s.nom as name"; // Add fields to SELECT from hooks @@ -296,6 +296,8 @@ if ($resql) $productstatic->ref = $objp->ref; $productstatic->type = $objp->fk_product_type; $productstatic->entity = $objp->entity; + $productstatic->status = $objp->tosell; + $productstatic->status_buy = $objp->tobuy; print $productstatic->getNomUrl(1, 'supplier'); print ''; diff --git a/htdocs/ftp/admin/ftpclient.php b/htdocs/ftp/admin/ftpclient.php index 49af7141d84..70a96546fc2 100644 --- a/htdocs/ftp/admin/ftpclient.php +++ b/htdocs/ftp/admin/ftpclient.php @@ -33,7 +33,7 @@ if (!$user->admin) accessforbidden(); $def = array(); $lastftpentry = 0; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $entry = GETPOST('numero_entry', 'alpha'); diff --git a/htdocs/ftp/index.php b/htdocs/ftp/index.php index 5310a0b3bf8..7c0eab0f352 100644 --- a/htdocs/ftp/index.php +++ b/htdocs/ftp/index.php @@ -87,7 +87,7 @@ if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $result = $ecmdir->fetch($_REQUEST["section"]); + $result = $ecmdir->fetch(GETPOST("section", 'int')); if (!$result > 0) { dol_print_error($db, $ecmdir->error); @@ -125,9 +125,9 @@ if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC)) // Action ajout d'un rep if ($action == 'add' && $user->rights->ftp->setup) { - $ecmdir->ref = $_POST["ref"]; - $ecmdir->label = $_POST["label"]; - $ecmdir->description = $_POST["desc"]; + $ecmdir->ref = GETPOST("ref"); + $ecmdir->label = GETPOST("label"); + $ecmdir->description = GETPOST("desc"); $id = $ecmdir->create($user); if ($id > 0) @@ -140,8 +140,8 @@ if ($action == 'add' && $user->rights->ftp->setup) } } -// Remove file -if ($action == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes') +// Remove 1 file +if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes') { // set up a connection or die if (!$conn_id) @@ -155,16 +155,26 @@ if ($action == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes') if ($conn_id && $ok && !$mesg) { + $newsection = $section; + 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 + } + $langs->load("other"); // Remote file $filename = $file; - $remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; + $remotefile = $newsection.(preg_match('@[\\\/]$@', $newsection) ? '' : '/').$file; $newremotefileiso = utf8_decode($remotefile); //print "x".$newremotefileiso; dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso); - $result = @ftp_delete($conn_id, $newremotefileiso); + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { + $result = ssh2_sftp_unlink($conn_id, $newremotefileiso); + } else { + $result = @ftp_delete($conn_id, $newremotefileiso); + } if ($result) { setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs'); @@ -182,7 +192,7 @@ if ($action == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes') } // Delete several lines at once -if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("Delete")) +if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $langs->trans("Delete")) { // set up a connection or die if (!$conn_id) @@ -196,7 +206,7 @@ if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("De if ($conn_id && $ok && !$mesg) { - foreach ($_POST["const"] as $const) + foreach (GETPOST('const', 'array') as $const) { if ($const["check"]) // Is checkbox checked { @@ -204,18 +214,26 @@ if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("De // Remote file $file = $const["file"]; - $section = $const["section"]; - $remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; + $newsection = $const["section"]; + 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; $newremotefileiso = utf8_decode($remotefile); //print "x".$newremotefileiso; - dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso); - $result = @ftp_delete($conn_id, $newremotefileiso); + dol_syslog("ftp/index.php ftp_delete n files for ".$newremotefileiso); + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { + $result = ssh2_sftp_unlink($conn_id, $newremotefileiso); + } else { + $result = @ftp_delete($conn_id, $newremotefileiso); + } if ($result) { setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs'); } else { - dol_syslog("ftp/index.php ftp_delete", LOG_ERR); + dol_syslog("ftp/index.php ftp_delete n files", LOG_ERR); setEventMessages($langs->trans("FTPFailedToRemoveFile", $file), null, 'errors'); } @@ -244,12 +262,22 @@ if ($action == 'confirm_deletesection' && $confirm == 'yes') if ($conn_id && $ok && !$mesg) { + $newsection = $section; + 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 + } + // Remote file $filename = $file; - $remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; + $remotefile = $newsection.(preg_match('@[\\\/]$@', $newsection) ? '' : '/').$file; $newremotefileiso = utf8_decode($remotefile); - $result = @ftp_rmdir($conn_id, $newremotefileiso); + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { + $result = ssh2_sftp_rmdir($conn_id, $newremotefileiso); + } else { + $result = @ftp_rmdir($conn_id, $newremotefileiso); + } if ($result) { setEventMessages($langs->trans("DirWasRemoved", $file), null, 'mesgs'); @@ -283,12 +311,22 @@ if ($action == 'download') // Local file $localfile = tempnam($download_dir, 'dol_'); + $newsection = $section; + 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 + } + // Remote file $filename = $file; - $remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; + $remotefile = $newsection.(preg_match('@[\\\/]$@', $newsection) ? '' : '/').$file; $newremotefileiso = utf8_decode($remotefile); - $result = ftp_get($conn_id, $localfile, $newremotefileiso, FTP_BINARY); + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { + $result = fopen('ssh2.sftp://' . intval($conn_id) . $newremotefileiso, 'r'); + } else { + $result = ftp_get($conn_id, $localfile, $newremotefileiso, FTP_BINARY); + } if ($result) { if (!empty($conf->global->MAIN_UMASK)) @@ -296,13 +334,13 @@ if ($action == 'download') // Define mime type $type = 'application/octet-stream'; - if (!empty($_GET["type"])) $type = $_GET["type"]; - else $type = dol_mimetype($original_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 ($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.'"'); @@ -382,13 +420,13 @@ if (!function_exists('ftp_connect')) // Confirm remove file if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'§ion='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'§ion='.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') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'§ion='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'§ion='.urlencode(GETPOST('section')).'&file='.urlencode(GETPOST('file')), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1); } print $langs->trans("Server").': '.$ftp_server.'
    '; @@ -431,12 +469,12 @@ if (!function_exists('ftp_connect')) print ''."\n"; print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; print ''; // Size @@ -553,22 +595,22 @@ if (!function_exists('ftp_connect')) print $vals[0]; print ''; // Action - print ''; + print '
    '.$langs->trans("Content").''.$langs->trans("Size").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Group").''.$langs->trans("Permissions").''.$langs->trans("Content").''.$langs->trans("Size").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Group").''.$langs->trans("Permissions").''; if ($conf->use_javascript_ajax) print ''.$langs->trans("All").' / '.$langs->trans("None").' '; print ''.img_picto($langs->trans("Refresh"), 'refresh').' '; @@ -464,10 +502,14 @@ if (!function_exists('ftp_connect')) // List content of directory ($newsection = '/', '/home', ...) if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { - if ($newsection == '/') $newsection = '/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 + if ($newsection == '/') { + //$newsection = '/./'; + $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169 + } + //$newsection='/'; //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection); - //var_dump($dirHandle); - $contents = scandir('ssh2.sftp://'.$conn_id.$newsection); + //$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) { @@ -528,7 +570,7 @@ if (!function_exists('ftp_connect')) $newsection = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file; $newsection = preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@', '/', $newsection); // Change aaa/xxx/.. to new aaa if ($is_directory) print ''; - print $file; + print dol_escape_htmltag($file); if ($is_directory) print ''; print ''; + print ''; if ($is_directory) { - if ($file != '..') print ''.img_delete().''; + if ($file != '..') print ''.img_delete().''; else print ' '; } elseif ($is_link) { $newfile = $file; $newfile = preg_replace('/ ->.*/', '', $newfile); - print ''.img_delete().''; + print ''.img_delete().''; } else { - print ''.img_picto('', 'file').''; + print ''.img_picto('', 'file').''; print '   '; print ''; print '   '; - print ''.img_delete().''; + print ''.img_delete().''; print ''; print ''; } @@ -676,12 +718,10 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect if ($ok) { $connecttimeout = (empty($conf->global->FTP_CONNECT_TIMEOUT) ? 40 : $conf->global->FTP_CONNECT_TIMEOUT); - if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) - { + if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) { dol_syslog('Try to connect with ssh2_ftp'); $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port); - } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL)) - { + } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL)) { dol_syslog('Try to connect with ftp_ssl_connect'); $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout); } else { @@ -694,6 +734,7 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect { 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)) { // Turn on passive mode transfers (must be after a successful login @@ -705,11 +746,13 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect $conn_id = ssh2_sftp($tmp_conn_id); if (!$conn_id) { + dol_syslog('Failed to connect to SFTP after sssh authentication', LOG_DEBUG); $mesg = $langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication"); $ok = 0; $error++; } } else { + dol_syslog('Failed to connect to FTP with login '.$ftp_user, LOG_DEBUG); $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials"); $ok = 0; $error++; diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index fe315f9c7b7..d9bbe6607bf 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -69,16 +69,16 @@ $extrafields->fetch_name_optionals_label($object->table_element); if (($id > 0) || $ref) { - $object->fetch($id, $ref); + $object->fetch($id, $ref); - // Check current user can read this leave request - $canread = 0; - if (!empty($user->rights->holiday->read_all)) $canread = 1; - if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) $canread = 1; - if (!$canread) - { - accessforbidden(); - } + // Check current user can read this leave request + $canread = 0; + if (!empty($user->rights->holiday->read_all)) $canread = 1; + if (!empty($user->rights->holiday->read) && in_array($object->fk_user, $childids)) $canread = 1; + if (!$canread) + { + accessforbidden(); + } } $cancreate = 0; @@ -111,152 +111,152 @@ if (empty($reshook)) header("Location: ".$backtopage); exit; } - $action = ''; + $action = ''; } - // If create a request - if ($action == 'create') + // Add leave request + if ($action == 'add') { - // If no right to create a request - if (!$cancreate) - { - $error++; - setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); - $action = 'request'; - } + // If no right to create a request + if (!$cancreate) + { + $error++; + setEventMessages($langs->trans('CantCreateCP'), null, 'errors'); + $action = 'create'; + } - if (!$error) - { - $object = new Holiday($db); + if (!$error) + { + $object = new Holiday($db); - $db->begin(); + $db->begin(); - $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); - $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); - $starthalfday = GETPOST('starthalfday'); - $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; + $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); + $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1); + $starthalfday = GETPOST('starthalfday'); + $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; - $valideur = GETPOST('valideur', 'int'); - $description = trim(GETPOST('description')); + $valideur = GETPOST('valideur', 'int'); + $description = trim(GETPOST('description', 'restricthtml')); - // If no type - if ($type <= 0) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error++; - $action = 'create'; - } + // If no type + if ($type <= 0) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error++; + $action = 'add'; + } - // If no start date - if (empty($date_debut)) - { - setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); - $error++; - $action = 'create'; - } - // If no end date - if (empty($date_fin)) - { - setEventMessages($langs->trans("NoDateFin"), null, 'errors'); - $error++; - $action = 'create'; - } - // If start date after end date - if ($date_debut > $date_fin) - { - setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); - $error++; - $action = 'create'; - } + // If no start date + if (empty($date_debut)) + { + setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); + $error++; + $action = 'add'; + } + // If no end date + if (empty($date_fin)) + { + setEventMessages($langs->trans("NoDateFin"), null, 'errors'); + $error++; + $action = 'add'; + } + // If start date after end date + if ($date_debut > $date_fin) + { + setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); + $error++; + $action = 'add'; + } - // Check if there is already holiday for this period - $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); - if (!$verifCP) - { - setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); - $error++; - $action = 'create'; - } + // Check if there is already holiday for this period + $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday); + if (!$verifCP) + { + setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); + $error++; + $action = 'add'; + } - // 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) - { - setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); - $error++; - $action = 'create'; - } + // 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) + { + setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); + $error++; + $action = 'add'; + } - // If no validator designated - if ($valideur < 1) - { - setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); - $error++; - } + // If no validator designated + if ($valideur < 1) + { + setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors'); + $error++; + } - $result = 0; + $result = 0; - if (!$error) - { - $object->fk_user = $fuserid; - $object->description = $description; - $object->fk_validator = $valideur; - $object->fk_type = $type; - $object->date_debut = $date_debut; - $object->date_fin = $date_fin; - $object->halfday = $halfday; + if (!$error) + { + $object->fk_user = $fuserid; + $object->description = $description; + $object->fk_validator = $valideur; + $object->fk_type = $type; + $object->date_debut = $date_debut; + $object->date_fin = $date_fin; + $object->halfday = $halfday; - $result = $object->create($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + $result = $object->create($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } - // If no SQL error we redirect to the request card - if (!$error) - { + // If no SQL error we redirect to the request card + if (!$error) + { $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - $db->rollback(); - } - } + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + $db->rollback(); + } + } } if ($action == 'update' && GETPOSTISSET('savevalidator') && !empty($user->rights->holiday->approve)) { - $object->fetch($id); + $object->fetch($id); - $object->oldcopy = dol_clone($object); + $object->oldcopy = dol_clone($object); - $object->fk_validator = GETPOST('valideur', 'int'); + $object->fk_validator = GETPOST('valideur', 'int'); - if ($object->fk_validator != $object->oldcopy->fk_validator) - { - $verif = $object->update($user); + if ($object->fk_validator != $object->oldcopy->fk_validator) + { + $verif = $object->update($user); - if ($verif <= 0) - { - setEventMessages($object->error, $object->errors, 'warnings'); - $action = 'editvalidator'; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } + if ($verif <= 0) + { + setEventMessages($object->error, $object->errors, 'warnings'); + $action = 'editvalidator'; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } - $action = ''; + $action = ''; } if ($action == 'update' && !GETPOSTISSET('savevalidator')) @@ -272,60 +272,61 @@ if (empty($reshook)) elseif ($starthalfday == 'afternoon') $halfday = -1; elseif ($endhalfday == 'morning') $halfday = 1; - // If no right to modify a request - if (!$user->rights->holiday->write) - { - header('Location: '.$_SERVER["PHP_SELF"].'?action=request&error=CantUpdate'); - exit; - } + // If no right to modify a request + if (!$user->rights->holiday->write) + { + setEventMessages($langs->trans("CantUpdate"), null, 'errors'); + header('Location: '.$_SERVER["PHP_SELF"].'?action=create'); + exit; + } - $object->fetch($id); + $object->fetch($id); // If under validation - if ($object->statut == Holiday::STATUS_DRAFT) - { - // If this is the requestor or has read/write rights - if ($cancreate) - { - $valideur = GETPOST('valideur', 'int'); - $description = trim(GETPOST('description', 'none')); + if ($object->statut == Holiday::STATUS_DRAFT) + { + // If this is the requestor or has read/write rights + if ($cancreate) + { + $valideur = GETPOST('valideur', 'int'); + $description = trim(GETPOST('description', 'restricthtml')); - // If no start date - if (empty($_POST['date_debut_'])) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatedebut'); - exit; - } + // If no start date + if (empty($_POST['date_debut_'])) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatedebut'); + exit; + } - // If no end date - if (empty($_POST['date_fin_'])) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatefin'); - exit; - } + // If no end date + if (empty($_POST['date_fin_'])) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=nodatefin'); + exit; + } - // If start date after end date - if ($date_debut > $date_fin) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=datefin'); - exit; - } + // If start date after end date + if ($date_debut > $date_fin) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=datefin'); + exit; + } - // If no validator designated - if ($valideur < 1) { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=Valideur'); - exit; - } + // If no validator designated + if ($valideur < 1) { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=Valideur'); + exit; + } - // 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) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=DureeHoliday'); - exit; - } + // 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) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&error=DureeHoliday'); + exit; + } - $object->description = $description; - $object->date_debut = $date_debut; - $object->date_fin = $date_fin; - $object->fk_validator = $valideur; + $object->description = $description; + $object->date_debut = $date_debut; + $object->date_fin = $date_fin; + $object->fk_validator = $valideur; $object->halfday = $halfday; // Update @@ -339,14 +340,14 @@ if (empty($reshook)) header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } - } else { - setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); - $action = ''; - } - } else { - setEventMessages($langs->trans("ErrorBadStatus"), null, 'errors'); - $action = ''; - } + } else { + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); + $action = ''; + } + } else { + setEventMessages($langs->trans("ErrorBadStatus"), null, 'errors'); + $action = ''; + } } // If delete of request @@ -358,7 +359,7 @@ if (empty($reshook)) $object->fetch($id); - // If this is a rough draft, approved, canceled or refused + // 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) { // Si l'utilisateur à le droit de lire cette demande, il peut la supprimer @@ -385,100 +386,100 @@ if (empty($reshook)) // Action validate (+ send email for approval) if ($action == 'confirm_send') { - $object->fetch($id); + $object->fetch($id); - // Si brouillon et créateur - if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) - { - $object->oldcopy = dol_clone($object); + // Si brouillon et créateur + if ($object->statut == Holiday::STATUS_DRAFT && $cancreate) + { + $object->oldcopy = dol_clone($object); - $object->statut = Holiday::STATUS_VALIDATED; + $object->statut = Holiday::STATUS_VALIDATED; - $verif = $object->validate($user); + $verif = $object->validate($user); - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if ($verif > 0) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_validator); - $emailTo = $destinataire->email; + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if ($verif > 0) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_validator); + $emailTo = $destinataire->email; - 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; - } + 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; + } - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_user); - $emailFrom = $expediteur->email; + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_user); + $emailFrom = $expediteur->email; - // 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->transnoentitiesnoconv("HolidaysToValidate"); + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate"); - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message .= "\n"; - $message .= $langs->transnoentities("HolidaysToValidateBody")."\n"; + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message .= "\n"; + $message .= $langs->transnoentities("HolidaysToValidateBody")."\n"; - $delayForRequest = $object->getConfCP('delayForRequest'); - //$delayForRequest = $delayForRequest * (60*60*24); + $delayForRequest = $object->getConfCP('delayForRequest'); + //$delayForRequest = $delayForRequest * (60*60*24); - $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); + $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) - { - $message .= "\n"; - $message .= $langs->transnoentities("HolidaysToValidateDelay", $object->getConfCP('delayForRequest'))."\n"; - } - } + // Si l'option pour avertir le valideur en cas de délai trop court + 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')) - { - $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)) - { - $message .= "\n"; - $message .= $langs->transnoentities("HolidaysToValidateAlertSolde")."\n"; - } - } + // Si l'option pour avertir le valideur en cas de solde inférieur à la demande + 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)) + { + $message .= "\n"; + $message .= $langs->transnoentities("HolidaysToValidateAlertSolde")."\n"; + } + } - $message .= "\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message .= "\n"; + $message .= "\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')."\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message .= "\n"; - $trackid = 'leav'.$object->id; + $trackid = 'leav'.$object->id; - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail - $result = $mail->sendfile(); + // Envoi du mail + $result = $mail->sendfile(); - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); - $action = ''; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $action = ''; - } - } + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); + $action = ''; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; + } + } } if ($action == 'update_extras') @@ -486,7 +487,7 @@ if (empty($reshook)) $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none')); + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); if ($ret < 0) $error++; if (!$error) @@ -507,200 +508,200 @@ if (empty($reshook)) // Approve leave request if ($action == 'confirm_valid') { - $object->fetch($id); + $object->fetch($id); - // Si statut en attente de validation et valideur = utilisateur - if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) - { - $object->oldcopy = dol_clone($object); + // Si statut en attente de validation et valideur = utilisateur + if ($object->statut == Holiday::STATUS_VALIDATED && $user->id == $object->fk_validator) + { + $object->oldcopy = dol_clone($object); - $object->date_valid = dol_now(); - $object->fk_user_valid = $user->id; - $object->statut = Holiday::STATUS_APPROVED; + $object->date_valid = dol_now(); + $object->fk_user_valid = $user->id; + $object->statut = Holiday::STATUS_APPROVED; - $db->begin(); + $db->begin(); - $verif = $object->approve($user); - if ($verif <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } + $verif = $object->approve($user); + 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) - { - // 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); + // Si pas d'erreur SQL on redirige vers la fiche de la demande + 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 - $result = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type); - if ($result < 0) - { - $error++; - setEventMessages(null, $object->errors, 'errors'); - } + // On ajoute la modification dans le LOG + $result = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $object->fk_type); + if ($result < 0) + { + $error++; + setEventMessages(null, $object->errors, 'errors'); + } - //Update balance - $result = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - if ($result < 0) - { - $error++; - setEventMessages(null, $object->errors, 'errors'); - } - } + //Update balance + $result = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); + if ($result < 0) + { + $error++; + setEventMessages(null, $object->errors, 'errors'); + } + } - if (!$error) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; + if (!$error) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; - if (!$emailTo) - { - dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); - } else { - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_validator); - $emailFrom = $expediteur->email; + if (!$emailTo) + { + dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); + } else { + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_validator); + $emailFrom = $expediteur->email; - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated"); + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated"); - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message .= "\n"; - $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message .= "\n"; + $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message .= "\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message .= "\n"; - $trackid = 'leav'.$object->id; + $trackid = 'leav'.$object->id; - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail - $result = $mail->sendfile(); + // Envoi du mail + $result = $mail->sendfile(); - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 - $action = ''; - } - } - } + 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) - { - $db->commit(); + if (!$error) + { + $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - $db->rollback(); - $action = ''; - } - } + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + $db->rollback(); + $action = ''; + } + } } if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes') { if (!empty($_POST['detail_refuse'])) - { - $object->fetch($id); + { + $object->fetch($id); - // Si statut en attente de validation et valideur = utilisateur - 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; - $object->detail_refuse = GETPOST('detail_refuse', 'alphanohtml'); + // Si statut en attente de validation et valideur = utilisateur + 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; + $object->detail_refuse = GETPOST('detail_refuse', 'alphanohtml'); - $db->begin(); + $db->begin(); - $verif = $object->update($user); - if ($verif <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $verif = $object->update($user); + 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) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if (!$error) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; - if (!$emailTo) - { - dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); - } else { - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_validator); - $emailFrom = $expediteur->email; + if (!$emailTo) + { + dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email"); + } else { + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_validator); + $emailFrom = $expediteur->email; - // Subject - $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; + // Subject + $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE; - $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused"); + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused"); - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message .= "\n"; - $message .= $langs->transnoentities("HolidaysRefusedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; - $message .= GETPOST('detail_refuse', 'alpha')."\n\n"; + // Content + $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; + $message .= "\n"; + $message .= $langs->transnoentities("HolidaysRefusedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + $message .= GETPOST('detail_refuse', 'alpha')."\n\n"; - $message .= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + $message .= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message .= "\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message .= "\n"; - $trackid = 'leav'.$object->id; + $trackid = 'leav'.$object->id; - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail - $result = $mail->sendfile(); + // Envoi du mail + $result = $mail->sendfile(); - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 - $action = ''; - } - } - } else { - $action = ''; - } + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1 + $action = ''; + } + } + } else { + $action = ''; + } - if (!$error) - { - $db->commit(); + if (!$error) + { + $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - $db->rollback(); - $action = ''; - } - } - } else { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DetailRefusCP")), null, 'errors'); - $action = 'refuse'; - } + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + $db->rollback(); + $action = ''; + } + } + } else { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DetailRefusCP")), null, 'errors'); + $action = 'refuse'; + } } @@ -709,27 +710,27 @@ if (empty($reshook)) { $error = 0; - $object->fetch($id); + $object->fetch($id); - $oldstatus = $object->statut; - $object->statut = Holiday::STATUS_DRAFT; + $oldstatus = $object->statut; + $object->statut = Holiday::STATUS_DRAFT; - $result = $object->update($user); - if ($result < 0) - { - $error++; - setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors'); - } + $result = $object->update($user); + if ($result < 0) + { + $error++; + setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors'); + } - if (!$error) - { - $db->commit(); + if (!$error) + { + $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - $db->rollback(); - } + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + $db->rollback(); + } } // Si confirmation of cancellation @@ -737,100 +738,100 @@ if (empty($reshook)) { $error = 0; - $object->fetch($id); + $object->fetch($id); - // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres - if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all))) - { - $db->begin(); + // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres + if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all))) + { + $db->begin(); - $oldstatus = $object->statut; - $object->date_cancel = dol_now(); - $object->fk_user_cancel = $user->id; - $object->statut = Holiday::STATUS_CANCELED; + $oldstatus = $object->statut; + $object->date_cancel = dol_now(); + $object->fk_user_cancel = $user->id; + $object->statut = Holiday::STATUS_CANCELED; - $result = $object->update($user); + $result = $object->update($user); - 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); + 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); + $soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type); + $newSolde = ($soldeActuel + $nbopenedday); - // On ajoute la modification dans le LOG - $result1 = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("HolidaysCancelation"), $newSolde, $object->fk_type); + // On ajoute la modification dans le LOG + $result1 = $object->addLogCP($user->id, $object->fk_user, $langs->transnoentitiesnoconv("HolidaysCancelation"), $newSolde, $object->fk_type); - // Mise à jour du solde - $result2 = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); + // Mise à jour du solde + $result2 = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type); - if ($result1 < 0 || $result2 < 0) - { - $error++; - setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors'); - } - } + if ($result1 < 0 || $result2 < 0) + { + $error++; + setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors'); + } + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } - // Si pas d'erreur SQL on redirige vers la fiche de la demande - if (!$error && $result > 0) - { - // To - $destinataire = new User($db); - $destinataire->fetch($object->fk_user); - $emailTo = $destinataire->email; + // Si pas d'erreur SQL on redirige vers la fiche de la demande + if (!$error && $result > 0) + { + // To + $destinataire = new User($db); + $destinataire->fetch($object->fk_user); + $emailTo = $destinataire->email; - if (!$emailTo) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } + if (!$emailTo) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } - // From - $expediteur = new User($db); - $expediteur->fetch($object->fk_user_cancel); - $emailFrom = $expediteur->email; + // From + $expediteur = new User($db); + $expediteur->fetch($object->fk_user_cancel); + $emailFrom = $expediteur->email; - // 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->transnoentitiesnoconv("HolidaysCanceled"); + $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysCanceled"); - // Content - $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n"; - $message .= "\n"; + // Content + $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"; - $message .= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; + $message .= $langs->transnoentities("HolidaysCanceledBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."\n"; + $message .= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; - $message .= "\n"; + $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$object->id."\n\n"; + $message .= "\n"; - $trackid = 'leav'.$object->id; + $trackid = 'leav'.$object->id; - $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); + $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid); - // Envoi du mail - $result = $mail->sendfile(); + // Envoi du mail + $result = $mail->sendfile(); - if (!$result) - { - setEventMessages($mail->error, $mail->errors, 'warnings'); - $action = ''; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - } - } + if (!$result) + { + setEventMessages($mail->error, $mail->errors, 'warnings'); + $action = ''; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + } + } } /* @@ -863,53 +864,53 @@ $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->t llxHeader('', $langs->trans('CPTitreMenu')); -if ((empty($id) && empty($ref)) || $action == 'add' || $action == 'request' || $action == 'create') +if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') { - // Si l'utilisateur n'a pas le droit de faire une demande - if (($fuserid == $user->id && empty($user->rights->holiday->write)) || ($fuserid != $user->id && empty($user->rights->holiday->write_all))) - { - $errors[] = $langs->trans('CantCreateCP'); - } else { - // Formulaire de demande de congés payés - print load_fiche_titre($langs->trans('MenuAddCP'), '', 'title_hrm.png'); + // Si l'utilisateur n'a pas le droit de faire une demande + if (($fuserid == $user->id && empty($user->rights->holiday->write)) || ($fuserid != $user->id && empty($user->rights->holiday->write_all))) + { + $errors[] = $langs->trans('CantCreateCP'); + } else { + // Formulaire de demande de congés payés + print load_fiche_titre($langs->trans('MenuAddCP'), '', 'title_hrm.png'); - // Si il y a une erreur - if (GETPOST('error')) { - switch (GETPOST('error')) { - case 'datefin' : - $errors[] = $langs->trans('ErrorEndDateCP'); - break; - case 'SQL_Create' : - $errors[] = $langs->trans('ErrorSQLCreateCP').' '.htmlentities($_GET['msg']).''; - break; - case 'CantCreate' : - $errors[] = $langs->trans('CantCreateCP'); - break; - case 'Valideur' : - $errors[] = $langs->trans('InvalidValidatorCP'); - break; - case 'nodatedebut' : - $errors[] = $langs->trans('NoDateDebut'); - break; - case 'nodatefin' : - $errors[] = $langs->trans('NoDateFin'); - break; - case 'DureeHoliday' : - $errors[] = $langs->trans('ErrorDureeCP'); - break; - case 'alreadyCP' : - $errors[] = $langs->trans('alreadyCPexist'); - break; - } + // Si il y a une erreur + if (GETPOST('error')) { + switch (GETPOST('error')) { + case 'datefin' : + $errors[] = $langs->trans('ErrorEndDateCP'); + break; + case 'SQL_Create' : + $errors[] = $langs->trans('ErrorSQLCreateCP').' '.htmlentities($_GET['msg']).''; + break; + case 'CantCreate' : + $errors[] = $langs->trans('CantCreateCP'); + break; + case 'Valideur' : + $errors[] = $langs->trans('InvalidValidatorCP'); + break; + case 'nodatedebut' : + $errors[] = $langs->trans('NoDateDebut'); + break; + case 'nodatefin' : + $errors[] = $langs->trans('NoDateFin'); + break; + case 'DureeHoliday' : + $errors[] = $langs->trans('ErrorDureeCP'); + break; + case 'alreadyCP' : + $errors[] = $langs->trans('alreadyCPexist'); + break; + } - setEventMessages($errors, null, 'errors'); - } + setEventMessages($errors, null, 'errors'); + } - $delayForRequest = $object->getConfCP('delayForRequest'); - //$delayForRequest = $delayForRequest * (60*60*24); + $delayForRequest = $object->getConfCP('delayForRequest'); + //$delayForRequest = $delayForRequest * (60*60*24); - $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); + $nextMonth = dol_time_plus_duree($now, $delayForRequest, 'd'); print ''."\n"; - // Formulaire de demande - print '
    '."\n"; - print ''."\n"; - print ''."\n"; + // Formulaire de demande + print ''."\n"; + print ''."\n"; + print ''."\n"; - if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) - { - dol_fiche_head('', '', '', -1); + if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) + { + dol_fiche_head('', '', '', -1); - $out = ''; - $typeleaves = $object->getTypes(1, 1); - foreach ($typeleaves as $key => $val) + $out = ''; + $typeleaves = $object->getTypes(1, 1); + foreach ($typeleaves as $key => $val) { $nb_type = $object->getCPforUser($user->id, $val['rowid']); $nb_holiday += $nb_type; @@ -959,528 +960,534 @@ if ((empty($id) && empty($ref)) || $action == 'add' || $action == 'request' || $ $out .= ' - '.($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']).': '.($nb_type ?price2num($nb_type) : 0).'
    '; //$out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
    '; } - print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; + print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; print $out; - dol_fiche_end(); - } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) - { - print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'
    '; - } + dol_fiche_end(); + } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) + { + print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'
    '; + } - dol_fiche_head(); + dol_fiche_head(); - //print ''.$langs->trans('DelayToRequestCP',$object->getConfCP('delayForRequest')).'

    '; + //print ''.$langs->trans('DelayToRequestCP',$object->getConfCP('delayForRequest')).'

    '; - print ''; - print ''; + print '
    '; + print ''; - // User for leave request - print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + if (empty($user->rights->holiday->write_all)) + { + print $form->select_dolusers(($fuserid ? $fuserid : $user->id), 'fuserid', 0, '', 0, 'hierarchyme', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); + //print ''; + } else print $form->select_dolusers(GETPOST('fuserid', 'int') ?GETPOST('fuserid', 'int') : $user->id, 'fuserid', 0, '', 0, '', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); + print ''; + print ''; - // Type - print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + } + print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ?GETPOST('type', 'alpha') : ''), 1); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print ''; + print ''; - // Date start - print ''; - print ''; - print ''; - print ''; + // Date start + print ''; + print ''; + print ''; + print ''; - // Date end - print ''; - print ''; - print ''; - print ''; + // Date end + print ''; + print ''; + print ''; + print ''; - // Approver - print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + //print $form->select_dolusers((GETPOST('valideur','int')>0?GETPOST('valideur','int'):$user->fk_user), "valideur", 1, ($user->admin ? '' : array($user->id)), 0, '', 0, 0, 0, 0, '', 0, '', '', 1); // By default, hierarchical parent + print ''; + print ''; - // Description - print ''; - print ''; - print ''; + // Description + print ''; + print ''; + print ''; - // Other attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; - print ''; - print '
    '.$langs->trans("User").''; + // User for leave request + print '
    '.$langs->trans("User").''; - if (empty($user->rights->holiday->write_all)) - { - print $form->select_dolusers(($fuserid ? $fuserid : $user->id), 'fuserid', 0, '', 0, 'hierarchyme', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); - //print ''; - } else print $form->select_dolusers(GETPOST('fuserid', 'int') ?GETPOST('fuserid', 'int') : $user->id, 'fuserid', 0, '', 0, '', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); - print '
    '.$langs->trans("Type").''; - $typeleaves = $object->getTypes(1, -1); - $arraytypeleaves = array(); - 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").')' : ''); + // Type + print '
    '.$langs->trans("Type").''; + $typeleaves = $object->getTypes(1, -1); + $arraytypeleaves = array(); + 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); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
    '; - print $langs->trans("DateDebCP"); - print ' ('.$langs->trans("FirstDayOfHoliday").')'; - print ''; - // Si la demande ne vient pas de l'agenda - if (!GETPOST('date_debut_')) { - print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1); - } else { - $tmpdate = dol_mktime(0, 0, 0, GETPOST('date_debut_month', 'int'), GETPOST('date_debut_day', 'int'), GETPOST('date_debut_year', 'int')); - print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1); - } - print '     '; - print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ?GETPOST('starthalfday', 'alpha') : 'morning')); - print '
    '; + print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday")); + print ''; + // Si la demande ne vient pas de l'agenda + if (!GETPOST('date_debut_')) { + print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1); + } else { + $tmpdate = dol_mktime(0, 0, 0, GETPOST('date_debut_month', 'int'), GETPOST('date_debut_day', 'int'), GETPOST('date_debut_year', 'int')); + print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1); + } + print '     '; + print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ?GETPOST('starthalfday', 'alpha') : 'morning')); + print '
    '; - print $langs->trans("DateFinCP"); - print ' ('.$langs->trans("LastDayOfHoliday").')'; - print ''; - // Si la demande ne vient pas de l'agenda - if (!GETPOST('date_fin_')) { - print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1); - } else { - $tmpdate = dol_mktime(0, 0, 0, GETPOST('date_fin_month', 'int'), GETPOST('date_fin_day', 'int'), GETPOST('date_fin_year', 'int')); - print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1); - } - print '     '; - print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ?GETPOST('endhalfday', 'alpha') : 'afternoon')); - print '
    '; + print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday")); + print ''; + // Si la demande ne vient pas de l'agenda + if (!GETPOST('date_fin_')) { + print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1); + } else { + $tmpdate = dol_mktime(0, 0, 0, GETPOST('date_fin_month', 'int'), GETPOST('date_fin_day', 'int'), GETPOST('date_fin_year', 'int')); + print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1); + } + print '     '; + print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ?GETPOST('endhalfday', 'alpha') : 'afternoon')); + print '
    '.$langs->trans("ReviewedByCP").''; + // Approver + print '
    '.$langs->trans("ReviewedByCP").''; - $object = new Holiday($db); - $include_users = $object->fetch_users_approver_holiday(); - if (empty($include_users)) 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'); - $s = $form->select_dolusers($defaultselectuser, "valideur", 1, "", 0, $include_users); - print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); - } + $object = new Holiday($db); + $include_users = $object->fetch_users_approver_holiday(); + if (empty($include_users)) 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'); + $s = $form->select_dolusers($defaultselectuser, "valideur", 1, "", 0, $include_users); + print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate")); + } - //print $form->select_dolusers((GETPOST('valideur','int')>0?GETPOST('valideur','int'):$user->fk_user), "valideur", 1, ($user->admin ? '' : array($user->id)), 0, '', 0, 0, 0, 0, '', 0, '', '', 1); // By default, hierarchical parent - print '
    '.$langs->trans("DescCP").''; - $doleditor = new DolEditor('description', GETPOST('description', 'none'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
    '.$langs->trans("DescCP").''; + $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
    '; + print '
    '; - dol_fiche_end(); + dol_fiche_end(); - print '
    '; - print ''; - print '    '; - print ''; - print '
    '; + print '
    '; + print ''; + print '    '; + print ''; + print '
    '; - print ''."\n"; - } + print ''."\n"; + } } else { - if ($error) - { - print '
    '; - print $error; - print '

    '; - print '
    '; - } else { - // Affichage de la fiche d'une demande de congés payés - if (($id > 0) || $ref) - { - $result = $object->fetch($id, $ref); + if ($error) + { + print '
    '; + print $error; + print '

    '; + print '
    '; + } else { + // Affichage de la fiche d'une demande de congés payés + if (($id > 0) || $ref) + { + $result = $object->fetch($id, $ref); - $valideur = new User($db); - $valideur->fetch($object->fk_validator); + $valideur = new User($db); + $valideur->fetch($object->fk_validator); - $userRequest = new User($db); - $userRequest->fetch($object->fk_user); + $userRequest = new User($db); + $userRequest->fetch($object->fk_user); - //print load_fiche_titre($langs->trans('TitreRequestCP')); + //print load_fiche_titre($langs->trans('TitreRequestCP')); - // Si il y a une erreur - if (GETPOST('error')) - { - switch (GETPOST('error')) - { - case 'datefin' : - $errors[] = $langs->transnoentitiesnoconv('ErrorEndDateCP'); - break; - case 'SQL_Create' : - $errors[] = $langs->transnoentitiesnoconv('ErrorSQLCreateCP').' '.$_GET['msg']; - break; - case 'CantCreate' : - $errors[] = $langs->transnoentitiesnoconv('CantCreateCP'); - break; - case 'Valideur' : - $errors[] = $langs->transnoentitiesnoconv('InvalidValidatorCP'); - break; - case 'nodatedebut' : - $errors[] = $langs->transnoentitiesnoconv('NoDateDebut'); - break; - case 'nodatefin' : - $errors[] = $langs->transnoentitiesnoconv('NoDateFin'); - break; - case 'DureeHoliday' : - $errors[] = $langs->transnoentitiesnoconv('ErrorDureeCP'); - break; - case 'NoMotifRefuse' : - $errors[] = $langs->transnoentitiesnoconv('NoMotifRefuseCP'); - break; - case 'mail' : - $errors[] = $langs->transnoentitiesnoconv('ErrorMailNotSend')."\n".$_GET['error_content']; - break; - } + // Si il y a une erreur + if (GETPOST('error')) + { + switch (GETPOST('error')) + { + case 'datefin' : + $errors[] = $langs->transnoentitiesnoconv('ErrorEndDateCP'); + break; + case 'SQL_Create' : + $errors[] = $langs->transnoentitiesnoconv('ErrorSQLCreateCP').' '.$_GET['msg']; + break; + case 'CantCreate' : + $errors[] = $langs->transnoentitiesnoconv('CantCreateCP'); + break; + case 'Valideur' : + $errors[] = $langs->transnoentitiesnoconv('InvalidValidatorCP'); + break; + case 'nodatedebut' : + $errors[] = $langs->transnoentitiesnoconv('NoDateDebut'); + break; + case 'nodatefin' : + $errors[] = $langs->transnoentitiesnoconv('NoDateFin'); + break; + case 'DureeHoliday' : + $errors[] = $langs->transnoentitiesnoconv('ErrorDureeCP'); + break; + case 'NoMotifRefuse' : + $errors[] = $langs->transnoentitiesnoconv('NoMotifRefuseCP'); + break; + case 'mail' : + $errors[] = $langs->transnoentitiesnoconv('ErrorMailNotSend')."\n".$_GET['error_content']; + break; + } - setEventMessages($errors, null, 'errors'); - } + setEventMessages($errors, null, 'errors'); + } - // On vérifie si l'utilisateur à le droit de lire cette demande - if ($cancreate) - { - $head = holiday_prepare_head($object); + // On vérifie si l'utilisateur à le droit de lire cette demande + 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 ''."\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - } + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + } - dol_fiche_head($head, 'card', $langs->trans("CPTitreMenu"), -1, 'holiday'); + dol_fiche_head($head, 'card', $langs->trans("CPTitreMenu"), -1, 'holiday'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref'); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; - print ''; + print '
    '; + print ''; - // User - print ''; - print ''; - print ''; + // User + print ''; + print ''; + print ''; - // Type - print ''; - print ''; - print ''; - print ''; + // Type + print ''; + print ''; + print ''; + print ''; - $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning'; - $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon'; + $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning'; + $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon'; - if (!$edit) - { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + if (!$edit) + { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + print ''; + } - if (!$edit) - { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + if (!$edit) + { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + print ''; + } - // Nb of days - print ''; - print ''; - print ''; - print ''; + // Nb of days + print ''; + print ''; + print ''; + print ''; - if ($object->statut == Holiday::STATUS_REFUSED) - { - print ''; - print ''; - print ''; - print ''; - } + if ($object->statut == Holiday::STATUS_REFUSED) + { + print ''; + print ''; + print ''; + print ''; + } - // Description - if (!$edit) - { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - } + // Description + if (!$edit) + { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + } - // Other attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print ''; - print '
    '.$langs->trans("User").''; - print $userRequest->getNomUrl(-1, 'leave'); - print '
    '.$langs->trans("User").''; + print $userRequest->getNomUrl(-1, 'leave'); + print '
    '.$langs->trans("Type").''; - $typeleaves = $object->getTypes(1, -1); - $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']); - print empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow; - print '
    '.$langs->trans("Type").''; + $typeleaves = $object->getTypes(1, -1); + $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']); + print empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow; + print '
    '.$langs->trans('DateDebCP').' ('.$langs->trans("FirstDayOfHoliday").')'.dol_print_date($object->date_debut, 'day'); - print '     '; - print ''.$langs->trans($listhalfday[$starthalfday]).''; - print '
    '.$langs->trans('DateDebCP').' ('.$langs->trans("FirstDayOfHoliday").')'; - print $form->selectDate($object->date_debut, 'date_debut_'); - print '     '; - print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday') ?GETPOST('starthalfday') : $starthalfday)); - print '
    '; + print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); + print ''.dol_print_date($object->date_debut, 'day'); + print '     '; + print ''.$langs->trans($listhalfday[$starthalfday]).''; + print '
    '; + print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); + print ''; + print $form->selectDate($object->date_debut, 'date_debut_'); + print '     '; + print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday') ?GETPOST('starthalfday') : $starthalfday)); + print '
    '.$langs->trans('DateFinCP').' ('.$langs->trans("LastDayOfHoliday").')'.dol_print_date($object->date_fin, 'day'); - print '     '; - print ''.$langs->trans($listhalfday[$endhalfday]).''; - print '
    '.$langs->trans('DateFinCP').' ('.$langs->trans("LastDayOfHoliday").')'; - print $form->selectDate($object->date_fin, 'date_fin_'); - print '     '; - print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ?GETPOST('endhalfday') : $endhalfday)); - print '
    '; + print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); + print ''.dol_print_date($object->date_fin, 'day'); + print '     '; + print ''.$langs->trans($listhalfday[$endhalfday]).''; + print '
    '; + print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); + print ''; + print $form->selectDate($object->date_fin, 'date_fin_'); + print '     '; + print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ?GETPOST('endhalfday') : $endhalfday)); + print '
    '; - $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 .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); - if ($includesunday) $htmlhelp .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); - print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp); - print '
    '; - print num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); - print '
    '; + $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 .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); + if ($includesunday) $htmlhelp .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp); + print '
    '; + print num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday); + print '
    '.$langs->trans('DetailRefusCP').''.$object->detail_refuse.'
    '.$langs->trans('DetailRefusCP').''.$object->detail_refuse.'
    '.$langs->trans('DescCP').''.nl2br($object->description).'
    '.$langs->trans('DescCP').''; - $doleditor = new DolEditor('description', $object->description, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
    '.$langs->trans('DescCP').''.nl2br($object->description).'
    '.$langs->trans('DescCP').''; + $doleditor = new DolEditor('description', $object->description, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
    '."\n"; + print ''; + print ''."\n"; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print '
    '; + print '
    '; // Info workflow - print ''."\n"; - print ''; + print '
    '."\n"; + print ''; - if (!empty($object->fk_user_create)) - { - $userCreate = new User($db); - $userCreate->fetch($object->fk_user_create); - print ''; - print ''; - print ''; - print ''; - } + if (!empty($object->fk_user_create)) + { + $userCreate = new User($db); + $userCreate->fetch($object->fk_user_create); + print ''; + print ''; + print ''; + print ''; + } - // Approver - if (!$edit && $action != 'editvalidator') { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + // Approver + if (!$edit && $action != 'editvalidator') { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + print ''; + } - print ''; - print ''; - print ''; - print ''; - if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) { - print ''; - print ''; - print ''; // warning: date_valid is approval date on holiday module - print ''; - } - if ($object->statut == Holiday::STATUS_CANCELED) { - print ''; - print ''; - print ''; - print ''; - } - if ($object->statut == Holiday::STATUS_REFUSED) { - print ''; - print ''; - print ''; - print ''; - } - print ''; - print '
    '.$langs->trans('RequestByCP').''.$userCreate->getNomUrl(-1).'
    '.$langs->trans('RequestByCP').''.$userCreate->getNomUrl(-1).'
    '; - if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) print $langs->trans('ApprovedBy'); - else print $langs->trans('ReviewedByCP'); - print ''.$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) - { - print ''.img_edit($langs->trans("Edit")).''; - } - print '
    '.$langs->trans('ReviewedByCP').''; - $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. - { - $include_users[] = $object->fk_validator; - } - 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') - { - print ''; - print ''; - } - print '
    '; + if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) print $langs->trans('ApprovedBy'); + else print $langs->trans('ReviewedByCP'); + print ''.$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) + { + print ''.img_edit($langs->trans("Edit")).''; + } + print '
    '.$langs->trans('ReviewedByCP').''; + $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. + { + $include_users[] = $object->fk_validator; + } + 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') + { + print ''; + print ''; + } + print '
    '.$langs->trans('DateCreation').''.dol_print_date($object->date_create, 'dayhour').'
    '.$langs->trans('DateValidCP').''.dol_print_date($object->date_valid, 'dayhour').'
    '.$langs->trans('DateCancelCP').''.dol_print_date($object->date_cancel, 'dayhour').'
    '.$langs->trans('DateRefusCP').''.dol_print_date($object->date_refuse, 'dayhour').'
    '; + print ''; + print ''.$langs->trans('DateCreation').''; + print ''.dol_print_date($object->date_create, 'dayhour').''; + print ''; + if ($object->statut == Holiday::STATUS_APPROVED || $object->statut == Holiday::STATUS_CANCELED) { + print ''; + print ''.$langs->trans('DateValidCP').''; + print ''.dol_print_date($object->date_valid, 'dayhour').''; // warning: date_valid is approval date on holiday module + print ''; + } + if ($object->statut == Holiday::STATUS_CANCELED) { + print ''; + print ''.$langs->trans('DateCancelCP').''; + print ''.dol_print_date($object->date_cancel, 'dayhour').''; + print ''; + } + if ($object->statut == Holiday::STATUS_REFUSED) { + print ''; + print ''.$langs->trans('DateRefusCP').''; + print ''.dol_print_date($object->date_refuse, 'dayhour').''; + print ''; + } + print ''; + print ''; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print '
    '; + print '
    '; - dol_fiche_end(); + dol_fiche_end(); - // Confirmation messages - 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); - } - } + // Confirmation messages + 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) - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleToValidCP"), $langs->trans("ConfirmToValidCP"), "confirm_send", '', 1, 1); - } + // Si envoi en validation + 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') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleValidCP"), $langs->trans("ConfirmValidCP"), "confirm_valid", '', 1, 1); - } + // Si validation de la demande + 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') - { - $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 refus de la demande + 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') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleCancelCP"), $langs->trans("ConfirmCancelCP"), "confirm_cancel", '', 1, 1); - } + // Si annulation de la demande + 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') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleSetToDraft"), $langs->trans("ConfirmSetToDraft"), "confirm_draft", '', 1, 1); - } + // Si back to draft + 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) - { - print '
    '; - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) - { - print ''; - } - print '
    '; - } + if (($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) + { + if ($action == 'edit' && $object->statut == Holiday::STATUS_DRAFT) + { + print '
    '; + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) + { + print ''; + } + print '
    '; + } - print ''; - } + print ''; + } - if (!$edit) - { - // Buttons for actions + if (!$edit) + { + // Buttons for actions - print '
    '; + print '
    '; - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) - { - print ''.$langs->trans("EditCP").''; - } - if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) // If draft - { - print ''.$langs->trans("Validate").''; - } - if ($object->statut == Holiday::STATUS_VALIDATED) // If validated - { - if ($user->id == $object->fk_validator) - { - print ''.$langs->trans("Approve").''; - print ''.$langs->trans("ActionRefuseCP").''; - } else { - print ''.$langs->trans("Approve").''; - print ''.$langs->trans("ActionRefuseCP").''; - } - } - if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all)) && ($object->statut == 2 || $object->statut == 3)) // Status validated or approved - { - if (($object->date_debut > dol_now()) || $user->admin) print ''.$langs->trans("ActionCancelCP").''; - else print ''.$langs->trans("ActionCancelCP").''; - } - if ($cancreate && $object->statut == Holiday::STATUS_CANCELED) - { - print ''.$langs->trans("SetToDraft").''; - } - if ($candelete && ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED)) // If draft or canceled or refused - { - print ''.$langs->trans("DeleteCP").''; - } + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) + { + print ''.$langs->trans("EditCP").''; + } + if ($cancreate && $object->statut == Holiday::STATUS_DRAFT) // If draft + { + print ''.$langs->trans("Validate").''; + } + if ($object->statut == Holiday::STATUS_VALIDATED) // If validated + { + if ($user->id == $object->fk_validator) + { + print ''.$langs->trans("Approve").''; + print ''.$langs->trans("ActionRefuseCP").''; + } else { + print ''.$langs->trans("Approve").''; + print ''.$langs->trans("ActionRefuseCP").''; + } + } + if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all)) && ($object->statut == 2 || $object->statut == 3)) // Status validated or approved + { + if (($object->date_debut > dol_now()) || $user->admin) print ''.$langs->trans("ActionCancelCP").''; + else print ''.$langs->trans("ActionCancelCP").''; + } + if ($cancreate && $object->statut == Holiday::STATUS_CANCELED) + { + print ''.$langs->trans("SetToDraft").''; + } + if ($candelete && ($object->statut == Holiday::STATUS_DRAFT || $object->statut == Holiday::STATUS_CANCELED || $object->statut == Holiday::STATUS_REFUSED)) // If draft or canceled or refused + { + print ''.$langs->trans("DeleteCP").''; + } - print '
    '; - } - } else { - print '
    '; - print $langs->trans('ErrorUserViewCP'); - print '

    '; - print '
    '; - } - } else { - print '
    '; - print $langs->trans('ErrorIDFicheCP'); - print '

    '; - print '
    '; - } - } + print '
    '; + } + } else { + print '
    '; + print $langs->trans('ErrorUserViewCP'); + print '

    '; + print '
    '; + } + } else { + print '
    '; + print $langs->trans('ErrorIDFicheCP'); + print '

    '; + print '
    '; + } + } } // End of page diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index ce4c74d786a..b702bbf5353 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -1122,7 +1122,7 @@ 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->escape($status).")"; + if ($status != '-1') $sql .= " AND cp.statut IN (".$this->db->sanitize($this->db->escape($status)).")"; $resql = $this->db->query($sql); if ($resql) @@ -1178,7 +1178,11 @@ class Holiday extends CommonObject $result = ''; - $label = $langs->trans("Show").': '.$this->ref; + $label = img_picto('', $this->picto).' '.$langs->trans("Holiday").''; + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + if (isset($this->statut)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id; @@ -1269,20 +1273,22 @@ class Holiday extends CommonObject $nb = count($name) + 1; // Select HTML - $statut = ''."\n"; + $out .= ''."\n"; // Boucle des statuts for ($i = 1; $i < $nb; $i++) { if ($i == $selected) { - $statut .= ''."\n"; + $out .= ''."\n"; } else { - $statut .= ''."\n"; + $out .= ''."\n"; } } - $statut .= ''."\n"; - print $statut; + $out .= ''."\n"; + $out .= ajax_combobox($htmlname); + + print $out; } /** @@ -1296,8 +1302,8 @@ class Holiday extends CommonObject { $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; - $sql .= " value = '".$value."'"; - $sql .= " WHERE name = '".$name."'"; + $sql .= " value = '".$this->db->escape($value)."'"; + $sql .= " WHERE name = '".$this->db->escape($name)."'"; dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG); $result = $this->db->query($sql); @@ -1492,7 +1498,7 @@ class Holiday extends CommonObject $sql = "SELECT value"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config"; - $sql .= " WHERE name = '".$name."'"; + $sql .= " WHERE name = '".$this->db->escape($name)."'"; $result = $this->db->query($sql); @@ -1516,7 +1522,7 @@ class Holiday extends CommonObject */ public function createCPusers($single = false, $userid = '') { - // Si c'est l'ensemble des utilisateurs à ajouter + // do we have to add balance for all users ? if (!$single) { dol_syslog(get_class($this).'::createCPusers'); @@ -1526,7 +1532,7 @@ class Holiday extends CommonObject { $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; $sql .= " (fk_user, nb_holiday)"; - $sql .= " VALUES ('".$users['rowid']."','0')"; + $sql .= " VALUES (".((int) $users['rowid'])."', '0')"; $resql = $this->db->query($sql); if (!$resql) dol_print_error($this->db); @@ -1534,7 +1540,7 @@ class Holiday extends CommonObject } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; $sql .= " (fk_user, nb_holiday)"; - $sql .= " VALUES ('".$userid."','0')"; + $sql .= " VALUES (".((int) $userid)."', '0')"; $resql = $this->db->query($sql); if (!$resql) dol_print_error($this->db); @@ -1551,7 +1557,7 @@ class Holiday extends CommonObject { $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users"; - $sql .= " WHERE fk_user = '".$user_id."'"; + $sql .= " WHERE fk_user = ".((int) $user_id); $this->db->query($sql); } @@ -1919,11 +1925,11 @@ class Holiday extends CommonObject $sql .= "fk_type"; $sql .= ") VALUES ("; $sql .= " '".$this->db->idate(dol_now())."',"; - $sql .= " '".$fk_user_action."',"; - $sql .= " '".$fk_user_update."',"; + $sql .= " '".$this->db->escape($fk_user_action)."',"; + $sql .= " '".$this->db->escape($fk_user_update)."',"; $sql .= " '".$this->db->escape($label)."',"; - $sql .= " '".$prev_solde."',"; - $sql .= " '".$new_solde."',"; + $sql .= " '".$this->db->escape($prev_solde)."',"; + $sql .= " '".$this->db->escape($new_solde)."',"; $sql .= " ".$fk_type; $sql .= ")"; diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php index 0e83d68509d..af646984045 100644 --- a/htdocs/holiday/define_holiday.php +++ b/htdocs/holiday/define_holiday.php @@ -41,8 +41,8 @@ $search_supervisor = GETPOST('search_supervisor', 'int'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php index 256e69028f2..bdd791e80f1 100644 --- a/htdocs/holiday/document.php +++ b/htdocs/holiday/document.php @@ -41,7 +41,7 @@ $langs->loadLangs(array('other', 'holiday', 'companies')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check @@ -50,8 +50,8 @@ $result = restrictedArea($user, 'holiday', $id, 'holiday'); // Get parameters $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -130,7 +130,8 @@ if ($object->id) print ''.$langs->trans("Type").''; print ''; $typeleaves = $object->getTypes(1, -1); - print empty($typeleaves[$object->fk_type]['label']) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $typeleaves[$object->fk_type]['label']; + $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']); + print empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow; print ''; print ''; @@ -140,7 +141,9 @@ if ($object->id) if (!$edit) { print ''; - print ''.$langs->trans('DateDebCP').' ('.$langs->trans("FirstDayOfHoliday").')'; + print ''; + print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); + print ''; print ''.dol_print_date($object->date_debut, 'day'); print '     '; print ''.$langs->trans($listhalfday[$starthalfday]).''; @@ -148,7 +151,9 @@ if ($object->id) print ''; } else { print ''; - print ''.$langs->trans('DateDebCP').' ('.$langs->trans("FirstDayOfHoliday").')'; + print ''; + print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); + print ''; print ''; print $form->selectDate($object->date_debut, 'date_debut_'); print '     '; @@ -160,7 +165,9 @@ if ($object->id) if (!$edit) { print ''; - print ''.$langs->trans('DateFinCP').' ('.$langs->trans("LastDayOfHoliday").')'; + print ''; + print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); + print ''; print ''.dol_print_date($object->date_fin, 'day'); print '     '; print ''.$langs->trans($listhalfday[$endhalfday]).''; @@ -168,7 +175,9 @@ if ($object->id) print ''; } else { print ''; - print ''.$langs->trans('DateFinCP').' ('.$langs->trans("LastDayOfHoliday").')'; + print ''; + print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); + print ''; print ''; print $form->selectDate($object->date_fin, 'date_fin_'); print '     '; @@ -176,8 +185,17 @@ if ($object->id) print ''; print ''; } + + // Nb days consumed print ''; - print ''.$langs->trans('NbUseDaysCP').''; + print ''; + $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 .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday")); + if ($includesunday) $htmlhelp .= '
    '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday")); + print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp); + print ''; print ''.num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday).''; print ''; diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index 5a4f782deac..ca83d9341f2 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -83,8 +83,8 @@ $diroutputmassaction = $conf->holiday->dir_output.'/temp/massgeneration/'.$user- // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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 $offset = $limit * $page; @@ -106,7 +106,7 @@ $search_month_end = GETPOST('search_month_end', 'int'); $search_year_end = GETPOST('search_year_end', 'int'); $search_employee = GETPOST('search_employee', 'int'); $search_valideur = GETPOST('search_valideur', 'int'); -$search_statut = GETPOST('search_statut', 'int'); +$search_status = GETPOST('search_status', 'int'); $search_type = GETPOST('search_type', 'int'); // Initialize technical objects @@ -182,7 +182,7 @@ if (empty($reshook)) $search_year_end = ""; $search_employee = ""; $search_valideur = ""; - $search_statut = ""; + $search_status = ""; $search_type = ''; $toselect = ''; $search_array_options = array(); @@ -253,7 +253,7 @@ $sql .= " cp.description,"; $sql .= " cp.date_debut,"; $sql .= " cp.date_fin,"; $sql .= " cp.halfday,"; -$sql .= " cp.statut,"; +$sql .= " cp.statut as status,"; $sql .= " cp.fk_validator,"; $sql .= " cp.date_valid,"; $sql .= " cp.fk_user_valid,"; @@ -268,7 +268,7 @@ $sql .= " uu.firstname as user_firstname,"; $sql .= " uu.admin as user_admin,"; $sql .= " uu.email as user_email,"; $sql .= " uu.login as user_login,"; -$sql .= " uu.statut as user_statut,"; +$sql .= " uu.statut as user_status,"; $sql .= " uu.photo as user_photo,"; $sql .= " ua.lastname as validator_lastname,"; @@ -276,7 +276,7 @@ $sql .= " ua.firstname as validator_firstname,"; $sql .= " ua.admin as validator_admin,"; $sql .= " ua.email as validator_email,"; $sql .= " ua.login as validator_login,"; -$sql .= " ua.statut as validator_statut,"; +$sql .= " ua.statut as validator_status,"; $sql .= " ua.photo as validator_photo"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { @@ -311,11 +311,11 @@ if (!empty($search_valideur) && $search_valideur != -1) { } // Type if (!empty($search_type) && $search_type != -1) { - $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; + $sql .= ' AND cp.fk_type IN ('.$db->sanitize($db->escape($search_type)).')'; } // Status -if (!empty($search_statut) && $search_statut != -1) { - $sql .= " AND cp.statut = '".$db->escape($search_statut)."'\n"; +if (!empty($search_status) && $search_status != -1) { + $sql .= " AND cp.statut = '".$db->escape($search_status)."'\n"; } if (empty($user->rights->holiday->read_all)) $sql .= ' AND cp.fk_user IN ('.join(',', $childids).')'; @@ -371,7 +371,7 @@ if ($resql) 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_statut > 0) $param .= '&search_statut='.urlencode($search_statut); + 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'; @@ -425,18 +425,14 @@ if ($resql) if ($canedit) { - print ''.$langs->trans("AddCP").''; + print ''.$langs->trans("AddCP").''; } print '
    '; } else { $title = $langs->trans("ListeCP"); - $newcardbutton = ''; - if ($user->rights->holiday->write) - { - $newcardbutton .= dolGetButtonTitle($langs->trans('MenuAddCP'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/holiday/card.php?action=request'); - } + $newcardbutton = dolGetButtonTitle($langs->trans('MenuAddCP'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/holiday/card.php?action=create', '', $user->rights->holiday->write); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_hrm', 0, $newcardbutton, '', $limit, 0, 0, 1); } @@ -504,7 +500,7 @@ if ($resql) } print ''; - print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); + print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150'); print ''; } @@ -519,7 +515,7 @@ if ($resql) $valideurobjects = $validator->listUsersForGroup($excludefilter); $valideurarray = array(); 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, '', 'maxwidth200'); + print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150'); print ''; } else { print ' '; @@ -541,7 +537,7 @@ if ($resql) //$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':''); $arraytypeleaves[$val['rowid']] = $labeltoshow; } - print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1); + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1); } print ''; } @@ -599,7 +595,7 @@ if ($resql) if (!empty($arrayfields['cp.statut']['checked'])) { print ''; - $object->selectStatutCP($search_statut, 'search_statut'); + $object->selectStatutCP($search_status, 'search_status'); print ''; } @@ -616,7 +612,7 @@ if ($resql) 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 '); + 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 @@ -656,6 +652,7 @@ if ($resql) // Leave request $holidaystatic->id = $obj->rowid; $holidaystatic->ref = ($obj->ref ? $obj->ref : $obj->rowid); + $holidaystatic->statut = $obj->status; // User $userstatic->id = $obj->fk_user; @@ -664,7 +661,7 @@ if ($resql) $userstatic->admin = $obj->user_admin; $userstatic->email = $obj->user_email; $userstatic->login = $obj->user_login; - $userstatic->statut = $obj->user_statut; + $userstatic->statut = $obj->user_status; $userstatic->photo = $obj->user_photo; // Validator @@ -674,7 +671,7 @@ if ($resql) $approbatorstatic->admin = $obj->validator_admin; $approbatorstatic->email = $obj->validator_email; $approbatorstatic->login = $obj->validator_login; - $approbatorstatic->statut = $obj->validator_statut; + $approbatorstatic->statut = $obj->validator_status; $approbatorstatic->photo = $obj->validator_photo; $date = $obj->date_create; @@ -694,12 +691,12 @@ if ($resql) } if (!empty($arrayfields['cp.fk_user']['checked'])) { - print ''.$userstatic->getNomUrl(-1, 'leave').''; + print ''.$userstatic->getNomUrl(-1, 'leave').''; if (!$i) $totalarray['nbfield']++; } if (!empty($arrayfields['cp.fk_validator']['checked'])) { - print ''.$approbatorstatic->getNomUrl(-1).''; + print ''.$approbatorstatic->getNomUrl(-1).''; if (!$i) $totalarray['nbfield']++; } if (!empty($arrayfields['cp.fk_type']['checked'])) @@ -722,7 +719,7 @@ if ($resql) { print ''; print dol_print_date($db->jdate($obj->date_debut), 'day'); - print ' ('.$langs->trans($listhalfday[$starthalfday]).')'; + print ' ('.$langs->trans($listhalfday[$starthalfday]).')'; print ''; if (!$i) $totalarray['nbfield']++; } @@ -730,7 +727,7 @@ if ($resql) { print ''; print dol_print_date($db->jdate($obj->date_fin), 'day'); - print ' ('.$langs->trans($listhalfday[$endhalfday]).')'; + print ' ('.$langs->trans($listhalfday[$endhalfday]).')'; print ''; if (!$i) $totalarray['nbfield']++; } @@ -755,7 +752,7 @@ if ($resql) } if (!empty($arrayfields['cp.statut']['checked'])) { - print ''.$holidaystatic->LibStatut($obj->statut, 5).''; + print ''.$holidaystatic->getLibStatut(5).''; if (!$i) $totalarray['nbfield']++; } diff --git a/htdocs/holiday/month_report.php b/htdocs/holiday/month_report.php index b6da0427464..7e7e7ed29f9 100644 --- a/htdocs/holiday/month_report.php +++ b/htdocs/holiday/month_report.php @@ -48,10 +48,13 @@ $massaction = GETPOST('massaction', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ'); $optioncss = GETPOST('optioncss', 'aZ'); -$search_ref = GETPOST('search_ref', 'alpha'); +$search_ref = GETPOST('search_ref', 'alphanohtml'); +$search_employee = GETPOST('search_employee', 'int'); +$search_type = GETPOST('search_type', 'int'); +$search_description = GETPOST('search_description', 'alphanohtml'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'alpha'); if (! $sortfield) $sortfield = "cp.rowid"; @@ -82,6 +85,9 @@ 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_ref = ''; + $search_employee = ''; + $search_type = ''; + $search_description = ''; $toselect = ''; $search_array_options = array(); } @@ -135,7 +141,10 @@ $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 ($search_ref != '') $sql.= natural_search('cp.ref', $search_ref, 0); +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); @@ -149,9 +158,12 @@ 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 ($search_ref) $param = '&search_ref='.urlencode($search_ref); +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 '
    '; if ($optioncss != '') print ''; @@ -184,16 +196,50 @@ print '
    '; print ''; print ''; -if (!empty($arrayfields['cp.ref']['checked'])) print ''; -if (!empty($arrayfields['cp.fk_user']['checked'])) print ''; -if (!empty($arrayfields['ct.label']['checked'])) print ''; + +// Filter: Ref +if (!empty($arrayfields['cp.ref']['checked'])) { + print ''; +} + +// Filter: Employee +if (!empty($arrayfields['cp.fk_user']['checked'])) { + print ''; +} + +// Filter: Type +if (!empty($arrayfields['ct.label']['checked'])) { + $typeleaves = $holidaystatic->getTypes(1, -1); + $arraytypeleaves = array(); + foreach ($typeleaves as $key => $val) + { + $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); + $arraytypeleaves[$val['rowid']] = $labeltoshow; + } + + print ''; +} + if (!empty($arrayfields['cp.date_debut']['checked'])) print ''; if (!empty($arrayfields['cp.date_fin']['checked'])) print ''; if (!empty($arrayfields['used_days']['checked'])) print ''; if (!empty($arrayfields['date_start_month']['checked'])) print ''; if (!empty($arrayfields['date_end_month']['checked'])) print ''; if (!empty($arrayfields['used_days_month']['checked'])) print ''; -if (!empty($arrayfields['cp.description']['checked'])) print ''; + +// Filter: Description +if (!empty($arrayfields['cp.description']['checked'])) { + print ''; +} + // Action column print '
    '; + print ''; + print ''; + print $form->select_dolusers($search_employee, "search_employee", 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + print ''; + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1); + print ''; + print ''; + print ''; $searchpicto = $form->showFilterButtons(); diff --git a/htdocs/holiday/view_log.php b/htdocs/holiday/view_log.php index 44d57e9860a..4ff8238648c 100644 --- a/htdocs/holiday/view_log.php +++ b/htdocs/holiday/view_log.php @@ -51,8 +51,8 @@ if (empty($year)) // Load variable for pagination $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); +$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; diff --git a/htdocs/hrm/admin/admin_establishment.php b/htdocs/hrm/admin/admin_establishment.php index a260941ab0d..ea266a644e0 100644 --- a/htdocs/hrm/admin/admin_establishment.php +++ b/htdocs/hrm/admin/admin_establishment.php @@ -32,13 +32,6 @@ if (!$user->admin) $error = 0; -// List of statut -static $tmpstatus2label = array( - '0'=>'OpenEtablishment', - '1'=>'CloseEtablishment' -); -$status2label = array(''); -foreach ($tmpstatus2label as $key => $val) $status2label[$key] = $langs->trans($val); /* * Actions @@ -51,11 +44,14 @@ foreach ($tmpstatus2label as $key => $val) $status2label[$key] = $langs->trans($ * View */ +$form = new Form($db); +$establishmenttmp = new Establishment($db); + llxHeader('', $langs->trans("Establishments")); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortorder = GETPOST("sortorder"); -$sortfield = GETPOST("sortfield"); +$sortorder = GETPOST("sortorder", 'alpha'); +$sortfield = GETPOST("sortfield", 'alpha'); if (!$sortorder) $sortorder = "DESC"; if (!$sortfield) $sortfield = "e.rowid"; @@ -68,11 +64,6 @@ $pageprev = $page - 1; $pagenext = $page + 1; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$form = new Form($db); -$establishmenttmp = new Establishment($db); - -dol_htmloutput_mesg($mesg); - // Subheader $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("HRMSetup"), $linkback); @@ -81,7 +72,7 @@ print load_fiche_titre($langs->trans("HRMSetup"), $linkback); $head = hrm_admin_prepare_head(); dol_fiche_head($head, 'establishments', $langs->trans("HRM"), -1, "user"); -$sql = "SELECT e.rowid, e.name, e.address, e.zip, e.town, e.status"; +$sql = "SELECT e.rowid, e.label, e.address, e.zip, e.town, e.status"; $sql .= " FROM ".MAIN_DB_PREFIX."establishment as e"; $sql .= " WHERE e.entity IN (".getEntity('establishment').')'; $sql .= $db->order($sortfield, $sortorder); @@ -96,42 +87,44 @@ if ($result) // Load attribute_label print ''; print ''; - print_liste_field_titre("Name", $_SERVER["PHP_SELF"], "e.name", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "e.ref", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "e.label", "", "", "", $sortfield, $sortorder); print_liste_field_titre("Address", $_SERVER["PHP_SELF"], "e.address", "", "", "", $sortfield, $sortorder); - print_liste_field_titre("Zipcode", $_SERVER["PHP_SELF"], "e.zip", "", "", "", $sortfield, $sortorder); + print_liste_field_titre("Zip", $_SERVER["PHP_SELF"], "e.zip", "", "", "", $sortfield, $sortorder); print_liste_field_titre("Town", $_SERVER["PHP_SELF"], "e.town", "", "", "", $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "e.status", "", "", '', $sortfield, $sortorder, 'right '); print "\n"; if ($num > 0) - { - $establishmentstatic = new Establishment($db); + { + $establishmentstatic = new Establishment($db); while ($i < min($num, $limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); $establishmentstatic->id = $obj->rowid; - $establishmentstatic->name = $obj->name; + $establishmentstatic->ref = $obj->ref; + $establishmentstatic->label = $obj->label; $establishmentstatic->status = $obj->status; print ''; print ''; - print ''; + print ''; + print ''; print ''; print ''; - - print ''; - print "\n"; + print "\n"; - $i++; - } - } else { - print ''; - } + $i++; + } + } else { + print ''; + } print '
    '.$establishmentstatic->getNomUrl(1).''.$obj->address.''.$obj->label.''.$obj->address.''.$obj->zip.''.$obj->town.''; + print ''; print $establishmentstatic->getLibStatut(5); print '
    '.$langs->trans("None").'
    '.$langs->trans("None").'
    '; } else { @@ -142,7 +135,7 @@ dol_fiche_end(); // Buttons print ''; // End of page diff --git a/htdocs/hrm/admin/admin_hrm.php b/htdocs/hrm/admin/admin_hrm.php index c839e7c4cd4..79bf11f7ec9 100644 --- a/htdocs/hrm/admin/admin_hrm.php +++ b/htdocs/hrm/admin/admin_hrm.php @@ -30,11 +30,11 @@ $langs->loadLangs(array('admin', 'hrm')); if (!$user->admin) accessforbidden(); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); // Other parameters HRM_* $list = array( - 'HRM_EMAIL_EXTERNAL_SERVICE' // To prevent your public accountant for example +// 'HRM_EMAIL_EXTERNAL_SERVICE' // To prevent your public accountant for example ); /* @@ -58,9 +58,11 @@ if ($action == 'update') { } } + /* * View */ + llxHeader('', $langs->trans('Parameters')); $form = new Form($db); @@ -82,7 +84,7 @@ dol_fiche_head($head, 'parameters', $langs->trans("HRM"), -1, "user"); print ''; print ''; -print ''; +print ''; print "\n"; foreach ($list as $key) { diff --git a/htdocs/hrm/class/establishment.class.php b/htdocs/hrm/class/establishment.class.php index 2bbe374d1d0..d2b53337abe 100644 --- a/htdocs/hrm/class/establishment.class.php +++ b/htdocs/hrm/class/establishment.class.php @@ -60,12 +60,12 @@ class Establishment extends CommonObject */ public $picto = 'building'; - /** + /** * @var int ID */ public $id; - /** + /** * @var string Ref */ public $ref; @@ -75,7 +75,7 @@ class Establishment extends CommonObject */ public $rowid; - public $name; + public $label; /** * @var string Address @@ -97,11 +97,31 @@ class Establishment extends CommonObject public $country_id; - public $statuts = array(); - public $statuts_short = array(); - const STATUS_OPEN = 0; - const STATUS_CLOSED = 1; + const STATUS_OPEN = 1; + const STATUS_CLOSED = 0; + + + 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), + 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>20), + 'label' =>array('type'=>'varchar(128)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>22), + 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>25), + 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>30), + 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>35), + 'fk_state' =>array('type'=>'integer', 'label'=>'Fkstate', 'enabled'=>1, 'visible'=>-1, 'position'=>40), + 'fk_country' =>array('type'=>'integer', 'label'=>'Fkcountry', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + 'profid1' =>array('type'=>'varchar(20)', 'label'=>'Profid1', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'profid2' =>array('type'=>'varchar(20)', 'label'=>'Profid2', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'profid3' =>array('type'=>'varchar(20)', 'label'=>'Profid3', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fkuserauthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70), + 'fk_user_mod' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fkusermod', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85), + 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500), + ); /** @@ -112,9 +132,6 @@ class Establishment extends CommonObject public function __construct($db) { $this->db = $db; - - $this->statuts_short = array(0 => 'Closed', 1 => 'Open'); - $this->statuts = array(0 => 'Closed', 1 => 'Open'); } /** @@ -128,20 +145,20 @@ class Establishment extends CommonObject global $conf, $langs; $error = 0; - $ret = 0; $now = dol_now(); - // Clean parameters - $this->address = ($this->address > 0 ? $this->address : $this->address); - $this->zip = ($this->zip > 0 ? $this->zip : $this->zip); - $this->town = ($this->town > 0 ? $this->town : $this->town); - $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); + // Clean parameters + $this->address = trim($this->address); + $this->zip = trim($this->zip); + $this->town = trim($this->town); + + if (empty($this->ref)) $this->ref = '(PROV)'; $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."establishment ("; $sql .= "ref"; - $sql .= ", name"; + $sql .= ", label"; $sql .= ", address"; $sql .= ", zip"; $sql .= ", town"; @@ -152,10 +169,11 @@ class Establishment extends CommonObject $sql .= ", fk_user_author"; $sql .= ", fk_user_mod"; $sql .= ") VALUES ("; - $sql .= " '".$this->db->escape($this->name)."'"; + $sql .= "'".$this->db->escape($this->ref)."'"; + $sql .= ", '".$this->db->escape($this->label)."'"; $sql .= ", '".$this->db->escape($this->address)."'"; - $sql .= ", '".$this->db->escape($this->zip)."'"; - $sql .= ", '".$this->db->escape($this->town)."'"; + $sql .= ", '".$this->db->escape($this->zip)."'"; + $sql .= ", '".$this->db->escape($this->town)."'"; $sql .= ", ".$this->country_id; $sql .= ", ".$this->status; $sql .= ", ".$conf->entity; @@ -184,6 +202,12 @@ class Establishment extends CommonObject $this->db->rollback(); return -1 * $error; } else { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'establishment'); + + $sql = 'UPDATE '.MAIN_DB_PREFIX."establishment SET ref = '".$this->db->escape($this->id)."'"; + $sql .= " WHERE rowid = ".$this->id; + $this->db->query($sql); + $this->db->commit(); return $this->id; } @@ -199,17 +223,18 @@ class Establishment extends CommonObject { global $langs; - // Check parameters - if (empty($this->name)) - { - $this->error = 'ErrorBadParameter'; - return -1; - } + // Check parameters + if (empty($this->label)) + { + $this->error = 'ErrorBadParameter'; + return -1; + } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."establishment"; - $sql .= " SET ref = '".$this->db->escape($this->ref)."', name = '".$this->db->escape($this->name)."'"; + $sql .= " SET ref = '".$this->db->escape($this->ref)."'"; + $sql .= ", label = '".$this->db->escape($this->label)."'"; $sql .= ", address = '".$this->db->escape($this->address)."'"; $sql .= ", zip = '".$this->db->escape($this->zip)."'"; $sql .= ", town = '".$this->db->escape($this->town)."'"; @@ -232,17 +257,17 @@ class Establishment extends CommonObject } /** - * Load an object from database - * - * @param int $id Id of record to load - * @return int <0 if KO, >0 if OK - */ + * Load an object from database + * + * @param int $id Id of record to load + * @return int <0 if KO, >0 if OK + */ public function fetch($id) { - $sql = "SELECT e.rowid, e.ref, e.name, e.address, e.zip, e.town, e.status, e.fk_country as country_id, e.entity,"; + $sql = "SELECT e.rowid, e.ref, e.label, e.address, e.zip, e.town, e.status, e.fk_country as country_id, e.entity,"; $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 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON e.fk_country = c.rowid'; $sql .= " WHERE e.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -253,16 +278,16 @@ class Establishment extends CommonObject $this->id = $obj->rowid; $this->ref = $obj->ref; - $this->name = $obj->name; + $this->label = $obj->label; $this->address = $obj->address; $this->zip = $obj->zip; $this->town = $obj->town; $this->status = $obj->status; $this->entity = $obj->entity; - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; - $this->country = $obj->country; + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_code; + $this->country = $obj->country; return 1; } else { @@ -271,7 +296,7 @@ class Establishment extends CommonObject } } - /** + /** * Delete record * * @param int $id Id of record to delete @@ -329,7 +354,7 @@ class Establishment extends CommonObject } $statusType = 'status'.$status; - //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_OPEN) $statusType = 'status4'; if ($status == self::STATUS_CLOSED) $statusType = 'status6'; return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); @@ -380,58 +405,60 @@ class Establishment extends CommonObject } } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @return string String with URL - */ - public function getNomUrl($withpicto = 0) - { - global $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @return string String with URL + */ + public function getNomUrl($withpicto = 0) + { + global $langs; - $result = ''; + $result = ''; - $link = ''; - $linkend = ''; + $link = ''; + $linkend = ''; - $picto = 'building'; + $picto = 'building'; - $label = $langs->trans("Show").': '.$this->name; + $label = ''.$langs->trans("Establishment").''; + $label .= '
    '.$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->name.$linkend; - return $result; - } + if ($withpicto) $result .= ($link.img_object($label, $picto).$linkend); + if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto != 2) $result .= $link.$this->label.$linkend; + return $result; + } /** - * Return account country code - * - * @return string country code - */ - public function getCountryCode() - { - global $mysoc; + * Return account country code + * + * @return string country code + */ + public function getCountryCode() + { + global $mysoc; - // We return country code of bank account - if (!empty($this->country_code)) return $this->country_code; + // We return country code of bank account + 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; + // We return country code of managed company + if (!empty($mysoc->country_code)) return $mysoc->country_code; - return ''; - } + return ''; + } - /** - * Initialise object with example values - * Id must be 0 if object instance is a specimen - * - * @return void - */ - public function initAsSpecimen() - { - $this->id = 0; - $this->ref = 'DEP-AAA'; - } + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + $this->ref = '0'; + $this->label = 'Department AAA'; + } } diff --git a/htdocs/hrm/establishment/card.php b/htdocs/hrm/establishment/card.php index c7784d42fb2..1f43878babf 100644 --- a/htdocs/hrm/establishment/card.php +++ b/htdocs/hrm/establishment/card.php @@ -33,7 +33,7 @@ if (!$user->admin) accessforbidden(); $error = 0; -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $id = GETPOST('id', 'int'); @@ -41,7 +41,7 @@ $id = GETPOST('id', 'int'); // List of status static $tmpstatus2label = array( '0'=>'CloseEtablishment', - '1'=>'OpenEtablishment' + '1'=>'OpenEtablishment' ); $status2label = array(''); foreach ($tmpstatus2label as $key => $val) $status2label[$key] = $langs->trans($val); @@ -58,29 +58,29 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ if ($action == 'confirm_delete' && $confirm == "yes") { - $result = $object->delete($id); - if ($result >= 0) - { - header("Location: ../admin/admin_establishment.php"); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->delete($id); + if ($result >= 0) + { + header("Location: ../admin/admin_establishment.php"); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'add') { - if (!$cancel) - { - $error = 0; + if (!$cancel) + { + $error = 0; - $object->name = GETPOST('name', 'alpha'); - if (empty($object->name)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Name")), null, 'errors'); - $error++; - } + $object->label = GETPOST('label', 'alpha'); + 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,20 +92,20 @@ if ($action == 'confirm_delete' && $confirm == "yes") $id = $object->create($user); - if ($id > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; + if ($id > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } else { - $action = 'create'; - } - } else { - header("Location: ../admin/admin_establishment.php"); - exit; - } + } else { + $action = 'create'; + } + } else { + header("Location: ../admin/admin_establishment.php"); + exit; + } } // Update record @@ -114,15 +114,15 @@ elseif ($action == 'update') $error = 0; if (!$cancel) { - $name = GETPOST('name', 'alpha'); + $name = GETPOST('label', 'alpha'); if (empty($name)) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Name')), null, 'errors'); + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')), null, 'errors'); $error++; } if (empty($error)) { - $object->name = GETPOST('name', 'alpha'); + $object->label = GETPOST('label', 'alphanohtml'); $object->address = GETPOST('address', 'alpha'); $object->zip = GETPOST('zipcode', 'alpha'); $object->town = GETPOST('town', 'alpha'); @@ -133,17 +133,17 @@ elseif ($action == 'update') $result = $object->update($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); - exit; - } else { + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); + exit; + } else { setEventMessages($object->error, $object->errors, 'errors'); } } } else { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); - exit; + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']); + exit; } } @@ -161,20 +161,20 @@ $formcompany = new FormCompany($db); */ if ($action == 'create') { - print load_fiche_titre($langs->trans("NewEstablishment")); + print load_fiche_titre($langs->trans("NewEstablishment")); - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; dol_fiche_head(); - print '
    '.$langs->trans('Journaux').''.$langs->trans('Parameters').'
    '; + print '
    '; // Name print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Entity @@ -192,7 +192,7 @@ if ($action == 'create') print ''; print ''; print ''; print ''; @@ -233,54 +233,54 @@ if ($action == 'create') print ''; // Status - print ''; - print ''; + print ''; + print ''; print ''; + print ''; - print '
    '.$form->editfieldkey('Name', 'name', '', $object, 0, 'string', '', 1).''.$form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).'
    '.$form->editfieldkey('Address', 'address', '', $object, 0).''; - print ''; + print ''; print '
    '.$form->editfieldkey('Status', 'status', '', $object, 0, 'string', '', 1).'
    '.$form->editfieldkey('Status', 'status', '', $object, 0, 'string', '', 1).''; print $form->selectarray('status', $status2label, GETPOSTISSET('status') ? GETPOST('status', 'alpha') : 1); - print '
    '; + print '
    '; dol_fiche_end(); - print '
    '; + print '
    '; print ''; print '     '; - print ''; + print ''; print '
    '; - print ''; + print ''; } // Part to edit record if (($id || $ref) && $action == 'edit') { - $result = $object->fetch($id); - if ($result > 0) - { - $head = establishment_prepare_head($object); + $result = $object->fetch($id); + if ($result > 0) + { + $head = establishment_prepare_head($object); - if ($action == 'edit') - { - dol_fiche_head($head, 'card', $langs->trans("Establishment"), 0, 'building'); + if ($action == 'edit') + { + dol_fiche_head($head, 'card', $langs->trans("Establishment"), 0, 'building'); - print '
    '."\n"; - print ''; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; + print ''; - print ''; + print '
    '; - // Ref - print ""; - print ''; + // Ref + print ""; + print ''; - // Name - print ''; + // Name + print ''; // Entity /* @@ -294,7 +294,7 @@ if (($id || $ref) && $action == 'edit') // Address print ''; print ''; // Zipcode / Town @@ -322,33 +322,33 @@ if (($id || $ref) && $action == 'edit') print $form->selectarray('status', $status2label, $object->status); print ''; - print '
    '.$langs->trans("Ref").''; - print $object->id; - print '
    '.$langs->trans("Ref").''; + print $object->id; + print '
    '.$form->editfieldkey('Name', 'name', '', $object, 0, 'string', '', 1).''; - print ''; - print '
    '.$form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).''; + print ''; + print '
    '.$form->editfieldkey('Address', 'address', '', $object, 0).''; - print ''; + print ''; print '
    '; + print ''; dol_fiche_end(); - print '
    '; + print '
    '; print ''; print '     '; - print ''; - print '
    '; + print ''; + print '
    '; - print '
    '; - } - } else dol_print_error($db); + print ''; + } + } else dol_print_error($db); } if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - $res = $object->fetch_optionals(); + $res = $object->fetch_optionals(); - $head = establishment_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("Establishment"), -1, 'building'); + $head = establishment_prepare_head($object); + dol_fiche_head($head, 'card', $langs->trans("Establishment"), -1, 'building'); - // Confirmation to delete - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteEstablishment"), $langs->trans("ConfirmDeleteEstablishment"), "confirm_delete"); - } + // Confirmation to delete + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteEstablishment"), $langs->trans("ConfirmDeleteEstablishment"), "confirm_delete"); + } // Object card @@ -357,20 +357,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
    '; - $morehtmlref .= '
    '; + $morehtmlref .= '
    '; - dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', $morehtmlref); + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', $morehtmlref); - print '
    '; - //print '
    '; - print '
    '; - print ''."\n"; + print '
    '; + //print '
    '; + print '
    '; + print '
    '."\n"; // Name print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Entity @@ -390,7 +390,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Zipcode print ''; - print ''; + print ''; print ''; print ''; @@ -413,21 +413,21 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; - print '
    '.$langs->trans("Name").''.$object->name.''.$langs->trans("Label").''.$object->label.'
    '.$langs->trans("Zipcode").''.$langs->trans("Zip").''.$object->zip.'
    '; - print '
    '; + print ''; + print '
    '; - print '

    '; + print '

    '; - dol_fiche_end(); + dol_fiche_end(); - /* + /* * Barre d'actions */ - print '
    '; - print ''.$langs->trans('Modify').''; - print ''.$langs->trans('Delete').''; - print '
    '; + print '
    '; + print ''.$langs->trans('Modify').''; + print ''.$langs->trans('Delete').''; + print '
    '; } // End of page diff --git a/htdocs/hrm/establishment/info.php b/htdocs/hrm/establishment/info.php index c26f7db4fc1..7bd6c5727b7 100644 --- a/htdocs/hrm/establishment/info.php +++ b/htdocs/hrm/establishment/info.php @@ -31,7 +31,7 @@ $langs->loadLangs(array('admin', 'hrm')); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); diff --git a/htdocs/hrm/index.php b/htdocs/hrm/index.php index 0cdc539bf0c..3955e3f849a 100644 --- a/htdocs/hrm/index.php +++ b/htdocs/hrm/index.php @@ -3,7 +3,7 @@ * Copyright (C) 2013-2015 Laurent Destailleur * Copyright (C) 2012-2014 Regis Houssin * Copyright (C) 2015-2016 Alexandre Spangaro - * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2019 Nicolas ZABOURI * * 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,6 +35,7 @@ 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'; +require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $hookmanager = new HookManager($db); @@ -52,9 +53,9 @@ if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INF $holiday = new Holiday($db); $holidaystatic = new Holiday($db); +$staticrecruitmentcandidature = new RecruitmentCandidature($db); -$max = 3; - +$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; /* @@ -95,42 +96,42 @@ print '
    '; 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) - { - $langs->load("trips"); - $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); - } - if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) - { - $langs->load("trips"); - $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); - } - if (count($listofsearchfields)) - { - print '
    '; - print ''; - print '
    '; - print ''; - $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print ''; - print ''; - print ''; - if ($i == 0) print ''; - print ''; - $i++; - } - print '
    '.$langs->trans("Search").'
    '; - print '
    '; - print '
    '; - print '
    '; - } + 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) + { + $langs->load("trips"); + $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); + } + if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) + { + $langs->load("trips"); + $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); + } + if (count($listofsearchfields)) + { + print '
    '; + print ''; + print '
    '; + print ''; + $i = 0; + foreach ($listofsearchfields as $key => $value) + { + if ($i == 0) print ''; + print ''; + print ''; + if ($i == 0) print ''; + print ''; + $i++; + } + print '
    '.$langs->trans("Search").'
    '; + print '
    '; + print '
    '; + print '
    '; + } } @@ -140,26 +141,26 @@ if (!empty($conf->holiday->enabled)) { $user_id = $user->id; - print '
    '; - print ''; - print ''; - print ''; - print ''; + print ''; + print '
    '.$langs->trans("Holidays").'
    '; + print '
    '; + print ''; + print ''; + print ''; + print ''; - print ''; - print '
    '.$langs->trans("Holidays").'
    '; - $out = ''; - $typeleaves = $holiday->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { - $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); - $nb_holiday += $nb_type; - $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
    '; - } - print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; - print $out; + $out = ''; + $typeleaves = $holiday->getTypes(1, 1); + foreach ($typeleaves as $key => $val) + { + $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); + $nb_holiday += $nb_type; + $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
    '; + } + print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; + print $out; - print '

    '; + print '

    '; } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) { print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'
    '; @@ -174,86 +175,88 @@ print '
    '; // Latest leave requests 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, 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->read_all)) $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); + $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->read_all)) $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) - { - $var = false; - $num = $db->num_rows($result); + $result = $db->query($sql); + if ($result) + { + $var = false; + $num = $db->num_rows($result); - $holidaystatic = new Holiday($db); - $userstatic = new User($db); + $holidaystatic = new Holiday($db); + $userstatic = new User($db); - $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); - $typeleaves = $holidaystatic->getTypes(1, -1); + $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); + $typeleaves = $holidaystatic->getTypes(1, -1); - $i = 0; + $i = 0; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if ($num) - { - while ($i < $num && $i < $max) - { - $obj = $db->fetch_object($result); + print '
    '; + print '
    '.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("DateModificationShort").' 
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($num) + { + while ($i < $num && $i < $max) + { + $obj = $db->fetch_object($result); - $holidaystatic->id = $obj->rowid; - $holidaystatic->ref = $obj->ref; + $holidaystatic->id = $obj->rowid; + $holidaystatic->ref = $obj->ref; + $holidaystatic->statut = $obj->status; - $userstatic->id = $obj->uid; - $userstatic->lastname = $obj->lastname; - $userstatic->firstname = $obj->firstname; - $userstatic->login = $obj->login; - $userstatic->photo = $obj->photo; - $userstatic->email = $obj->email; - $userstatic->statut = $obj->statut; + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->login = $obj->login; + $userstatic->photo = $obj->photo; + $userstatic->email = $obj->email; + $userstatic->statut = $obj->user_status; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; - $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; + $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; + $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - $i++; - } - } else { - print ''; - } - print '
    '.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("FullList").'
    '.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].'
    '.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].''.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]); - print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]); - print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
    '.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]).''; + print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]).''; + print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
    '.$langs->trans("None").'
    '; - print '
    '; - print '
    '; - } else dol_print_error($db); + $i++; + } + } else { + print ''.$langs->trans("None").''; + } + print ''; + print '
    '; + print '
    '; + } else dol_print_error($db); } // Latest expense report 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, u.photo, x.rowid, x.ref, x.date_debut as date, x.tms as dm, x.total_ttc, x.fk_statut as status"; + $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"; @@ -276,8 +279,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) print ''; print ''.$langs->trans("BoxTitleLastModifiedExpenses", min($max, $num)).''; print ''.$langs->trans("TotalTTC").''; - print ''.$langs->trans("DateModificationShort").''; - print ' '; + print ''.$langs->trans("FullList").''; print ''; if ($num) { @@ -291,13 +293,14 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) $expensereportstatic->id = $obj->rowid; $expensereportstatic->ref = $obj->ref; + $expensereportstatic->statut = $obj->status; $userstatic->id = $obj->uid; $userstatic->lastname = $obj->lastname; $userstatic->firstname = $obj->firstname; - $userstatic->email = $obj->email; + $userstatic->email = $obj->email; $userstatic->login = $obj->login; - $userstatic->statut = $obj->statut; + $userstatic->statut = $obj->user_status; $userstatic->photo = $obj->photo; print ''; @@ -305,7 +308,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) print ''.$userstatic->getNomUrl(-1).''; print ''.price($obj->total_ttc).''; print ''.dol_print_date($db->jdate($obj->dm), 'day').''; - print ''.$expensereportstatic->LibStatut($obj->status, 3).''; + print ''.$expensereportstatic->LibStatut($obj->status, 3).''; print ''; $i++; @@ -315,10 +318,75 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) } print ''; print '
    '; + print '
    '; } else dol_print_error($db); } +// Last modified job position +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"; + $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"; + $sql .= " ORDER BY rc.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 ''; + print ''; + if ($num) + { + while ($i < $num) + { + $objp = $db->fetch_object($resql); + $staticrecruitmentcandidature->id = $objp->rowid; + $staticrecruitmentcandidature->ref = $objp->ref; + $staticrecruitmentcandidature->email = $objp->email; + $staticrecruitmentcandidature->status = $objp->status; + $staticrecruitmentcandidature->date_creation = $objp->date_creation; + $staticrecruitmentcandidature->firstname = $objp->firstname; + $staticrecruitmentcandidature->lastname = $objp->lastname; + + print ''; + print ''; + print '"; + print '"; + print '"; + print ''; + $i++; + } + + $db->free($resql); + } else { + print ''; + } + print "
    '; + print $langs->trans("BoxTitleLatestModifiedCandidatures", $max); + print ''.$langs->trans("FullList").'
    '.$staticrecruitmentcandidature->getNomUrl(1, '').''; + print "'.dol_print_date($db->jdate($objp->tms), 'day')."'; + print $staticrecruitmentcandidature->getLibStatut(3); + print "
    '.$langs->trans("None").'
    "; + print "
    "; + print "
    "; + } else { + dol_print_error($db); + } +} + print '
    '; // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array diff --git a/htdocs/imports/class/import.class.php b/htdocs/imports/class/import.class.php index 12dfc5d19e9..3684d4d2d7e 100644 --- a/htdocs/imports/class/import.class.php +++ b/htdocs/imports/class/import.class.php @@ -1,6 +1,7 @@ * Copyright (C) 2016 Raphaël Doursenaud + * Copyright (C) 2020 Ahmad Jamaly Rabib * * 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 @@ -101,6 +102,8 @@ class Import // Defined if module is enabled $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 (empty($enabled)) continue; @@ -171,7 +174,7 @@ class Import // Sql request to run after import $this->array_import_run_sql_after[$i] = (isset($module->import_run_sql_after_array[$r]) ? $module->import_run_sql_after_array[$r] : ''); // Module - $this->array_import_module[$i] = $module; + $this->array_import_module[$i] = array('position_of_profile'=>($module->module_position.'-'.$module->import_code[$r]), 'module'=>$module); dol_syslog("Import loaded for module ".$modulename." with index ".$i.", dataset=".$module->import_code[$r].", nb of fields=".count($module->import_fields_array[$r])); $i++; @@ -278,7 +281,7 @@ class Import { $sql = 'SELECT em.rowid, em.field, em.label, em.type'; $sql .= ' FROM '.MAIN_DB_PREFIX.'import_model as em'; - $sql .= ' WHERE em.rowid = '.$id; + $sql .= ' WHERE em.rowid = '.((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 1ca191f5124..6c93d96619f 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -77,8 +77,8 @@ $importmodelid = GETPOST('importmodelid'); $excludefirstline = (GETPOST('excludefirstline') ? GETPOST('excludefirstline') : 1); $endatlinenb = (GETPOST('endatlinenb') ? GETPOST('endatlinenb') : ''); $updatekeys = (GETPOST('updatekeys', 'array') ? GETPOST('updatekeys', 'array') : array()); -$separator = (GETPOST('separator') ? GETPOST('separator') : (!empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE) ? $conf->global->IMPORT_CSV_SEPARATOR_TO_USE : ',')); -$enclosure = (GETPOST('enclosure') ? GETPOST('enclosure') : '"'); +$separator = (GETPOST('separator', 'nohtml') ? GETPOST('separator', 'nohtml') : (!empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE) ? $conf->global->IMPORT_CSV_SEPARATOR_TO_USE : ',')); +$enclosure = (GETPOST('enclosure', 'nohtml') ? GETPOST('enclosure', 'nohtml') : '"'); $objimport = new Import($db); $objimport->load_arrays($user, ($step == 1 ? '' : $datatoimport)); @@ -148,9 +148,9 @@ if ($action == 'builddoc') if ($action == 'deleteprof') { - if ($_GET["id"]) + if (GETPOST("id", 'int')) { - $objimport->fetch($_GET["id"]); + $objimport->fetch(GETPOST("id", 'int')); $result = $objimport->delete($user); } } @@ -212,9 +212,9 @@ if ($step == 3 && $datatoimport) { $langs->load("other"); - $param = '&datatoimport='.$datatoimport.'&format='.$format; - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format); + 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); @@ -321,8 +321,8 @@ if ($step == 1 || !$datatoimport) $_SESSION["dol_array_match_file_to_database"] = ''; $param = ''; - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + if ($excludefirstline) $param .= '&excludefirstline='.urlencode($excludefirstline); + if ($endatlinenb) $param .= '&endatlinenb='.urlencode($endatlinenb); if ($separator) $param .= '&separator='.urlencode($separator); if ($enclosure) $param .= '&enclosure='.urlencode($enclosure); @@ -346,22 +346,22 @@ if ($step == 1 || !$datatoimport) if (count($objimport->array_import_module)) { - $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'module_position', 'asc', 0, 0, 1); + $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1); foreach ($sortedarrayofmodules as $key => $value) { - //var_dump($objimport->array_import_code[$key]); + //var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]); print ''; - $titleofmodule = $objimport->array_import_module[$key]->getName(); + $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"); print $titleofmodule; print ''; - print img_object($objimport->array_import_module[$key]->getName(), $objimport->array_import_icon[$key]).' '; + print img_object($objimport->array_import_module[$key]['module']->getName(), $objimport->array_import_icon[$key]).' '; print $objimport->array_import_label[$key]; print ''; if ($objimport->array_import_perms[$key]) { - print ''.img_picto($langs->trans("NewImport"), 'filenew').''; + print ''.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').''; } else { print $langs->trans("NotEnoughPermissions"); } @@ -380,9 +380,9 @@ if ($step == 1 || !$datatoimport) // STEP 2: Page to select input format file if ($step == 2 && $datatoimport) { - $param = '&datatoimport='.$datatoimport; - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + $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); @@ -400,7 +400,7 @@ if ($step == 2 && $datatoimport) // Module print ''.$langs->trans("Module").''; print ''; - $titleofmodule = $objimport->array_import_module[0]->getName(); + $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"); print $titleofmodule; @@ -409,7 +409,7 @@ if ($step == 2 && $datatoimport) // Lot de donnees a importer print ''.$langs->trans("DatasetToImport").''; print ''; - print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' '; + print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print ''; @@ -424,7 +424,7 @@ if ($step == 2 && $datatoimport) print ''; print ''; - print ''.$langs->trans("ChooseFormatOfFileToImport", img_picto('', 'filenew')).'

    '; + print ''.$langs->trans("ChooseFormatOfFileToImport", img_picto('', 'next', '')).'

    '; print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; @@ -445,7 +445,7 @@ if ($step == 2 && $datatoimport) print ''; // Action button print ''; print ''; } @@ -460,9 +460,9 @@ if ($step == 2 && $datatoimport) // STEP 3: Page to select file if ($step == 3 && $datatoimport) { - $param = '&datatoimport='.$datatoimport.'&format='.$format; - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + $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); @@ -490,7 +490,7 @@ if ($step == 3 && $datatoimport) // Module print ''; print ''; print ''; @@ -549,7 +549,7 @@ if ($step == 3 && $datatoimport) print ''; print ''; - print ''.$langs->trans("ChooseFileToImport", img_picto('', 'filenew')).'

    '; + print ''.$langs->trans("ChooseFileToImport", img_picto('', 'next')).'

    '; print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
    '.$langs->trans("DownloadEmptyExample").''; - print ''.img_picto($langs->trans("SelectFormat"), 'filenew').''; + print ''.img_picto($langs->trans("SelectFormat"), 'next', 'class="fa-15x"').''; print '
    '.$langs->trans("Module").''; - $titleofmodule = $objimport->array_import_module[0]->getName(); + $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"); print $titleofmodule; @@ -499,7 +499,7 @@ if ($step == 3 && $datatoimport) // Lot de donnees a importer print '
    '.$langs->trans("DatasetToImport").''; - print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' '; + print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '
    '; @@ -639,11 +639,11 @@ if ($step == 3 && $datatoimport) // Affiche date fichier print ''; // Del button - print ''; // Action button print ''; print ''; } @@ -753,9 +753,9 @@ 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='.$datatoimport.'&filetoimport='.urlencode($filetoimport); - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + $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); @@ -773,7 +773,7 @@ if ($step == 4 && $datatoimport) // Module print ''; print ''; print ''; @@ -1147,7 +1147,7 @@ if ($step == 4 && $datatoimport) // List of existing import profils $sql = "SELECT rowid, label"; $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; - $sql .= " WHERE type = '".$datatoimport."'"; + $sql .= " WHERE type = '".$db->escape($datatoimport)."'"; $sql .= " ORDER BY rowid"; $resql = $db->query($sql); if ($resql) @@ -1160,7 +1160,7 @@ if ($step == 4 && $datatoimport) print ''; @@ -1213,10 +1213,10 @@ if ($step == 5 && $datatoimport) $nboflines = $obj->import_get_nb_of_lines($conf->import->dir_temp.'/'.$filetoimport); - $param = '&leftmenu=import&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines.'&separator='.urlencode($separator).'&enclosure='.urlencode($enclosure); + $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='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + 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ódulo_Importaciones'); @@ -1239,7 +1239,7 @@ if ($step == 5 && $datatoimport) // Module print ''; print ''; print ''; @@ -1642,9 +1642,9 @@ if ($step == 6 && $datatoimport) $nboflines = (!empty($_GET["nboflines"]) ? $_GET["nboflines"] : dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport)); - $param = '&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines; - if ($excludefirstline) $param .= '&excludefirstline='.$excludefirstline; - if ($endatlinenb) $param .= '&endatlinenb='.$endatlinenb; + $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); @@ -1662,7 +1662,7 @@ if ($step == 6 && $datatoimport) // Module print ''; print ''; print ''; diff --git a/htdocs/imports/index.php b/htdocs/imports/index.php index 365df6086f4..bc68b53cfd0 100644 --- a/htdocs/imports/index.php +++ b/htdocs/imports/index.php @@ -45,69 +45,18 @@ llxHeader('', $langs->trans("ImportArea"), 'EN:Module_Imports_En|FR:Module_Impor print load_fiche_titre($langs->trans("ImportArea")); print $langs->trans("FormatedImportDesc1").'
    '; -//print $langs->trans("FormatedImportDesc2").'
    '; print '
    '; -//print '
    '; - - -// List of import set -/* -print '
    '; -print '
    '.dol_print_date(dol_filemtime($dir.'/'.$file), 'dayhour').''.img_delete().''; - print ''.img_picto($langs->trans("NewImport"), 'filenew').''; + print ''.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').''; print '
    '.$langs->trans("Module").''; - $titleofmodule = $objimport->array_import_module[0]->getName(); + $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"); print $titleofmodule; @@ -782,7 +782,7 @@ if ($step == 4 && $datatoimport) // Lot de donnees a importer print '
    '.$langs->trans("DatasetToImport").''; - print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' '; + print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '
    '; print $obj->label; print ''; - print 'rowid.'&filetoimport='.urlencode($filetoimport).'">'; + print 'rowid.'&filetoimport='.urlencode($filetoimport).'">'; print img_delete(); print ''; print '
    '.$langs->trans("Module").''; - $titleofmodule = $objimport->array_import_module[0]->getName(); + $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"); print $titleofmodule; @@ -1248,7 +1248,7 @@ if ($step == 5 && $datatoimport) // Lot de donnees a importer print '
    '.$langs->trans("DatasetToImport").''; - print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' '; + print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '
    '.$langs->trans("Module").''; - $titleofmodule = $objimport->array_import_module[0]->getName(); + $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"); print $titleofmodule; @@ -1671,7 +1671,7 @@ if ($step == 6 && $datatoimport) // Lot de donnees a importer print '
    '.$langs->trans("DatasetToImport").''; - print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' '; + print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '
    '; -print ''; -print ''; -print ''; -//print ''; -print ''; - -if (count($import->array_import_code)) -{ - foreach ($import->array_import_code as $key => $value) - { - print ''; - // print ''; - print ''; - - } -} -else -{ - print ''; -} -print '
    '.$langs->trans("Module").''.$langs->trans("ImportableDatas").' 
    '; - print img_object($import->array_import_module[$key]->getName(),$import->array_import_module[$key]->picto).' '; - print $import->array_import_module[$key]->getName(); - print ''; - $string=$langs->trans($import->array_import_label[$key]); - print ($string!=$import->array_import_label[$key]?$string:$import->array_import_label[$key]); - print ''; - // print ''.img_picto($langs->trans("NewImport"),'filenew').''; - // print '
    '.$langs->trans("NoImportableData").'
    '; -print '
    '; -print '
    '; -*/ - print '
    '; if (count($import->array_import_code)) { - //if ($user->rights->import->run) - //{ print dolGetButtonTitle($langs->trans('NewImport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/imports/import.php?leftmenu=import'); - //} - //else - //{ - // print ''.$langs->trans("NewImport").''; - //} } print '
    '; print '
    '; -//print '
    '; - - // List of available import format print '
    '; print ''; @@ -136,8 +85,6 @@ print '
    '; print '
    '; -//print '
    '; - // End of page llxFooter(); $db->close(); diff --git a/htdocs/includes/DebugBar/DataCollector/AssetProvider.php b/htdocs/includes/DebugBar/DataCollector/AssetProvider.php deleted file mode 100644 index 6910f737e17..00000000000 --- a/htdocs/includes/DebugBar/DataCollector/AssetProvider.php +++ /dev/null @@ -1,28 +0,0 @@ -name = $name; - $this->data = $data; - } - - /** - * Sets the data - * - * @param array $data - */ - public function setData(array $data) - { - $this->data = $data; - } - - public function collect() - { - $data = array(); - foreach ($this->data as $k => $v) { - if (!is_string($v)) { - $v = $this->getDataFormatter()->formatVar($v); - } - $data[$k] = $v; - } - return $data; - } - - public function getName() - { - return $this->name; - } - - public function getWidgets() - { - $name = $this->getName(); - return array( - "$name" => array( - "icon" => "gear", - "widget" => "PhpDebugBar.Widgets.VariableListWidget", - "map" => "$name", - "default" => "{}" - ) - ); - } -} diff --git a/htdocs/includes/DebugBar/DataCollector/DataCollector.php b/htdocs/includes/DebugBar/DataCollector/DataCollector.php deleted file mode 100644 index 081f66e6872..00000000000 --- a/htdocs/includes/DebugBar/DataCollector/DataCollector.php +++ /dev/null @@ -1,90 +0,0 @@ -dataFormater = $formater; - return $this; - } - - public function getDataFormatter() - { - if ($this->dataFormater === null) { - $this->dataFormater = self::getDefaultDataFormatter(); - } - return $this->dataFormater; - } - - /** - * @deprecated - */ - public function formatVar($var) - { - return $this->getDataFormatter()->formatVar($var); - } - - /** - * @deprecated - */ - public function formatDuration($seconds) - { - return $this->getDataFormatter()->formatDuration($seconds); - } - - /** - * @deprecated - */ - public function formatBytes($size, $precision = 2) - { - return $this->getDataFormatter()->formatBytes($size, $precision); - } -} diff --git a/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDO.php b/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDO.php deleted file mode 100644 index 5f7688b978e..00000000000 --- a/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDO.php +++ /dev/null @@ -1,196 +0,0 @@ -pdo = $pdo; - $this->pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DebugBar\DataCollector\PDO\TraceablePDOStatement', array($this))); - } - - public function beginTransaction() - { - return $this->pdo->beginTransaction(); - } - - public function commit() - { - return $this->pdo->commit(); - } - - public function errorCode() - { - return $this->pdo->errorCode(); - } - - public function errorInfo() - { - return $this->pdo->errorInfo(); - } - - public function exec($sql) - { - return $this->profileCall('exec', $sql, func_get_args()); - } - - public function getAttribute($attr) - { - return $this->pdo->getAttribute($attr); - } - - public function inTransaction() - { - return $this->pdo->inTransaction(); - } - - public function lastInsertId($name = null) - { - return $this->pdo->lastInsertId($name); - } - - public function prepare($sql, $driver_options = array()) - { - return $this->pdo->prepare($sql, $driver_options); - } - - public function query($sql) - { - return $this->profileCall('query', $sql, func_get_args()); - } - - public function quote($expr, $parameter_type = PDO::PARAM_STR) - { - return $this->pdo->quote($expr, $parameter_type); - } - - public function rollBack() - { - return $this->pdo->rollBack(); - } - - public function setAttribute($attr, $value) - { - return $this->pdo->setAttribute($attr, $value); - } - - /** - * Profiles a call to a PDO method - * - * @param string $method - * @param string $sql - * @param array $args - * @return mixed The result of the call - */ - protected function profileCall($method, $sql, array $args) - { - $trace = new TracedStatement($sql); - $trace->start(); - - $ex = null; - try { - $result = call_user_func_array(array($this->pdo, $method), $args); - } catch (PDOException $e) { - $ex = $e; - } - - if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION && $result === false) { - $error = $this->pdo->errorInfo(); - $ex = new PDOException($error[2], $error[0]); - } - - $trace->end($ex); - $this->addExecutedStatement($trace); - - if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) === PDO::ERRMODE_EXCEPTION && $ex !== null) { - throw $ex; - } - return $result; - } - - /** - * Adds an executed TracedStatement - * - * @param TracedStatement $stmt - */ - public function addExecutedStatement(TracedStatement $stmt) - { - $this->executedStatements[] = $stmt; - } - - /** - * Returns the accumulated execution time of statements - * - * @return int - */ - public function getAccumulatedStatementsDuration() - { - return array_reduce($this->executedStatements, function ($v, $s) { return $v + $s->getDuration(); }); - } - - /** - * Returns the peak memory usage while performing statements - * - * @return int - */ - public function getMemoryUsage() - { - return array_reduce($this->executedStatements, function ($v, $s) { return $v + $s->getMemoryUsage(); }); - } - - /** - * Returns the peak memory usage while performing statements - * - * @return int - */ - public function getPeakMemoryUsage() - { - return array_reduce($this->executedStatements, function ($v, $s) { $m = $s->getEndMemory(); return $m > $v ? $m : $v; }); - } - - /** - * Returns the list of executed statements as TracedStatement objects - * - * @return array - */ - public function getExecutedStatements() - { - return $this->executedStatements; - } - - /** - * Returns the list of failed statements - * - * @return array - */ - public function getFailedExecutedStatements() - { - return array_filter($this->executedStatements, function ($s) { return !$s->isSuccess(); }); - } - - public function __get($name) - { - return $this->pdo->$name; - } - - public function __set($name, $value) - { - $this->pdo->$name = $value; - } - - public function __call($name, $args) - { - return call_user_func_array(array($this->pdo, $name), $args); - } -} diff --git a/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDOStatement.php b/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDOStatement.php deleted file mode 100644 index b903b10c361..00000000000 --- a/htdocs/includes/DebugBar/DataCollector/PDO/TraceablePDOStatement.php +++ /dev/null @@ -1,74 +0,0 @@ -pdo = $pdo; - } - - public function bindColumn($column, &$param, $type = null, $maxlen = null, $driverdata = null) - { - $this->boundParameters[$column] = $param; - $args = array_merge(array($column, &$param), array_slice(func_get_args(), 2)); - return call_user_func_array(array("parent", 'bindColumn'), $args); - } - - public function bindParam($param, &$var, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) - { - $this->boundParameters[$param] = $var; - $args = array_merge(array($param, &$var), array_slice(func_get_args(), 2)); - return call_user_func_array(array("parent", 'bindParam'), $args); - } - - public function bindValue($param, $value, $data_type = PDO::PARAM_STR) - { - $this->boundParameters[$param] = $value; - return call_user_func_array(array("parent", 'bindValue'), func_get_args()); - } - - public function execute($params = null) - { - $preparedId = spl_object_hash($this); - $boundParameters = $this->boundParameters; - if (is_array($params)) { - $boundParameters = array_merge($boundParameters, $params); - } - - $trace = new TracedStatement($this->queryString, $boundParameters, $preparedId); - $trace->start(); - - $ex = null; - try { - $result = parent::execute($params); - } catch (PDOException $e) { - $ex = $e; - } - - if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION && $result === false) { - $error = $this->errorInfo(); - $ex = new PDOException($error[2], $error[0]); - } - - $trace->end($ex, $this->rowCount()); - $this->pdo->addExecutedStatement($trace); - - if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) === PDO::ERRMODE_EXCEPTION && $ex !== null) { - throw $ex; - } - return $result; - } -} diff --git a/htdocs/includes/DebugBar/DataCollector/RequestDataCollector.php b/htdocs/includes/DebugBar/DataCollector/RequestDataCollector.php deleted file mode 100644 index 1b8de32cb52..00000000000 --- a/htdocs/includes/DebugBar/DataCollector/RequestDataCollector.php +++ /dev/null @@ -1,48 +0,0 @@ -getDataFormatter()->formatVar($GLOBALS[$var]); - } - } - - return $data; - } - - public function getName() - { - return 'request'; - } - - public function getWidgets() - { - return array( - "request" => array( - "icon" => "tags", - "widget" => "PhpDebugBar.Widgets.VariableListWidget", - "map" => "request", - "default" => "{}" - ) - ); - } -} diff --git a/htdocs/includes/DebugBar/DataFormatter/DataFormatter.php b/htdocs/includes/DebugBar/DataFormatter/DataFormatter.php deleted file mode 100644 index 73269459838..00000000000 --- a/htdocs/includes/DebugBar/DataFormatter/DataFormatter.php +++ /dev/null @@ -1,169 +0,0 @@ -kintLite($data); - } - - public function formatDuration($seconds) - { - if ($seconds < 0.001) { - return round($seconds * 1000000) . 'μs'; - } elseif ($seconds < 1) { - return round($seconds * 1000, 2) . 'ms'; - } - return round($seconds, 2) . 's'; - } - - public function formatBytes($size, $precision = 2) - { - if ($size === 0 || $size === null) { - return "0B"; - } - $base = log($size) / log(1024); - $suffixes = array('B', 'KB', 'MB', 'GB', 'TB'); - return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)]; - } - - /** - * lightweight version of Kint::dump(). Uses whitespace for formatting instead of html - * sadly not DRY yet - * - * Extracted from Kint.class.php in raveren/kint, https://github.com/raveren/kint - * Copyright (c) 2013 Rokas Šleinius (raveren@gmail.com) - * - * @param mixed $var - * @param int $level - * - * @return string - */ - protected function kintLite(&$var, $level = 0) - { - // initialize function names into variables for prettier string output (html and implode are also DRY) - $html = "htmlspecialchars"; - $implode = "implode"; - $strlen = "strlen"; - $count = "count"; - $getClass = "get_class"; - - if ( $var === null ) { - return 'NULL'; - } elseif ( is_bool( $var ) ) { - return 'bool ' . ( $var ? 'TRUE' : 'FALSE' ); - } elseif ( is_float( $var ) ) { - return 'float ' . $var; - } elseif ( is_int( $var ) ) { - return 'integer ' . $var; - } elseif ( is_resource( $var ) ) { - if ( ( $type = get_resource_type( $var ) ) === 'stream' and $meta = stream_get_meta_data( $var ) ) { - if ( isset( $meta['uri'] ) ) { - $file = $meta['uri']; - - return "resource ({$type}) {$html( $file, 0 )}"; - } else { - return "resource ({$type})"; - } - } else { - return "resource ({$type})"; - } - } elseif ( is_string( $var ) ) { - return "string ({$strlen( $var )}) \"{$html( $var )}\""; - } elseif ( is_array( $var ) ) { - $output = array(); - $space = str_repeat( $s = ' ', $level ); - - static $marker; - - if ( $marker === null ) { - // Make a unique marker - $marker = uniqid( "\x00" ); - } - - if ( empty( $var ) ) { - return "array()"; - } elseif ( isset( $var[$marker] ) ) { - $output[] = "[\n$space$s*RECURSION*\n$space]"; - } elseif ( $level < 7 ) { - $isSeq = array_keys( $var ) === range( 0, count( $var ) - 1 ); - - $output[] = "["; - - $var[$marker] = true; - - foreach ( $var as $key => &$val ) { - if ( $key === $marker ) { - continue; - } - - $key = $space . $s . ( $isSeq ? "" : "'{$html( $key, 0 )}' => " ); - - $dump = $this->kintLite( $val, $level + 1 ); - $output[] = "{$key}{$dump}"; - } - - unset( $var[$marker] ); - $output[] = "$space]"; - } else { - $output[] = "[\n$space$s*depth too great*\n$space]"; - } - return "array({$count( $var )}) {$implode( "\n", $output )}"; - } elseif ( is_object( $var ) ) { - if ( $var instanceof SplFileInfo ) { - return "object SplFileInfo " . $var->getRealPath(); - } - - // Copy the object as an array - $array = (array) $var; - - $output = array(); - $space = str_repeat( $s = ' ', $level ); - - $hash = spl_object_hash( $var ); - - // Objects that are being dumped - static $objects = array(); - - if ( empty( $array ) ) { - return "object {$getClass( $var )} {}"; - } elseif ( isset( $objects[$hash] ) ) { - $output[] = "{\n$space$s*RECURSION*\n$space}"; - } elseif ( $level < 7 ) { - $output[] = "{"; - $objects[$hash] = true; - - foreach ( $array as $key => & $val ) { - if ( $key[0] === "\x00" ) { - $access = $key[1] === "*" ? "protected" : "private"; - - // Remove the access level from the variable name - $key = substr( $key, strrpos( $key, "\x00" ) + 1 ); - } else { - $access = "public"; - } - - $output[] = "$space$s$access $key -> " . $this->kintLite( $val, $level + 1 ); - } - unset( $objects[$hash] ); - $output[] = "$space}"; - } else { - $output[] = "{\n$space$s*depth too great*\n$space}"; - } - - return "object {$getClass( $var )} ({$count( $array )}) {$implode( "\n", $output )}"; - } else { - return gettype( $var ) . htmlspecialchars( var_export( $var, true ), ENT_NOQUOTES ); - } - } -} diff --git a/htdocs/includes/DebugBar/RequestIdGenerator.php b/htdocs/includes/DebugBar/RequestIdGenerator.php deleted file mode 100644 index 934f407ff8f..00000000000 --- a/htdocs/includes/DebugBar/RequestIdGenerator.php +++ /dev/null @@ -1,22 +0,0 @@ -li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"} \ No newline at end of file diff --git a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/FontAwesome.otf b/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/FontAwesome.otf deleted file mode 100644 index 81c9ad949b4..00000000000 Binary files a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/FontAwesome.otf and /dev/null differ diff --git a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.eot b/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.eot deleted file mode 100644 index 84677bc0c5f..00000000000 Binary files a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.eot and /dev/null differ diff --git a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.svg b/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.svg deleted file mode 100644 index d907b25ae60..00000000000 --- a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.svg +++ /dev/null @@ -1,520 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.ttf b/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.ttf deleted file mode 100644 index 96a3639cdde..00000000000 Binary files a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.ttf and /dev/null differ diff --git a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.woff b/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.woff deleted file mode 100644 index 628b6a52a87..00000000000 Binary files a/htdocs/includes/DebugBar/Resources/vendor/font-awesome/fonts/fontawesome-webfont.woff and /dev/null differ diff --git a/htdocs/includes/DebugBar/Resources/vendor/highlightjs/styles/github.css b/htdocs/includes/DebugBar/Resources/vendor/highlightjs/styles/github.css deleted file mode 100644 index 71967a3739c..00000000000 --- a/htdocs/includes/DebugBar/Resources/vendor/highlightjs/styles/github.css +++ /dev/null @@ -1,125 +0,0 @@ -/* - -github.com style (c) Vasily Polovnyov - -*/ - -.hljs { - display: block; padding: 0.5em; - color: #333; - background: #f8f8f8 -} - -.hljs-comment, -.hljs-template_comment, -.diff .hljs-header, -.hljs-javadoc { - color: #998; - font-style: italic -} - -.hljs-keyword, -.css .rule .hljs-keyword, -.hljs-winutils, -.javascript .hljs-title, -.nginx .hljs-title, -.hljs-subst, -.hljs-request, -.hljs-status { - color: #333; - font-weight: bold -} - -.hljs-number, -.hljs-hexcolor, -.ruby .hljs-constant { - color: #099; -} - -.hljs-string, -.hljs-tag .hljs-value, -.hljs-phpdoc, -.tex .hljs-formula { - color: #d14 -} - -.hljs-title, -.hljs-id, -.coffeescript .hljs-params, -.scss .hljs-preprocessor { - color: #900; - font-weight: bold -} - -.javascript .hljs-title, -.lisp .hljs-title, -.clojure .hljs-title, -.hljs-subst { - font-weight: normal -} - -.hljs-class .hljs-title, -.haskell .hljs-type, -.vhdl .hljs-literal, -.tex .hljs-command { - color: #458; - font-weight: bold -} - -.hljs-tag, -.hljs-tag .hljs-title, -.hljs-rules .hljs-property, -.django .hljs-tag .hljs-keyword { - color: #000080; - font-weight: normal -} - -.hljs-attribute, -.hljs-variable, -.lisp .hljs-body { - color: #008080 -} - -.hljs-regexp { - color: #009926 -} - -.hljs-symbol, -.ruby .hljs-symbol .hljs-string, -.lisp .hljs-keyword, -.tex .hljs-special, -.hljs-prompt { - color: #990073 -} - -.hljs-built_in, -.lisp .hljs-title, -.clojure .hljs-built_in { - color: #0086b3 -} - -.hljs-preprocessor, -.hljs-pragma, -.hljs-pi, -.hljs-doctype, -.hljs-shebang, -.hljs-cdata { - color: #999; - font-weight: bold -} - -.hljs-deletion { - background: #fdd -} - -.hljs-addition { - background: #dfd -} - -.diff .hljs-change { - background: #0086b3 -} - -.hljs-chunk { - color: #aaa -} diff --git a/htdocs/includes/DebugBar/Storage/MemcachedStorage.php b/htdocs/includes/DebugBar/Storage/MemcachedStorage.php deleted file mode 100644 index 9c2eef70019..00000000000 --- a/htdocs/includes/DebugBar/Storage/MemcachedStorage.php +++ /dev/null @@ -1,91 +0,0 @@ -memcached = $memcached; - $this->keyNamespace = $keyNamespace; - } - - public function save($id, $data) - { - $key = $this->createKey($id); - $this->memcached->set($key, $data); - if (!$this->memcached->append($this->keyNamespace, "|$key")) { - $this->memcached->set($this->keyNamespace, $key); - } - } - - public function get($id) - { - return $this->memcached->get($this->createKey($id)); - } - - public function find(array $filters = array(), $max = 20, $offset = 0) - { - if (!($keys = $this->memcached->get($this->keyNamespace))) { - return array(); - } - - $results = array(); - foreach (explode('|', $keys) as $key) { - if ($data = $this->memcached->get($key)) { - $meta = $data['__meta']; - if ($this->filter($meta, $filters)) { - $results[] = $meta; - } - } - } - return array_slice($results, $offset, $max); - } - - /** - * Filter the metadata for matches. - */ - protected function filter($meta, $filters) - { - foreach ($filters as $key => $value) { - if (!isset($meta[$key]) || fnmatch($value, $meta[$key]) === false) { - return false; - } - } - return true; - } - - public function clear() - { - if (!($keys = $this->memcached->get($this->keyNamespace))) { - return; - } - $this->memcached->delete($this->keyNamespace); - $this->memcached->deleteMulti(explode('|', $keys)); - } - - protected function createKey($id) - { - return md5("{$this->keyNamespace}.$id"); - } -} diff --git a/htdocs/includes/OAuth/Common/Storage/DoliStorage.php b/htdocs/includes/OAuth/Common/Storage/DoliStorage.php index 74d3356faeb..b2a79dc4751 100644 --- a/htdocs/includes/OAuth/Common/Storage/DoliStorage.php +++ b/htdocs/includes/OAuth/Common/Storage/DoliStorage.php @@ -242,7 +242,7 @@ class DoliStorage implements TokenStorageInterface $sql.= " WHERE service='".$this->db->escape($service)."'"; $resql = $this->db->query($sql); $result = $this->db->fetch_array($resql); - $states[$service] = $result[state]; + $states[$service] = $result['state']; $this->states[$service] = $states[$service]; return is_array($states) diff --git a/htdocs/includes/OAuth/OAuth2/Service/Google.php b/htdocs/includes/OAuth/OAuth2/Service/Google.php index 0d49609dccb..5ab0f8a474b 100644 --- a/htdocs/includes/OAuth/OAuth2/Service/Google.php +++ b/htdocs/includes/OAuth/OAuth2/Service/Google.php @@ -116,6 +116,11 @@ class Google extends AbstractService // Android Publisher const SCOPE_ANDROID_PUBLISHER = 'https://www.googleapis.com/auth/androidpublisher'; + + // Google Gsuite + const SCOPE_ADMIN_DIRECTORY_USER = "https://www.googleapis.com/auth/admin.directory.user"; + const SCOPE_ADMIN_DIRECTORY_CUSTOMER = "https://www.googleapis.com/auth/admin.directory.customer"; + protected $accessType = 'online'; public function __construct( @@ -150,7 +155,7 @@ class Google extends AbstractService } $this->approvalPrompt = $prompt; } - + /** * {@inheritdoc} */ diff --git a/htdocs/includes/jquery/plugins/multiselect/jquery.multi-select.js b/htdocs/includes/jquery/plugins/multiselect/jquery.multi-select.js new file mode 100644 index 00000000000..ee62d1f588d --- /dev/null +++ b/htdocs/includes/jquery/plugins/multiselect/jquery.multi-select.js @@ -0,0 +1,360 @@ +// jquery.multi-select.js +// by mySociety +// https://github.com/mysociety/jquery-multi-select + +;(function($) { + + "use strict"; + + var pluginName = "multiSelect", + defaults = { + 'containerHTML': '
    ', + 'menuHTML': '
    ', + 'buttonHTML': '', + 'menuItemsHTML': '
    ', + 'menuItemHTML': '