diff --git a/.github/ISSUE_TEMPLATE/custom.md b/.github/ISSUE_TEMPLATE/custom.md new file mode 100644 index 00000000000..48d5f81fa42 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/custom.md @@ -0,0 +1,10 @@ +--- +name: Custom issue template +about: Describe this issue template's purpose here. +title: '' +labels: '' +assignees: '' + +--- + + diff --git a/.travis.yml b/.travis.yml index 5193b7c2c77..dd3322e5cf7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,8 @@ # from Dolibarr GitHub repository. # For syntax, see http://about.travis-ci.org/docs/user/languages/php/ -# We use dist: trusty to have php 5.4+ available -dist: trusty +# We use dist: xenial to have php 5.6+ available +dist: xenial sudo: required language: php @@ -11,14 +11,16 @@ language: php # Start on every boot services: - memcached +- mysql +- postgresql addons: - mariadb: '10.0' - postgresql: '9.3' + # Force postgresql to 9.4 (the oldest availablable on xenial) + postgresql: '9.4' apt: sources: - # To use the last version of pgloader, we add repo of postgresql - - pgdg-trusty + # To use the last version of pgloader, we add repo of postgresql with a name available in http://apt.postgresql.org/pub/repos/apt/ + - pgdg-xenial packages: # We need a webserver to test the webservices # Let's install Apache with. @@ -29,7 +31,6 @@ addons: - pgloader php: -- '5.5' - '5.6' - '7.0' - '7.1' @@ -44,11 +45,9 @@ env: - DEBUG=false matrix: # MariaDB overrides MySQL installation so it's not possible to test both yet - #- DB=mysql - - DB=mariadb + #- DB=mariadb + - DB=mysql - DB=postgresql - # TODO - #- DB=sqlite # See https://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP #- WS=apache # See https://github.com/DracoBlue/travis-ci-nginx-php-fpm-test @@ -60,18 +59,14 @@ matrix: - php: nightly # We exclude some combinations not usefull to save Travis CPU exclude: - - php: '5.6' - env: DB=mariadb - php: '7.0' - env: DB=mariadb + env: DB=mysql - php: '7.1' - env: DB=mariadb + env: DB=mysql - php: '7.2' - env: DB=mariadb + env: DB=mysql - php: '7.3' - env: DB=mariadb - - php: '5.6' - env: DB=postgresql + env: DB=mysql - php: '7.0' env: DB=postgresql - php: '7.1' @@ -188,32 +183,31 @@ before_script: # Check Apache version echo "Apache version" apache2 -v | head - - # Check MariaDb - echo "MariaDb version" + # Check Database + echo "Database version" mysql --version | head - mysql -e "SELECT VERSION();" | head - + psql --version echo - | echo "Setting up database" if [ "$DB" = 'mysql' ] || [ "$DB" = 'mariadb' ] || [ "$DB" = 'postgresql' ]; then echo "MySQL" - mysql -e 'DROP DATABASE IF EXISTS travis;' - mysql -e 'CREATE DATABASE IF NOT EXISTS travis;' - mysql -e 'GRANT ALL PRIVILEGES ON travis.* TO travis@127.0.0.1;' - mysql -e 'FLUSH PRIVILEGES;' - mysql -D travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql + mysql -u root -e 'DROP DATABASE IF EXISTS travis;' + mysql -u root -e 'CREATE DATABASE IF NOT EXISTS travis;' + mysql -u root -e 'GRANT ALL PRIVILEGES ON travis.* TO travis@127.0.0.1;' + mysql -u root -e 'FLUSH PRIVILEGES;' + mysql -u root -D travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql fi if [ "$DB" = 'postgresql' ]; then - #pgsql travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql - #pgloader mysql://root:pass@127.0.0.1/dolibarr_9 postgresql://dolibarrowner:dolibarrownerpass@127.0.0.1/dolibarr_dev - echo pgloader mysql://root@127.0.0.1/travis postgresql:///travis - pgloader mysql://root@127.0.0.1/travis postgresql:///travis - echo 'ALTER SEQUENCE llx_accountingaccount_rowid_seq RENAME TO llx_accounting_account_rowid_seq' | psql travis - echo 'ALTER SEQUENCE llx_accounting_account_rowid_seq RESTART WITH 1000001;' | psql travis - #echo 'select * from INFORMATION_SCHEMA.COLUMNS where table_name = 'llx_accountingaccount' | psql travis - #echo 'select * from information_schema.table_constraints;' | psql travis - #echo 'ALTER TABLE "llx_accounting_account" DROP CONSTRAINT "idx_16390_primary"' | psql travis + #psql -c 'create database travis;' -U postgres + #psql travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql + #pgloader mysql://root:pass@127.0.0.1/dolibarr_src postgresql://dolibarrowner:dolibarrownerpass@127.0.0.1/dolibarr_dest + echo pgloader mysql://root@127.0.0.1/travis postgresql://postgres@/travis + pgloader mysql://root@127.0.0.1/travis postgresql://postgres@/travis + echo 'ALTER SEQUENCE llx_accountingaccount_rowid_seq RENAME TO llx_accounting_account_rowid_seq' | psql -U postgres travis + echo 'ALTER SEQUENCE llx_accounting_account_rowid_seq RESTART WITH 1000001;' | psql -U postgres travis fi echo @@ -262,10 +256,7 @@ before_script: - sudo sed -i -e "s,www-data,travis,g" /etc/apache2/envvars - sudo chown -R travis:travis /var/lib/apache2/fastcgi - ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm - # configure apache virtual hosts for precise - #- sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default - #- sudo cat /etc/apache2/sites-available/default - # configure apache virtual hosts for trusty + # configure apache virtual hosts - sudo cp -f build/travis-ci/apache.conf /etc/apache2/sites-available/000-default.conf - sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/000-default.conf - sudo cat /etc/apache2/sites-available/000-default.conf @@ -290,7 +281,7 @@ script: # Ensure we catch errors set -e #parallel-lint --exclude htdocs/includes --blame . - parallel-lint --exclude dev/namespacemig --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/tests --exclude htdocs/includes/jakub-onderka/php-parallel-lint/tests --exclude htdocs/includes/mike42/escpos-php/example --exclude htdocs/includes/phpunit/php-token-stream/tests --exclude htdocs/includes/composer/autoload_static.php --blame . + parallel-lint --exclude dev/namespacemig --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 . set +e echo @@ -406,9 +397,12 @@ script: php upgrade.php 9.0.0 10.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade9001000.log php upgrade2.php 9.0.0 10.0.0 > $TRAVIS_BUILD_DIR/upgrade9001000-2.log php step5.php 9.0.0 10.0.0 > $TRAVIS_BUILD_DIR/upgrade9001000-3.log - php upgrade.php 10.0.0 11.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade9001000.log - php upgrade2.php 10.0.0 11.0.0 > $TRAVIS_BUILD_DIR/upgrade9001000-2.log - php step5.php 10.0.0 11.0.0 > $TRAVIS_BUILD_DIR/upgrade9001000-3.log + php upgrade.php 10.0.0 11.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade10001100.log + php upgrade2.php 10.0.0 11.0.0 > $TRAVIS_BUILD_DIR/upgrade10001100-2.log + php step5.php 10.0.0 11.0.0 > $TRAVIS_BUILD_DIR/upgrade10001100-3.log + php upgrade.php 11.0.0 12.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade11001200.log + php upgrade2.php 11.0.0 12.0.0 > $TRAVIS_BUILD_DIR/upgrade11001200-2.log + php step5.php 11.0.0 12.0.0 > $TRAVIS_BUILD_DIR/upgrade11001200-3.log # Enable modules not enabled into original dump php upgrade2.php 0.0.0 0.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL,MAIN_MODULE_WEBSITE,MAIN_MODULE_TICKETSUP,MAIN_MODULE_ACCOUNTING > $TRAVIS_BUILD_DIR/enablemodule.log echo $? @@ -455,7 +449,7 @@ after_failure: # Dolibarr log file echo "Debugging informations for file dolibarr.log (latest 50 lines)" tail -n 50 $TRAVIS_BUILD_DIR/documents/dolibarr.log - # MariaDB log file + # Database log file echo "Debugging informations for file mysql error.log" sudo tail -n 50 /var/log/mysql/error.log # TODO: PostgreSQL log file diff --git a/ChangeLog b/ChangeLog index 6980edf4e6f..83c1adfe3d8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,21 @@ English Dolibarr ChangeLog -------------------------------------------------------------- +***** ChangeLog for 12.0.0 compared to 11.0.0 ***** +For Users: + + +For Developers or integrators: + + + +WARNING: + +Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: +* PHP 5.5 is no more supported. Minimum PHP is now 5.6+. + + + ***** ChangeLog for 11.0.0 compared to 10.0.0 ***** For Users: diff --git a/build/docker/Dockerfile b/build/docker/Dockerfile index 507170c7368..4b1df7e0876 100644 --- a/build/docker/Dockerfile +++ b/build/docker/Dockerfile @@ -3,10 +3,11 @@ FROM php:7.2-apache ENV HOST_USER_ID 33 ENV PHP_INI_DATE_TIMEZONE 'UTC' -RUN apt-get update && apt-get install -y libpng-dev libjpeg-dev libldap2-dev zlib1g-dev libicu-dev g++\ +RUN apt-get update && apt-get install -y libpng-dev libjpeg-dev libldap2-dev libzip-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 \ diff --git a/dev/initdata/dbf/import-dbf.php b/dev/initdata/dbf/import-dbf.php new file mode 100644 index 00000000000..0718a472cd6 --- /dev/null +++ b/dev/initdata/dbf/import-dbf.php @@ -0,0 +1,231 @@ +#!/usr/bin/env php + + * Copyright (C) 2016 Juanjo Menent + * + * 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 . + * + * WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE + */ + +/** + * \file dev/initdata/import-dbf.php + * \brief Script example to create a table from a large DBF file (openoffice) + * To purge data, you can have a look at purge-data.php + */ +// Test si mode batch +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); + +$path = dirname(__FILE__) . '/'; +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; +} + +// Recupere root dolibarr +$path = dirname($_SERVER["PHP_SELF"]); +require $path . "./../htdocs/master.inc.php"; +require $path . "/includes/dbase.class.php"; + +// Global variables +$version = DOL_VERSION; +$confirmed = 1; +$error = 0; + + +/* + * Main + */ + +@set_time_limit(0); +print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n"; +dol_syslog($script_file . " launched with arg " . implode(',', $argv)); + + +$filepath = $argv[1]; +$filepatherr = $filepath . '.err'; +$startchar = empty($argv[2]) ? 0 : (int) $argv[2]; +$deleteTable = empty($argv[3]) ? 1 : 0; +$startlinenb = empty($argv[3]) ? 1 : (int) $argv[3]; +$endlinenb = empty($argv[4]) ? 0 : (int) $argv[4]; + +if (empty($filepath)) { + print "Usage: php $script_file myfilepath.dbf [removeChatColumnName] [startlinenb] [endlinenb]\n"; + print "Example: php $script_file myfilepath.dbf 0 2 1002\n"; + print "\n"; + exit(-1); +} +if (!file_exists($filepath)) { + print "Error: File " . $filepath . " not found.\n"; + print "\n"; + exit(-1); +} + +$ret = $user->fetch('', 'admin'); +if (!$ret > 0) { + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; +} +$user->getrights(); + +// Ask confirmation +if (!$confirmed) { + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); +} + +// Open input and output files +$fhandle = dbase_open($filepath, 0); +if (!$fhandle) { + print 'Error: Failed to open file ' . $filepath . "\n"; + exit(1); +} +$fhandleerr = fopen($filepatherr, 'w'); +if (!$fhandleerr) { + print 'Error: Failed to open file ' . $filepatherr . "\n"; + exit(1); +} + +$langs->setDefaultLang($defaultlang); + +$record_numbers = dbase_numrecords($fhandle); +$table_name = substr(basename($filepath), 0, strpos(basename($filepath), '.')); +print 'Info: ' . $record_numbers . " lines in file \n"; +$header = dbase_get_header_info($fhandle); +if ($deleteTable) { + $db->query("DROP TABLE IF EXISTS `$table_name`"); +} +$sqlCreate = "CREATE TABLE IF NOT EXISTS `$table_name` ( `id` INT(11) NOT NULL AUTO_INCREMENT "; +$fieldArray = array("`id`"); +foreach ($header as $value) { + $fieldName = substr(str_replace('_', '', $value['name']), $startchar); + $fieldArray[] = "`$fieldName`"; + $sqlCreate .= ", `" . $fieldName . "` VARCHAR({$value['length']}) NULL DEFAULT NULL "; +} +$sqlCreate .= ", PRIMARY KEY (`id`)) ENGINE = InnoDB"; +$resql = $db->query($sqlCreate); +if ($resql !== false) { + print "Table $table_name created\n"; +} else { + var_dump($db->errno()); + print "Impossible : " . $sqlCreate . "\n"; + die(); +} + +$i = 0; +$nboflines++; + +$fields = implode(',', $fieldArray); +//var_dump($fieldArray);die(); +$maxLength = 0; +for ($i = 1; $i <= $record_numbers; $i++) { + if ($startlinenb && $i < $startlinenb) + continue; + if ($endlinenb && $i > $endlinenb) + continue; + $row = dbase_get_record_with_names($fhandle, $i); + if ($row === false || (isset($row["deleted"]) && $row["deleted"] == '1')) + continue; + $sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,"; + array_shift($row); // remove delete column + foreach ($row as $value) { + $sqlInsert .= "'" . $db->escape(utf8_encode($value)) . "', "; + } + replaceable_echo(implode("\t", $row)); + $sqlInsert = rtrim($sqlInsert, ', '); + $sqlInsert .= ")"; + $resql = $db->query($sqlInsert); + if ($resql === false) { + print "Impossible : " . $sqlInsert . "\n"; + var_dump($row, $db->errno()); + die(); + } + // $fields = (object) $row; + // var_dump($fields); + continue; +} +die(); + + + + + +// commit or rollback +print "Nb of lines qualified: " . $nboflines . "\n"; +print "Nb of errors: " . $error . "\n"; +if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) { + print "Rollback any changes.\n"; + $db->rollback(); +} else { + print "Commit all changes.\n"; + $db->commit(); +} + +$db->close(); +fclose($fhandle); +fclose($fhandleerr); + +exit($error); + + +/** + * replaceable_echo + * + * @param string $message Message + * @param int $force_clear_lines Force clear messages + * @return void + */ +function replaceable_echo($message, $force_clear_lines = null) +{ + static $last_lines = 0; + + if (!is_null($force_clear_lines)) { + $last_lines = $force_clear_lines; + } + + $toss = array(); + $status = 0; + $term_width = exec('tput cols', $toss, $status); + if ($status) { + $term_width = 64; // Arbitrary fall-back term width. + } + + $line_count = 0; + foreach (explode("\n", $message) as $line) { + $line_count += count(str_split($line, $term_width)); + } + + // Erasure MAGIC: Clear as many lines as the last output had. + for ($i = 0; $i < $last_lines; $i++) { + // Return to the beginning of the line + echo "\r"; + // Erase to the end of the line + echo "\033[K"; + // Move cursor Up a line + echo "\033[1A"; + // Return to the beginning of the line + echo "\r"; + // Erase to the end of the line + echo "\033[K"; + // Return to the beginning of the line + echo "\r"; + // Can be consolodated into + // echo "\r\033[K\033[1A\r\033[K\r"; + } + + $last_lines = $line_count; + + echo $message . "\n"; +} diff --git a/dev/initdata/dbf/importdb-products.php b/dev/initdata/dbf/importdb-products.php new file mode 100644 index 00000000000..845064f0688 --- /dev/null +++ b/dev/initdata/dbf/importdb-products.php @@ -0,0 +1,241 @@ +#!/usr/bin/env php + + * Copyright (C) 2016 Juanjo Menent + * + * 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 . + * + * WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE + */ + +/** + * \file dev/initdata/import-product.php + * \brief Script example to insert products from a csv file. + * To purge data, you can have a look at purge-data.php + */ +// Test si mode batch +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path = dirname(__FILE__) . '/'; +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; +} + +// Recupere root dolibarr +$path = preg_replace('/importdb-products.php/i', '', $_SERVER["PHP_SELF"]); +require $path . "../../htdocs/master.inc.php"; +require $path . "includes/dbase.class.php"; +include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +//$delimiter = ','; +//$enclosure = '"'; +//$linelength = 10000; +//$escape = '/'; +// Global variables +$version = DOL_VERSION; +$confirmed = 1; +$error = 0; + +$tvas = [ + '1' => "20.00", + '2' => "5.50", + '3' => "0.00", + '4' => "20.60", + '5' => "19.60", +]; +$tvasD = [ + '1' => "20", + '2' => "5.5", + '3' => "0", + '4' => "20", + '5' => "20", +]; + +/* + * Main + */ + +@set_time_limit(0); +print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n"; +dol_syslog($script_file . " launched with arg " . implode(',', $argv)); + +$table = $argv[1]; + +if (empty($argv[1])) { + print "Error: Which table ?\n"; + print "\n"; + exit(-1); +} + +$ret = $user->fetch('', 'admin'); +if (!$ret > 0) { + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; +} + +$sql = "SELECT * FROM `$table` WHERE 1"; +$resql = $db->query($sql); +if ($resql) +while ($fields = $db->fetch_array($resql)) { + $errorrecord = 0; + if ($fields === false) + continue; + $nboflines++; + + $produit = new Product($db); + $produit->type = 0; + $produit->status = 1; + $produit->ref = trim($fields['REF']); + if ($produit->ref == '') + continue; + print "Process line nb " . $j . ", ref " . $produit->ref; + $produit->label = trim($fields['LIBELLE']); + if ($produit->label == '') + $produit->label = $produit->ref; + if (empty($produit->label)) + continue; + //$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : '')); + // $produit->volume = price2num($fields[8]); + // $produit->volume_unit = 0; + $produit->weight = price2num($fields['MASSE']); + $produit->weight_units = 0; // -3 = g + //$produit->customcode = $fields[10]; + $produit->barcode = str_pad($fields['CODE'], 12, "0", STR_PAD_LEFT); + $produit->barcode_type = '2'; + $produit->import_key = $fields['CODE']; + + $produit->status = 1; + $produit->status_buy = 1; + + $produit->finished = 1; + + // $produit->multiprices[0] = price2num($fields['TARIF0']); + // $produit->multiprices[1] = price2num($fields['TARIF1']); + // $produit->multiprices[2] = price2num($fields['TARIF2']); + // $produit->multiprices[3] = price2num($fields['TARIF3']); + // $produit->multiprices[4] = price2num($fields['TARIF4']); + // $produit->multiprices[5] = price2num($fields['TARIF5']); + // $produit->multiprices[6] = price2num($fields['TARIF6']); + // $produit->multiprices[7] = price2num($fields['TARIF7']); + // $produit->multiprices[8] = price2num($fields['TARIF8']); + // $produit->multiprices[9] = price2num($fields['TARIF9']); + // $produit->price_min = null; + // $produit->price_min_ttc = null; + // $produit->price = price2num($fields[11]); + // $produit->price_ttc = price2num($fields[12]); + // $produit->price_base_type = 'TTC'; + // $produit->tva_tx = price2num($fields[13]); + $produit->tva_tx = (int) ($tvas[$fields['CODTVA']]); + $produit->tva_npr = 0; + // $produit->cost_price = price2num($fields[16]); + //compta + + $produit->accountancy_code_buy = trim($fields['COMACH']); + $produit->accountancy_code_sell = trim($fields['COMVEN']); + // $produit->accountancy_code_sell_intra=trim($fields['COMVEN']); + // $produit->accountancy_code_sell_export=trim($fields['COMVEN']); + // Extrafields + // $produit->array_options['options_ecotaxdeee'] = price2num($fields[17]); + + $produit->seuil_stock_alerte = $fields['STALERTE']; + $ret = $produit->create($user, 0); + if ($ret < 0) { + print " - Error in create result code = " . $ret . " - " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - Creation OK with ref " . $produit->ref . " - id = " . $ret; + } + + dol_syslog("Add prices"); + + // If we use price level, insert price for each level + if (!$errorrecord && 1) { + //$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); + $ret1 = false; + for ($i = 0; $i < 10; $i++) { + if ($fields['TARIF' . ($i)] == 0) + continue; + $ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0; + } + if ($ret1) { + print " - Error in updatePrice result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - updatePrice OK"; + } + } + + + // dol_syslog("Add multilangs"); + // Add alternative languages + // if (!$errorrecord && 1) { + // $produit->multilangs['fr_FR'] = array('label' => $produit->label, 'description' => $produit->description, 'note' => $produit->note_private); + // $produit->multilangs['en_US'] = array('label' => $fields[3], 'description' => $produit->description, 'note' => $produit->note_private); + // + // $ret = $produit->setMultiLangs($user); + // if ($ret < 0) { + // print " - Error in setMultiLangs result code = " . $ret . " - " . $produit->errorsToString(); + // $errorrecord++; + // } else { + // print " - setMultiLangs OK"; + // } + // } + + + dol_syslog("Add stocks"); + // stocks + if (!$errorrecord && $fields['STOCK'] != 0) { + $rets = $produit->correct_stock($user, 1, $fields['STOCK'], 0, 'Stock importé'); + if ($rets < 0) { + print " - Error in correct_stock result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - correct_stock OK"; + } + } + + //update date créa + if (!$errorrecord) { + $date = substr($fields['DATCREA'], 0, 4) . '-' . substr($fields['DATCREA'], 4, 2) . '-' . substr($fields['DATCREA'], 6, 2); + $retd = $db->query("UPDATE `llx_product` SET `datec` = '$date 00:00:00' WHERE `llx_product`.`rowid` = $produit->id"); + if ($retd < 1) { + print " - Error in update date créa result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - update date créa OK"; + } + } + print "\n"; + + if ($errorrecord) { + print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n"); + var_dump($db); + die(); + $error++; // $errorrecord will be reset + } + $j++; +} else + die("error : $sql"); + + + + +// commit or rollback +print "Nb of lines qualified: " . $nboflines . "\n"; +print "Nb of errors: " . $error . "\n"; +$db->close(); + +exit($error); diff --git a/dev/initdata/dbf/importdb-thirdparties.php b/dev/initdata/dbf/importdb-thirdparties.php new file mode 100644 index 00000000000..8f0eb0635f0 --- /dev/null +++ b/dev/initdata/dbf/importdb-thirdparties.php @@ -0,0 +1,355 @@ +#!/usr/bin/env php + + * Copyright (C) 2016 Juanjo Menent + * + * 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 . + * + * WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE + */ + +/** + * \file dev/initdata/import-product.php + * \brief Script example to insert products from a csv file. + * To purge data, you can have a look at purge-data.php + */ +// Test si mode batch +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path = dirname(__FILE__) . '/'; +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; +} + +// Recupere root dolibarr +$path = preg_replace('/importdb-thirdparties.php/i', '', $_SERVER["PHP_SELF"]); +require $path . "../../htdocs/master.inc.php"; +require $path . "includes/dbase.class.php"; +include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +//$delimiter = ','; +//$enclosure = '"'; +//$linelength = 10000; +//$escape = '/'; +// Global variables +$version = DOL_VERSION; +$confirmed = 1; +$error = 0; + +$civilPrivate = array("MLLE", + "MM", + "MM/MADAME", + "MME", + "MME.", + "MME²", + "MMONSIEUR", + "MMR", + "MOBNSIEUR", + "MOMSIEUR", + "MON SIEUR", + "MONDIAL", + "MONIEUR", + "MONJSIEUR", + "MONNSIEUR", + "MONRIEUR", + "MONS", + "MONSIEÕR", + "MONSIER", + "MONSIERU", + "MONSIEU", + "monsieue", + "MONSIEUR", + "Monsieur     \"", + "MONSIEUR    \"", + "MONSIEUR   E", + "MONSIEUR  DENIS", + "MONSIEUR ET MME", + "MONSIEUR!", + "MONSIEUR.", + "MONSIEUR.MADAME", + "MONSIEUR3", + "MONSIEURN", + "MONSIEURT", + "MONSIEUR£", + "MONSIEYR", + "Monsigur", + "MONSIIEUR", + "MONSIUER", + "MONSIZEUR", + "MOPNSIEUR", + "MOSIEUR", + "MR", + "Mr  Mme", + "Mr - MME", + "MR BLANC", + "MR ET MME", + "mr mm", + "MR OU MME", + "Mr.", + "MR/MME", + "MRME", + "MRR", + "Mrs", + "Mademoiselle", + "MADAOME", + "madamme", + "MADAME", + "M0NSIEUR", + "M.et Madame", + "M. ET MR", + "M.", + "M%", + "M MME", + "M ET MME", + "M", + "M CROCE", + "M DIEVART", +); + +/* + * Main + */ + +@set_time_limit(0); +print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n"; +dol_syslog($script_file . " launched with arg " . implode(',', $argv)); + +$table = $argv[1]; + +if (empty($argv[1])) { + print "Error: Quelle table ?\n"; + print "\n"; + exit(-1); +} + +$ret = $user->fetch('', 'admin'); +if (!$ret > 0) { + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; +} + +$sql = "SELECT * FROM `$table` WHERE 1 "; //ORDER BY REMISE DESC,`LCIVIL` DESC"; +$resql = $db->query($sql); +//$db->begin(); +if ($resql) +while ($fields = $db->fetch_array($resql)) { + $i++; + $errorrecord = 0; + + if ($startlinenb && $i < $startlinenb) + continue; + if ($endlinenb && $i > $endlinenb) + continue; + + $nboflines++; + + $object = new Societe($db); + $object->import_key = $fields['CODE']; + $object->state = 1; + $object->client = 3; + $object->fournisseur = 0; + + $object->name = $fields['FCIVIL'] . ' ' . $fields['FNOM']; + //$object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : ''; + + $date = $fields['DATCREA'] ? $fields['DATCREA'] : ($fields['DATMOD'] ? $fields['DATMOD'] : '20200101'); + $object->code_client = 'CU' . substr($date, 2, 2) . substr($date, 4, 2) . '-' . str_pad(substr($fields['CODE'], 0, 5), 5, "0", STR_PAD_LEFT); + + + $object->address = trim($fields['FADR1']); + if ($fields['FADR2']) + $object->address .= "\n" . trim($fields['FADR2']); + if ($fields['FADR3']) + $object->address .= "\n" . trim($fields['FADR3']); + + $object->zip = trim($fields['FPOSTE']); + $object->town = trim($fields['FVILLE']); + if ($fields['FPAYS']) + $object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid'); + else + $object->country_id = 1; + $object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']); + $object->phone = substr($object->phone, 0, 20); + $object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']); + $object->fax = substr($object->fax, 0, 20); + $object->email = trim($fields['FMAIL']); + // $object->idprof2 = trim($fields[29]); + $object->tva_intra = str_replace(['.', ' '], '', $fields['TVAINTRA']); + $object->tva_intra = substr($object->tva_intra, 0, 20); + $object->default_lang = 'fr_FR'; + + $object->cond_reglement_id = dol_getIdFromCode($db, 'PT_ORDER', 'c_payment_term', 'code', 'rowid', 1); + $object->multicurrency_code = 'EUR'; + + if ($fields['REMISE'] != '0.00') { + $object->remise_percent = abs($fields['REMISE']); + } + + // $object->code_client = $fields[9]; + // $object->code_fournisseur = $fields[10]; + + + if ($fields['FCIVIL']) { + $labeltype = in_array($fields['FCIVIL'], $civilPrivate) ? 'TE_PRIVATE' : 'TE_SMALL'; + $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'code'); + } + + // Set price level + $object->price_level = $fields['TARIF'] + 1; + // if ($labeltype == 'Revendeur') + // $object->price_level = 2; + + print "Process line nb " . $i . ", code " . $fields['CODE'] . ", name " . $object->name; + + + // Extrafields + $object->array_options['options_banque'] = $fields['BANQUE']; + $object->array_options['options_banque2'] = $fields['BANQUE2']; + $object->array_options['options_banquevalid'] = $fields['VALID']; + + if (!$errorrecord) { + $ret = $object->create($user); + if ($ret < 0) { + print " - Error in create result code = " . $ret . " - " . $object->errorsToString(); + $errorrecord++; + var_dump($object->code_client, $db); + die(); + } else { + print " - Creation OK with name " . $object->name . " - id = " . $ret; + } + } + + if (!$errorrecord) { + dol_syslog("Set price level"); + $object->set_price_level($object->price_level, $user); + } + if (!$errorrecord && @$object->remise_percent) { + dol_syslog("Set remise client"); + $object->set_remise_client($object->remise_percent, 'Importé', $user); + } + + dol_syslog("Add contact"); + // Insert an invoice contact if there is an invoice email != standard email + if (!$errorrecord && ($fields['LCIVIL'] || $fields['LNOM'])) { + $madame = array("MADAME", + "MADEMOISELLE", + "MELLE", + "MLLE", + "MM", + "Mme", + "MNE", + ); + $monsieur = array("M", + "M ET MME", + "M MME", + "M.", + "M. MME", + "M. OU Mme", + "M.ou Madame", + "MONSEUR", + "MONSIER", + "MONSIEU", + "MONSIEUR", + "monsieur:mme", + "MONSIEUR¨", + "MONSIEZUR", + "MONSIUER", + "MONSKIEUR", + "MR", + ); + $ret1 = $ret2 = 0; + + $contact = new Contact($db); + if (in_array($fields['LCIVIL'], $madame)) { + // une dame + $contact->civility_id = 'MME'; + $contact->lastname = $fields['LNOM']; + } elseif (in_array($fields['LCIVIL'], $monsieur)) { + // un monsieur + $contact->civility_id = 'MR'; + $contact->lastname = $fields['LNOM']; + } elseif (in_array($fields['LCIVIL'], ['DOCTEUR'])) { + // un monsieur + $contact->civility_id = 'DR'; + $contact->lastname = $fields['LNOM']; + } else { + // un a rattraper + $contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM']; + } + $contact->address = trim($fields['LADR1']); + if ($fields['LADR2']) + $contact->address .= "\n" . trim($fields['LADR2']); + if ($fields['LADR3']) + $contact->address .= "\n" . trim($fields['LADR3']); + + $contact->zip = trim($fields['LPOSTE']); + $contact->town = trim($fields['LVILLE']); + if ($fields['FPAYS']) + $contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid'); + else + $contact->country_id = 1; + $contact->email = $fields['LMAIL']; + $contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']); + $contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']); + $contact->socid = $object->id; + + $ret1 = $contact->create($user); + if ($ret1 > 0) { + //$ret2=$contact->add_contact($object->id, 'BILLING'); + } + if ($ret1 < 0 || $ret2 < 0) { + print " - Error in create contact result code = " . $ret1 . " " . $ret2 . " - " . $contact->errorsToString(); + $errorrecord++; + } else { + print " - create contact OK"; + } + } + + + //update date créa + if (!$errorrecord) { + $datec = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2); + $retd = $db->query("UPDATE `llx_societe` SET `datec` = '$datec 00:00:00' WHERE `rowid` = $object->id"); + if ($retd < 1) { + print " - Error in update date créa result " . $object->errorsToString(); + $errorrecord++; + } else { + print " - update date créa OK"; + } + } + print "\n"; + + if ($errorrecord) { + print( 'Error on record nb ' . $i . " - " . $object->errorsToString() . "\n"); + var_dump($db, $object, $contact); + // $db->rollback(); + die(); + $error++; // $errorrecord will be reset + } + $j++; +} else + die("error : $sql"); + +$db->commit(); + + + +// commit or rollback +print "Nb of lines qualified: " . $nboflines . "\n"; +print "Nb of errors: " . $error . "\n"; +$db->close(); + +exit($error); diff --git a/dev/initdata/dbf/includes/dbase.class.php b/dev/initdata/dbf/includes/dbase.class.php new file mode 100644 index 00000000000..0c2f6820a96 --- /dev/null +++ b/dev/initdata/dbf/includes/dbase.class.php @@ -0,0 +1,402 @@ +fd = $fd; + // Byte 4-7 (32-bit number): Number of records in the database file. Currently 0 + fseek($this->fd, 4, SEEK_SET); + $this->recordCount = self::getInt32($fd); + // Byte 8-9 (16-bit number): Number of bytes in the header. + fseek($this->fd, 8, SEEK_SET); + $this->headerLength = self::getInt16($fd); + // Number of fields is (headerLength - 33) / 32) + $this->fieldCount = ($this->headerLength - 33) / 32; + // Byte 10-11 (16-bit number): Number of bytes in record. + fseek($this->fd, 10, SEEK_SET); + $this->recordLength = self::getInt16($fd); + // Byte 32 - n (32 bytes each): Field descriptor array + fseek($fd, 32, SEEK_SET); + for ($i = 0; $i < $this->fieldCount; $i++) { + $data = fread($this->fd, 32); + $field = array_map('trim', unpack('a11name/a1type/c4/c1length/c1precision/s1workid/c1example/c10/c1production', $data)); + $this->fields[] = $field; + } + } + + //bool dbase_close ( resource $dbase_identifier ) + public function close() + { + fclose($this->fd); + } + + //array dbase_get_header_info ( resource $dbase_identifier ) + public function get_header_info() + { + return $this->fields; + } + + //int dbase_numfields ( resource $dbase_identifier ) + public function numfields() + { + return $this->fieldCount; + } + + //int dbase_numrecords ( resource $dbase_identifier ) + public function numrecords() + { + return $this->recordCount; + } + + //bool dbase_add_record ( resource $dbase_identifier , array $record ) + public function add_record($record) + { + if (count($record) != $this->fieldCount) + return false; + // Seek to end of file, minus the end of file marker + fseek($this->fd, 0, SEEK_END); + // Put the deleted flag + self::putChar8($this->fd, 0x20); + // Put the record + if (!$this->putRecord($record)) + return false; + // Update the record count + fseek($this->fd, 4); + self::putInt32($this->fd, ++$this->recordCount); + return true; + } + + //bool dbase_replace_record ( resource $dbase_identifier , array $record , int $record_number ) + public function replace_record($record, $record_number) + { + if (count($record) != $this->fieldCount) + return false; + if ($record_number < 1 || $record_number > $this->recordCount) + return false; + // Skip to the record location, plus the 1 byte for the deleted flag + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1); + return $this->putRecord($record); + } + + //bool dbase_delete_record ( resource $dbase_identifier , int $record_number ) + public function delete_record($record_number) + { + if ($record_number < 1 || $record_number > $this->recordCount) + return false; + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); + self::putChar8($this->fd, 0x2A); + return true; + } + + //array dbase_get_record ( resource $dbase_identifier , int $record_number ) + public function get_record($record_number) + { + if ($record_number < 1 || $record_number > $this->recordCount) + return false; + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); + $record = array( + 'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0 + ); + foreach ($this->fields as $i => &$field) { + $value = trim(fread($this->fd, $field['length'])); + if ($field['type'] == 'L') { + $value = strtolower($value); + if ($value == 't' || $value == 'y') + $value = true; + elseif ($value == 'f' || $value == 'n') + $value = false; + else + $value = null; + } + $record[$i] = $value; + } + return $record; + } + + //array dbase_get_record_with_names ( resource $dbase_identifier , int $record_number ) + public function get_record_with_names($record_number) + { + if ($record_number < 1 || $record_number > $this->recordCount) + return false; + $record = $this->get_record($record_number); + foreach ($this->fields as $i => &$field) { + $record[$field['name']] = $record[$i]; + unset($record[$i]); + } + return $record; + } + + //bool dbase_pack ( resource $dbase_identifier ) + public function pack() + { + $in_offset = $out_offset = $this->headerLength; + $new_count = 0; + $rec_count = $this->recordCount; + while ($rec_count > 0) { + fseek($this->fd, $in_offset, SEEK_SET); + $record = fread($this->fd, $this->recordLength); + $deleted = substr($record, 0, 1); + if ($deleted != '*') { + fseek($this->fd, $out_offset, SEEK_SET); + fwrite($this->fd, $record); + $out_offset += $this->recordLength; + $new_count++; + } + $in_offset += $this->recordLength; + $rec_count--; + } + ftruncate($this->fd, $out_offset); + // Update the record count + fseek($this->fd, 4); + self::putInt32($this->fd, $new_count); + } + + /* + * A few utilitiy functions + */ + + private static function length($field) + { + switch ($field[1]) { + case 'D': // Date: Numbers and a character to separate month, day, and year (stored internally as 8 digits in YYYYMMDD format) + return 8; + case 'T': // DateTime (YYYYMMDDhhmmss.uuu) (FoxPro) + return 18; + case 'M': // Memo (ignored): All ASCII characters (stored internally as 10 digits representing a .dbt block number, right justified, padded with whitespaces) + case 'N': // Number: -.0123456789 (right justified, padded with whitespaces) + case 'F': // Float: -.0123456789 (right justified, padded with whitespaces) + case 'C': // String: All ASCII characters (padded with whitespaces up to the field's length) + return $field[2]; + case 'L': // Boolean: YyNnTtFf? (? when not initialized) + return 1; + } + return 0; + } + + /* + * Functions for reading and writing bytes + */ + + private static function getChar8($fd) + { + return ord(fread($fd, 1)); + } + + private static function putChar8($fd, $value) + { + return fwrite($fd, chr($value)); + } + + private static function getInt16($fd, $n = 1) + { + $data = fread($fd, 2 * $n); + $i = unpack("S$n", $data); + if ($n == 1) + return (int) $i[1]; + else + return array_merge($i); + } + + private static function putInt16($fd, $value) + { + return fwrite($fd, pack('S', $value)); + } + + private static function getInt32($fd, $n = 1) + { + $data = fread($fd, 4 * $n); + $i = unpack("L$n", $data); + if ($n == 1) + return (int) $i[1]; + else + return array_merge($i); + } + + private static function putInt32($fd, $value) + { + return fwrite($fd, pack('L', $value)); + } + + private static function putString($fd, $value, $length = 254) + { + $ret = fwrite($fd, pack('A' . $length, $value)); + } + + private function putRecord($record) + { + foreach ($this->fields as $i => &$field) { + $value = $record[$i]; + // Number types are right aligned with spaces + if ($field['type'] == 'N' || $field['type'] == 'F' && strlen($value) < $field['length']) { + $value = str_repeat(' ', $field['length'] - strlen($value)) . $value; + } + self::putString($this->fd, $value, $field['length']); + } + return true; + } +} + +if (!function_exists('dbase_open')) { + + function dbase_open($filename, $mode) + { + return DBase::open($filename, $mode); + } + + function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE) + { + return DBase::create($filename, $fields, $type); + } + + function dbase_close($dbase_identifier) + { + return $dbase_identifier->close(); + } + + function dbase_get_header_info($dbase_identifier) + { + return $dbase_identifier->get_header_info(); + } + + function dbase_numfields($dbase_identifier) + { + $dbase_identifier->numfields(); + } + + function dbase_numrecords($dbase_identifier) + { + return $dbase_identifier->numrecords(); + } + + function dbase_add_record($dbase_identifier, $record) + { + return $dbase_identifier->add_record($record); + } + + function dbase_delete_record($dbase_identifier, $record_number) + { + return $dbase_identifier->delete_record($record_number); + } + + function dbase_replace_record($dbase_identifier, $record, $record_number) + { + return $dbase_identifier->replace_record($record, $record_number); + } + + function dbase_get_record($dbase_identifier, $record_number) + { + return $dbase_identifier->get_record($record_number); + } + + function dbase_get_record_with_names($dbase_identifier, $record_number) + { + return $dbase_identifier->get_record_with_names($record_number); + } + + function dbase_pack($dbase_identifier) + { + return $dbase_identifier->pack(); + } +} diff --git a/dev/initdata/generate-invoice.php b/dev/initdata/generate-invoice.php index 0c754b1c874..220144f2a7d 100755 --- a/dev/initdata/generate-invoice.php +++ b/dev/initdata/generate-invoice.php @@ -26,7 +26,7 @@ // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/generate-order.php b/dev/initdata/generate-order.php index b66d3a3abc9..129313c70fd 100755 --- a/dev/initdata/generate-order.php +++ b/dev/initdata/generate-order.php @@ -27,7 +27,7 @@ // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/generate-product.php b/dev/initdata/generate-product.php index 83951c57df7..49fd9860467 100755 --- a/dev/initdata/generate-product.php +++ b/dev/initdata/generate-product.php @@ -27,7 +27,7 @@ // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/generate-proposal.php b/dev/initdata/generate-proposal.php index ad8cf6025bb..d0b2cd4aa56 100755 --- a/dev/initdata/generate-proposal.php +++ b/dev/initdata/generate-proposal.php @@ -27,7 +27,7 @@ // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/generate-thirdparty.php b/dev/initdata/generate-thirdparty.php index 9f740b5705d..91c7c969b75 100755 --- a/dev/initdata/generate-thirdparty.php +++ b/dev/initdata/generate-thirdparty.php @@ -27,7 +27,7 @@ // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/import-products.php b/dev/initdata/import-products.php index e55f13c7c82..4288c5bf3b1 100755 --- a/dev/initdata/import-products.php +++ b/dev/initdata/import-products.php @@ -30,7 +30,7 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/import-thirdparties.php b/dev/initdata/import-thirdparties.php index 558745e8d06..ef1dfcc99ab 100755 --- a/dev/initdata/import-thirdparties.php +++ b/dev/initdata/import-thirdparties.php @@ -30,7 +30,7 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/initdata/import-users.php b/dev/initdata/import-users.php index 64af2f9eb64..60a672adf12 100755 --- a/dev/initdata/import-users.php +++ b/dev/initdata/import-users.php @@ -30,7 +30,7 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit; } diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index 015733ed95f..460f815755e 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -6,6 +6,7 @@ build/html build/aps dev/namespacemig + dev/initdata/dbf/includes documents htdocs/core/class/lessc.class.php htdocs/custom diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 333efefbc9d..9de858da26b 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2016-2018 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify @@ -42,16 +42,17 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'acc $search_account = GETPOST('search_account', 'alpha'); $search_label = GETPOST('search_label', 'alpha'); +$search_labelshort = GETPOST('search_labelshort', 'alpha'); $search_accountparent = GETPOST('search_accountparent', 'alpha'); $search_pcgtype = GETPOST('search_pcgtype', 'alpha'); $search_pcgsubtype = GETPOST('search_pcgsubtype', 'alpha'); // Security check if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->chartofaccount) accessforbidden(); +if (!$user->rights->accounting->chartofaccount) accessforbidden(); // Load variable for pagination -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -65,6 +66,7 @@ if (!$sortorder) $sortorder = "ASC"; $arrayfields = array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), 'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'aa.labelshort'=>array('label'=>$langs->trans("LabelToShow"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>1), 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), @@ -96,7 +98,8 @@ if (empty($reshook)) { $search_account = ""; $search_label = ""; - $search_accountparent = ""; + $search_labelshort = ""; + $search_accountparent = ""; $search_pcgtype = ""; $search_pcgsubtype = ""; $search_array_options = array(); @@ -192,7 +195,7 @@ if ($action == 'delete') { $pcgver = $conf->global->CHARTOFACCOUNTS; -$sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.active, "; +$sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.labelshort, aa.active, "; $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = ".$conf->entity; @@ -208,7 +211,7 @@ if (strlen(trim($search_account))) { $search_account_tmp = $search_account; $weremovedsomezero = 0; if (strlen($search_account_tmp) <= $lengthpaddingaccount) { - for($i = 0; $i < $lengthpaddingaccount; $i++) { + for ($i = 0; $i < $lengthpaddingaccount; $i++) { if (preg_match('/0$/', $search_account_tmp)) { $weremovedsomezero++; $search_account_tmp = preg_replace('/0$/', '', $search_account_tmp); @@ -235,6 +238,7 @@ if (strlen(trim($search_account))) { } } if (strlen(trim($search_label))) $sql .= natural_search("aa.label", $search_label); +if (strlen(trim($search_labelshort))) $sql .= natural_search("aa.labelshort", $search_labelshort); if (strlen(trim($search_accountparent)) && $search_accountparent != '-1') $sql .= natural_search("aa.account_parent", $search_accountparent, 2); if (strlen(trim($search_pcgtype))) $sql .= natural_search("aa.pcg_type", $search_pcgtype); if (strlen(trim($search_pcgsubtype))) $sql .= natural_search("aa.pcg_subtype", $search_pcgsubtype); @@ -267,6 +271,7 @@ if ($resql) if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$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 ($search_pcgsubtype) $param .= '&search_pcgsubtype='.urlencode($search_pcgsubtype); @@ -351,6 +356,7 @@ if ($resql) print ''; if (!empty($arrayfields['aa.account_number']['checked'])) print ''; if (!empty($arrayfields['aa.label']['checked'])) print ''; + if (!empty($arrayfields['aa.labelshort']['checked'])) print ''; if (!empty($arrayfields['aa.account_parent']['checked'])) { print ''; print $formaccounting->select_account($search_accountparent, 'search_accountparent', 2); @@ -368,8 +374,9 @@ if ($resql) print ''; if (!empty($arrayfields['aa.account_number']['checked'])) print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"], "aa.account_number", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['aa.label']['checked'])) print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"], "aa.label", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['aa.labelshort']['checked'])) print_liste_field_titre($arrayfields['aa.labelshort']['label'], $_SERVER["PHP_SELF"], "aa.labelshort", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['aa.account_parent']['checked'])) print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left '); - if (!empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']); + if (!empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']); if (!empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']); if (!empty($arrayfields['aa.active']['checked'])) print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); @@ -408,6 +415,15 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } + // Account label to show (label short) + if (!empty($arrayfields['aa.labelshort']['checked'])) + { + print ""; + print $obj->labelshort; + print "\n"; + if (!$i) $totalarray['nbfield']++; + } + // Account parent if (!empty($arrayfields['aa.account_parent']['checked'])) { diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index 33ff1e409e9..f2bc1907c7c 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2018 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2014 Florian Henry * * This program is free software; you can redistribute it and/or modify @@ -97,6 +97,7 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $object->account_parent = $account_parent; $object->account_category = GETPOST('account_category', 'alpha'); $object->label = GETPOST('label', 'alpha'); + $object->labelshort = GETPOST('labelshort', 'alpha'); $object->active = 1; $res = $object->create($user); @@ -162,6 +163,7 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $object->account_parent = $account_parent; $object->account_category = GETPOST('account_category', 'alpha'); $object->label = GETPOST('label', 'alpha'); + $object->labelshort = GETPOST('labelshort', 'alpha'); $result = $object->update($user); @@ -236,6 +238,10 @@ if ($action == 'create') { print ''.$langs->trans("Label").''; print ''; + // Label short + print '' . $langs->trans("LabelToShow") . ''; + print ''; + // Account parent print ''.$langs->trans("Accountparent").''; print ''; @@ -254,7 +260,7 @@ if ($action == 'create') { print ''; print ''; - // Chart of acounts subtype + // Chart of accounts subtype print ''.$langs->trans("Pcgsubtype").''; print ''; print ''; @@ -301,6 +307,10 @@ elseif ($id > 0 || $ref) { print ''.$langs->trans("Label").''; print ''; + // Label short + print '' . $langs->trans("LabelToShow") . ''; + print ''; + // Account parent print ''.$langs->trans("Accountparent").''; print ''; @@ -354,6 +364,10 @@ elseif ($id > 0 || $ref) { print ''.$langs->trans("Label").''; print ''.$object->label.''; + // Label to show + print '' . $langs->trans("LabelToShow") . ''; + print '' . $object->labelshort . ''; + // Account parent $accp = new AccountingAccount($db); if (!empty($object->account_parent)) { diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index d5a24a0e2e5..bd5b780a0b6 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2016 Florian Henry - * Copyright (C) 2013-2019 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2016-2017 Laurent Destailleur * Copyright (C) 2018 Frédéric France * @@ -86,6 +86,7 @@ $search_debit = GETPOST('search_debit', 'alpha'); $search_credit = GETPOST('search_credit', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); +$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); @@ -202,6 +203,7 @@ if (empty($reshook)) $search_debit = ''; $search_credit = ''; $search_lettering_code = ''; + $search_not_reconciled=''; } // Must be after the remove filter action, before the export. @@ -312,6 +314,10 @@ if (empty($reshook)) $filter['t.lettering_code'] = $search_lettering_code; $param .= '&search_lettering_code='.urlencode($search_lettering_code); } + if (! empty($search_not_reconciled)) { + $filter['t.reconciled_option'] = $search_not_reconciled; + $param .= '&search_not_reconciled=' . urlencode($search_not_reconciled); + } } if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->supprimer) { @@ -444,6 +450,8 @@ if (count($filter) > 0) { $sqlwhere[] = $key.'\''.$db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); + } elseif ($key == 't.reconciled_option') { + $sqlwhere[] = 't.lettering_code IS NULL'; } else { $sqlwhere[] = natural_search($key, $value, 0, 1); } @@ -758,6 +766,7 @@ if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; print ''; + print '
'.$langs->trans("NotReconciled").''; print ''; } // Code journal diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index 9cb863aec7d..91ce9f5e31a 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -260,9 +260,9 @@ if ($resql) { print '' . dol_print_date($db->jdate($obj->doc_date), 'day') . ''; print '' . $obj->doc_ref . ''; print '' . $obj->label_compte . ''; - print '' . price($obj->debit) . ''; - print '' . price($obj->credit) . ''; - print '' . price(round($solde, 2)) . ''; + print '' . price($obj->debit) . ''; + print '' . price($obj->credit) . ''; + print '' . price(round($solde, 2)) . ''; // Journal $accountingjournal = new AccountingJournal($db); @@ -285,15 +285,15 @@ if ($resql) { print ''; print ''.$langs->trans("Total").':' . "\n"; - print '' . price($debit) . ''; - print '' . price($credit) . ''; + print '' . price($debit) . ''; + print '' . price($credit) . ''; print ''; print "\n"; print ''; print ''.$langs->trans("Balancing").':' . "\n"; print ' '; - print '' . price($credit - $debit) . ''; + print '' . price($credit - $debit) . ''; print ''; print "\n"; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index 61e5e34da99..867f5303ff8 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -144,7 +144,7 @@ dol_fiche_end(); $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 .= " 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 . "' )"; if (dol_strlen($search_date_start) || dol_strlen($search_date_end)) { @@ -257,9 +257,9 @@ if ($resql) { print '' . dol_print_date($db->jdate($obj->doc_date), 'day') . ''; print '' . $obj->doc_ref . ''; print '' . $obj->label_compte . ''; - print '' . price($obj->debit) . ''; - print '' . price($obj->credit) . ''; - print '' . price(round($solde, 2)) . ''; + print '' . price($obj->debit) . ''; + print '' . price($obj->credit) . ''; + print '' . price(round($solde, 2)) . ''; // Journal $accountingjournal = new AccountingJournal($db); @@ -267,7 +267,7 @@ if ($resql) { $journaltoshow = (($result > 0)?$accountingjournal->getNomUrl(0, 0, 0, '', 0) : $obj->code_journal); print '' . $journaltoshow . ''; - if (empty($obj->lettering_code)) { + if (empty($obj->lettering_code) && empty($obj->date_validated) ) { print ''; print ''; print img_edit(); @@ -282,15 +282,15 @@ if ($resql) { print ''; print ''.$langs->trans("Total").':' . "\n"; - print '' . price($debit) . ''; - print '' . price($credit) . ''; + print '' . price($debit) . ''; + print '' . price($credit) . ''; print ''; print "\n"; print ''; print ''.$langs->trans("Balancing").':' . "\n"; print ' '; - print '' . price($credit - $debit) . ''; + print '' . price($credit - $debit) . ''; print ''; print "\n"; diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index b0007395e0a..1fc953af959 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2013-2014 Florian Henry * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Ari Elbaz (elarifr) @@ -120,7 +120,12 @@ class AccountingAccount extends CommonObject */ public $label; - /** + /** + * @var string Label short of account + */ + public $labelshort; + + /** * @var int ID */ public $fk_user_author; @@ -162,7 +167,7 @@ class AccountingAccount extends CommonObject global $conf; if ($rowid || $account_number) { - $sql = "SELECT a.rowid as rowid, a.datec, a.tms, a.fk_pcg_version, a.pcg_type, a.pcg_subtype, a.account_number, a.account_parent, a.label, a.fk_accounting_category, a.fk_user_author, a.fk_user_modif, a.active"; + $sql = "SELECT a.rowid as rowid, a.datec, a.tms, a.fk_pcg_version, a.pcg_type, a.pcg_subtype, a.account_number, a.account_parent, a.label, a.labelshort, a.fk_accounting_category, a.fk_user_author, a.fk_user_modif, a.active"; $sql .= ", ca.label as category_label"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as ca ON a.fk_accounting_category = ca.rowid"; @@ -197,6 +202,7 @@ class AccountingAccount extends CommonObject $this->account_number = $obj->account_number; $this->account_parent = $obj->account_parent; $this->label = $obj->label; + $this->labelshort = $obj->labelshort; $this->account_category = $obj->fk_accounting_category; $this->account_category_label = $obj->category_label; $this->fk_user_author = $obj->fk_user_author; @@ -240,6 +246,8 @@ class AccountingAccount extends CommonObject $this->account_number = trim($this->account_number); if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->labelshort)) + $this->labelshort = trim($this->labelshort); if (empty($this->pcg_type) || $this->pcg_type == '-1') { @@ -262,6 +270,7 @@ class AccountingAccount extends CommonObject $sql .= ", account_number"; $sql .= ", account_parent"; $sql .= ", label"; + $sql .= ", labelshort"; $sql .= ", fk_accounting_category"; $sql .= ", fk_user_author"; $sql .= ", active"; @@ -274,6 +283,7 @@ class AccountingAccount extends CommonObject $sql .= ", " . (empty($this->account_number) ? 'NULL' : "'" . $this->db->escape($this->account_number) . "'"); $sql .= ", " . (empty($this->account_parent) ? 0 : (int) $this->account_parent); $sql .= ", " . (empty($this->label) ? "''" : "'" . $this->db->escape($this->label) . "'"); + $sql .= ", " . (empty($this->labelshort) ? "''" : "'" . $this->db->escape($this->labelshort) . "'"); $sql .= ", " . (empty($this->account_category) ? 0 : (int) $this->account_category); $sql .= ", " . $user->id; $sql .= ", " . (int) $this->active; @@ -345,6 +355,7 @@ class AccountingAccount extends CommonObject $sql .= " , account_number = '" . $this->db->escape($this->account_number) . "'"; $sql .= " , account_parent = " . (int) $this->account_parent; $sql .= " , label = " . ($this->label ? "'" . $this->db->escape($this->label) . "'" : "''"); + $sql .= " , labelshort = " . ($this->labelshort ? "'" . $this->db->escape($this->labelshort) . "'" : "''"); $sql .= " , fk_accounting_category = " . (empty($this->account_category) ? 0 : (int) $this->account_category); $sql .= " , fk_user_modif = " . $user->id; $sql .= " , active = " . (int) $this->active; @@ -462,10 +473,11 @@ class AccountingAccount extends CommonObject * @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 $withcompletelabel 0=Short label (field short label), 1=Complete label (field label) * @return string String with URL */ - public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) - { + public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $withcompletelabel = 0) + { global $langs, $conf, $user; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -483,11 +495,18 @@ class AccountingAccount extends CommonObject $picto = 'billr'; $label=''; + if (empty($this->labelshort) || $withcompletelabel == 1) + { + $labeltoshow = $this->label; + } else { + $labeltoshow = $this->labelshort; + } + $label = '' . $langs->trans("ShowAccountingAccount") . ''; if (! empty($this->account_number)) $label .= '
'.$langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); - if (! empty($this->label)) - $label .= '
'.$langs->trans('Label') . ': ' . $this->label; + if (! empty($labeltoshow)) + $label .= '
'.$langs->trans('Label') . ': ' . $labeltoshow; if ($moretitle) $label.=' - '.$moretitle; $linkclose=''; @@ -514,7 +533,7 @@ class AccountingAccount extends CommonObject } $label_link = length_accountg($this->account_number); - if ($withlabel) $label_link .= ' - ' . $this->label; + if ($withlabel) $label_link .= ' - ' . $labeltoshow; if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto && $withpicto != 2) $result .= ' '; diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 6068e6ec0c1..ebc4a29793c 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -357,25 +357,25 @@ class BookKeeping extends CommonObject $sql .= ") VALUES ("; $sql .= "'".$this->db->idate($this->doc_date)."'"; $sql .= ", ".(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'"); - $sql .= ",'".$this->db->escape($this->doc_type)."'"; - $sql .= ",'".$this->db->escape($this->doc_ref)."'"; - $sql .= ",".$this->fk_doc; - $sql .= ",".$this->fk_docdet; - $sql .= ",'".$this->db->escape($this->thirdparty_code)."'"; - $sql .= ",'".$this->db->escape($this->subledger_account)."'"; - $sql .= ",'".$this->db->escape($this->subledger_label)."'"; - $sql .= ",'".$this->db->escape($this->numero_compte)."'"; - $sql .= ",'".$this->db->escape($this->label_compte)."'"; - $sql .= ",'".$this->db->escape($this->label_operation)."'"; - $sql .= ",".$this->debit; - $sql .= ",".$this->credit; - $sql .= ",".$this->montant; - $sql .= ",'".$this->db->escape($this->sens)."'"; - $sql .= ",'".$this->db->escape($this->fk_user_author)."'"; - $sql .= ",'".$this->db->idate($now)."'"; - $sql .= ",'".$this->db->escape($this->code_journal)."'"; - $sql .= ",'".$this->db->escape($this->journal_label)."'"; - $sql .= ",".$this->db->escape($this->piece_num); + $sql .= ", '".$this->db->escape($this->doc_type)."'"; + $sql .= ", '".$this->db->escape($this->doc_ref)."'"; + $sql .= ", ".$this->fk_doc; + $sql .= ", ".$this->fk_docdet; + $sql .= ", ".(!empty($this->thirdparty_code)?("'".$this->db->escape($this->thirdparty_code)."'"):"NULL"); + $sql .= ", ".(!empty($this->subledger_account)?("'".$this->db->escape($this->subledger_account)."'"):"NULL"); + $sql .= ", ".(!empty($this->subledger_label)?("'".$this->db->escape($this->subledger_label)."'"):"NULL"); + $sql .= ", '".$this->db->escape($this->numero_compte)."'"; + $sql .= ", ".(!empty($this->label_operation)?("'".$this->db->escape($this->label_operation)."'"):"NULL"); + $sql .= ", '".$this->db->escape($this->label_operation)."'"; + $sql .= ", ".$this->debit; + $sql .= ", ".$this->credit; + $sql .= ", ".$this->montant; + $sql .= ", ".(!empty($this->sens)?("'".$this->db->escape($this->sens)."'"):"NULL"); + $sql .= ", '".$this->db->escape($this->fk_user_author)."'"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '".$this->db->escape($this->code_journal)."'"; + $sql .= ", ".(!empty($this->journal_label)?("'".$this->db->escape($this->journal_label)."'"):"NULL"); + $sql .= ", ".$this->db->escape($this->piece_num); $sql .= ", ".(!isset($this->entity) ? $conf->entity : $this->entity); $sql .= ")"; diff --git a/htdocs/accountancy/class/lettering.class.php b/htdocs/accountancy/class/lettering.class.php index ef63fc8b15f..2012efe0eb9 100644 --- a/htdocs/accountancy/class/lettering.class.php +++ b/htdocs/accountancy/class/lettering.class.php @@ -76,6 +76,7 @@ class Lettering extends BookKeeping $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) "; $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) "; + $sql .= ' AND bk.date_validated IS NULL '; $sql .= $this->db->order('bk.doc_date', 'DESC'); // echo $sql; @@ -253,7 +254,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) . ") "; + $sql .= " rowid IN (" . implode(',', $ids) . ") AND date_validated IS NULL "; $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); @@ -275,7 +276,7 @@ class Lettering extends BookKeeping $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET"; $sql .= " lettering_code='" . $lettre . "'"; $sql .= " , date_lettering = '" . $this->db->idate($now) . "'"; // todo correct date it's false - $sql .= " WHERE rowid IN (" . implode(',', $ids) . ") "; + $sql .= " WHERE rowid IN (" . implode(',', $ids) . ") AND date_validated IS NULL "; $this->db->begin(); dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 1b68d910f0d..bb6391dcb8c 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -202,7 +202,7 @@ if (empty($reshook)) { // Creation user $nuser = new User($db); - $result = $nuser->create_from_member($object, GETPOST('login')); + $result = $nuser->create_from_member($object, GETPOST('login', 'alphanohtml')); if ($result < 0) { @@ -1747,7 +1747,7 @@ else { print ''.$langs->trans("Categories").''; print ''; - print $form->showCategories($object->id, 'member', 1); + print $form->showCategories($object->id, Categorie::TYPE_MEMBER, 1); print ''; } diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index ec4042cdf88..203ded8cedd 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -46,12 +46,12 @@ class Adherent extends CommonObject /** * @var string ID to identify managed object */ - public $element='member'; + public $element = 'member'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='adherent'; + public $table_element = 'adherent'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -220,7 +220,7 @@ class Adherent extends CommonObject public $user_id; public $user_login; - public $datefin; // From member table + public $datefin; // From member table // Fields loaded by fetch_subscriptions() public $first_subscription_date; @@ -229,7 +229,7 @@ class Adherent extends CommonObject public $last_subscription_date_start; public $last_subscription_date_end; public $last_subscription_amount; - public $subscriptions=array(); + public $subscriptions = array(); /** * @var Adherent To contains a clone of this when we need to save old properties of object @@ -241,6 +241,62 @@ class Adherent extends CommonObject */ public $entity; + + 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_ext' =>array('type'=>'varchar(128)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>20), + 'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>-1, 'position'=>25), + 'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>-1, 'position'=>30), + 'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>-1, 'position'=>35), + 'login' =>array('type'=>'varchar(50)', 'label'=>'Login', 'enabled'=>1, 'visible'=>-1, 'position'=>40), + 'gender' =>array('type'=>'varchar(10)', 'label'=>'Gender', 'enabled'=>1, 'visible'=>-1, 'position'=>250), + 'pass' =>array('type'=>'varchar(50)', 'label'=>'Pass', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + 'pass_crypted' =>array('type'=>'varchar(128)', 'label'=>'Pass crypted', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'fk_adherent_type' =>array('type'=>'integer', 'label'=>'Fk adherent type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>55), + 'morphy' =>array('type'=>'varchar(3)', 'label'=>'MorPhy', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>60), + 'societe' =>array('type'=>'varchar(128)', 'label'=>'Societe', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>70), + 'address' =>array('type'=>'text', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'zip' =>array('type'=>'varchar(10)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80), + 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85), + 'state_id' =>array('type'=>'integer', 'label'=>'State id', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'country' =>array('type'=>'integer', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + 'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>100), + 'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>105), + //'skype' =>array('type'=>'varchar(255)', 'label'=>'Skype', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + 'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>115), + 'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'Phone perso', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + 'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'Phone mobile', 'enabled'=>1, 'visible'=>-1, 'position'=>125), + 'birth' =>array('type'=>'date', 'label'=>'DateToBirth', 'enabled'=>1, 'visible'=>-1, 'position'=>130), + 'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>-1, 'position'=>135), + 'public' =>array('type'=>'smallint(6)', 'label'=>'Public', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>145), + 'datefin' =>array('type'=>'datetime', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>-1, 'position'=>150), + '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), + 'datevalid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>165), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>170), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>175), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>180), + 'fk_user_mod' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user mod', 'enabled'=>1, 'visible'=>-1, 'position'=>185), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', -1=>'MemberStatusResiliatedShort')), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>800), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>805), + /*'twitter' =>array('type'=>'varchar(255)', 'label'=>'Twitter', 'enabled'=>1, 'visible'=>-1, 'position'=>210), + 'facebook' =>array('type'=>'varchar(255)', 'label'=>'Facebook', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'instagram' =>array('type'=>'varchar(255)', 'label'=>'Instagram', 'enabled'=>1, 'visible'=>-1, 'position'=>220), + 'snapchat' =>array('type'=>'varchar(255)', 'label'=>'Snapchat', 'enabled'=>1, 'visible'=>-1, 'position'=>225), + 'googleplus' =>array('type'=>'varchar(255)', 'label'=>'Googleplus', 'enabled'=>1, 'visible'=>-1, 'position'=>230), + 'youtube' =>array('type'=>'varchar(255)', 'label'=>'Youtube', 'enabled'=>1, 'visible'=>-1, 'position'=>235), + 'whatsapp' =>array('type'=>'varchar(255)', 'label'=>'Whatsapp', 'enabled'=>1, 'visible'=>-1, 'position'=>240), + 'linkedin' =>array('type'=>'varchar(255)', 'label'=>'Linkedin', 'enabled'=>1, 'visible'=>-1, 'position'=>245),*/ + ); + + + + /** * Constructor * @@ -253,7 +309,7 @@ class Adherent extends CommonObject // l'adherent n'est pas public par defaut $this->public = 0; // les champs optionnels sont vides - $this->array_options=array(); + $this->array_options = array(); } @@ -277,7 +333,7 @@ class Adherent extends CommonObject public function send_an_email($text, $subject, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = -1, $errors_to = '', $moreinheader = '') { // phpcs:enable - global $conf,$langs; + global $conf, $langs; // Detect if message is HTML if ($msgishtml == -1) @@ -288,13 +344,13 @@ class Adherent extends CommonObject dol_syslog('send_an_email msgishtml='.$msgishtml); - $texttosend=$this->makeSubstitution($text); - $subjecttosend=$this->makeSubstitution($subject); - if ($msgishtml) $texttosend=dol_htmlentitiesbr($texttosend); + $texttosend = $this->makeSubstitution($text); + $subjecttosend = $this->makeSubstitution($subject); + if ($msgishtml) $texttosend = dol_htmlentitiesbr($texttosend); // Envoi mail confirmation - $from=$conf->email_from; - if (! empty($conf->global->ADHERENT_MAIL_FROM)) $from=$conf->global->ADHERENT_MAIL_FROM; + $from = $conf->email_from; + if (!empty($conf->global->ADHERENT_MAIL_FROM)) $from = $conf->global->ADHERENT_MAIL_FROM; $trackid = 'mem'.$this->id; @@ -307,7 +363,7 @@ class Adherent extends CommonObject } else { - $this->error=$langs->trans("ErrorFailedToSendMail", $from, $this->email).'. '.$mailfile->error; + $this->error = $langs->trans("ErrorFailedToSendMail", $from, $this->email).'. '.$mailfile->error; return -1; } } @@ -321,57 +377,57 @@ class Adherent extends CommonObject */ public function makeSubstitution($text) { - global $conf,$langs; + global $conf, $langs; $birthday = dol_print_date($this->birth, 'day'); $msgishtml = 0; if (dol_textishtml($text, 1)) $msgishtml = 1; - $infos=''; - if ($this->civility_id) $infos.= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; - $infos.= $langs->transnoentities("id").": ".$this->id."\n"; - $infos.= $langs->transnoentities("Lastname").": ".$this->lastname."\n"; - $infos.= $langs->transnoentities("Firstname").": ".$this->firstname."\n"; - $infos.= $langs->transnoentities("Company").": ".$this->company."\n"; - $infos.= $langs->transnoentities("Address").": ".$this->address."\n"; - $infos.= $langs->transnoentities("Zip").": ".$this->zip."\n"; - $infos.= $langs->transnoentities("Town").": ".$this->town."\n"; - $infos.= $langs->transnoentities("Country").": ".$this->country."\n"; - $infos.= $langs->transnoentities("EMail").": ".$this->email."\n"; - $infos.= $langs->transnoentities("PhonePro").": ".$this->phone."\n"; - $infos.= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n"; - $infos.= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n"; + $infos = ''; + if ($this->civility_id) $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; + $infos .= $langs->transnoentities("id").": ".$this->id."\n"; + $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n"; + $infos .= $langs->transnoentities("Firstname").": ".$this->firstname."\n"; + $infos .= $langs->transnoentities("Company").": ".$this->company."\n"; + $infos .= $langs->transnoentities("Address").": ".$this->address."\n"; + $infos .= $langs->transnoentities("Zip").": ".$this->zip."\n"; + $infos .= $langs->transnoentities("Town").": ".$this->town."\n"; + $infos .= $langs->transnoentities("Country").": ".$this->country."\n"; + $infos .= $langs->transnoentities("EMail").": ".$this->email."\n"; + $infos .= $langs->transnoentities("PhonePro").": ".$this->phone."\n"; + $infos .= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n"; + $infos .= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n"; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { - $infos.= $langs->transnoentities("Login").": ".$this->login."\n"; - $infos.= $langs->transnoentities("Password").": ".$this->pass."\n"; + $infos .= $langs->transnoentities("Login").": ".$this->login."\n"; + $infos .= $langs->transnoentities("Password").": ".$this->pass."\n"; } - $infos.= $langs->transnoentities("Birthday").": ".$birthday."\n"; - $infos.= $langs->transnoentities("Photo").": ".$this->photo."\n"; - $infos.= $langs->transnoentities("Public").": ".yn($this->public); + $infos .= $langs->transnoentities("Birthday").": ".$birthday."\n"; + $infos .= $langs->transnoentities("Photo").": ".$this->photo."\n"; + $infos .= $langs->transnoentities("Public").": ".yn($this->public); // Substitutions - $substitutionarray=array( + $substitutionarray = array( '__ID__'=>$this->id, '__MEMBER_ID__'=>$this->id, '__CIVILITY__'=>$this->getCivilityLabel(), - '__FIRSTNAME__'=>$msgishtml?dol_htmlentitiesbr($this->firstname):($this->firstname?$this->firstname:''), - '__LASTNAME__'=>$msgishtml?dol_htmlentitiesbr($this->lastname):($this->lastname?$this->lastname:''), - '__FULLNAME__'=>$msgishtml?dol_htmlentitiesbr($this->getFullName($langs)):$this->getFullName($langs), - '__COMPANY__'=>$msgishtml?dol_htmlentitiesbr($this->company):($this->company?$this->company:''), - '__ADDRESS__'=>$msgishtml?dol_htmlentitiesbr($this->address):($this->address?$this->address:''), - '__ZIP__'=>$msgishtml?dol_htmlentitiesbr($this->zip):($this->zip?$this->zip:''), - '__TOWN__'=>$msgishtml?dol_htmlentitiesbr($this->town):($this->town?$this->town:''), - '__COUNTRY__'=>$msgishtml?dol_htmlentitiesbr($this->country):($this->country?$this->country:''), - '__EMAIL__'=>$msgishtml?dol_htmlentitiesbr($this->email):($this->email?$this->email:''), - '__BIRTH__'=>$msgishtml?dol_htmlentitiesbr($birthday):($birthday?$birthday:''), - '__PHOTO__'=>$msgishtml?dol_htmlentitiesbr($this->photo):($this->photo?$this->photo:''), - '__LOGIN__'=>$msgishtml?dol_htmlentitiesbr($this->login):($this->login?$this->login:''), - '__PASSWORD__'=>$msgishtml?dol_htmlentitiesbr($this->pass):($this->pass?$this->pass:''), - '__PHONE__'=>$msgishtml?dol_htmlentitiesbr($this->phone):($this->phone?$this->phone:''), - '__PHONEPRO__'=>$msgishtml?dol_htmlentitiesbr($this->phone_perso):($this->phone_perso?$this->phone_perso:''), - '__PHONEMOBILE__'=>$msgishtml?dol_htmlentitiesbr($this->phone_mobile):($this->phone_mobile?$this->phone_mobile:'') + '__FIRSTNAME__'=>$msgishtml ?dol_htmlentitiesbr($this->firstname) : ($this->firstname ? $this->firstname : ''), + '__LASTNAME__'=>$msgishtml ?dol_htmlentitiesbr($this->lastname) : ($this->lastname ? $this->lastname : ''), + '__FULLNAME__'=>$msgishtml ?dol_htmlentitiesbr($this->getFullName($langs)) : $this->getFullName($langs), + '__COMPANY__'=>$msgishtml ?dol_htmlentitiesbr($this->company) : ($this->company ? $this->company : ''), + '__ADDRESS__'=>$msgishtml ?dol_htmlentitiesbr($this->address) : ($this->address ? $this->address : ''), + '__ZIP__'=>$msgishtml ?dol_htmlentitiesbr($this->zip) : ($this->zip ? $this->zip : ''), + '__TOWN__'=>$msgishtml ?dol_htmlentitiesbr($this->town) : ($this->town ? $this->town : ''), + '__COUNTRY__'=>$msgishtml ?dol_htmlentitiesbr($this->country) : ($this->country ? $this->country : ''), + '__EMAIL__'=>$msgishtml ?dol_htmlentitiesbr($this->email) : ($this->email ? $this->email : ''), + '__BIRTH__'=>$msgishtml ?dol_htmlentitiesbr($birthday) : ($birthday ? $birthday : ''), + '__PHOTO__'=>$msgishtml ?dol_htmlentitiesbr($this->photo) : ($this->photo ? $this->photo : ''), + '__LOGIN__'=>$msgishtml ?dol_htmlentitiesbr($this->login) : ($this->login ? $this->login : ''), + '__PASSWORD__'=>$msgishtml ?dol_htmlentitiesbr($this->pass) : ($this->pass ? $this->pass : ''), + '__PHONE__'=>$msgishtml ?dol_htmlentitiesbr($this->phone) : ($this->phone ? $this->phone : ''), + '__PHONEPRO__'=>$msgishtml ?dol_htmlentitiesbr($this->phone_perso) : ($this->phone_perso ? $this->phone_perso : ''), + '__PHONEMOBILE__'=>$msgishtml ?dol_htmlentitiesbr($this->phone_mobile) : ($this->phone_mobile ? $this->phone_mobile : '') ); complete_substitutions_array($substitutionarray, $langs, $this); @@ -389,7 +445,7 @@ class Adherent extends CommonObject public function getmorphylib($morphy = '') { global $langs; - if (! $morphy) { $morphy=$this->morphy; } + if (!$morphy) { $morphy = $this->morphy; } if ($morphy == 'phy') { return $langs->trans("Physical"); } if ($morphy == 'mor') { return $langs->trans("Moral"); } return $morphy; @@ -404,23 +460,23 @@ class Adherent extends CommonObject */ public function create($user, $notrigger = 0) { - global $conf,$langs; + global $conf, $langs; - $error=0; + $error = 0; - $now=dol_now(); + $now = dol_now(); // Clean parameters $this->import_key = trim($this->import_key); // Check parameters - if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) + if (!empty($conf->global->ADHERENT_MAIL_REQUIRED) && !isValidEMail($this->email)) { $langs->load("errors"); $this->error = $langs->trans("ErrorBadEMail", $this->email); return -1; } - if (! $this->datec) $this->datec=$now; + if (!$this->datec) $this->datec = $now; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($this->login)) @@ -434,16 +490,16 @@ class Adherent extends CommonObject // Insert member $sql = "INSERT INTO ".MAIN_DB_PREFIX."adherent"; - $sql.= " (datec,login,fk_user_author,fk_user_mod,fk_user_valid,morphy,fk_adherent_type,entity,import_key)"; - $sql.= " VALUES ("; - $sql.= " '".$this->db->idate($this->datec)."'"; - $sql.= ", ".($this->login?"'".$this->db->escape($this->login)."'":"null"); - $sql.= ", ".($user->id>0?$user->id:"null"); // Can be null because member can be created by a guest or a script - $sql.= ", null, null, '".$this->db->escape($this->morphy)."'"; - $sql.= ", ".$this->typeid; - $sql.= ", ".$conf->entity; - $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ")"; + $sql .= " (datec,login,fk_user_author,fk_user_mod,fk_user_valid,morphy,fk_adherent_type,entity,import_key)"; + $sql .= " VALUES ("; + $sql .= " '".$this->db->idate($this->datec)."'"; + $sql .= ", ".($this->login ? "'".$this->db->escape($this->login)."'" : "null"); + $sql .= ", ".($user->id > 0 ? $user->id : "null"); // Can be null because member can be created by a guest or a script + $sql .= ", null, null, '".$this->db->escape($this->morphy)."'"; + $sql .= ", ".$this->typeid; + $sql .= ", ".$conf->entity; + $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null"); + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); @@ -452,11 +508,11 @@ class Adherent extends CommonObject $id = $this->db->last_insert_id(MAIN_DB_PREFIX."adherent"); if ($id > 0) { - $this->id=$id; - $this->ref=(string) $id; + $this->id = $id; + $this->ref = (string) $id; // Update minor fields - $result=$this->update($user, 1, 1, 0, 0, 'add'); // nosync is 1 to avoid update data of user + $result = $this->update($user, 1, 1, 0, 0, 'add'); // nosync is 1 to avoid update data of user if ($result < 0) { $this->db->rollback(); @@ -468,22 +524,22 @@ class Adherent extends CommonObject { // Add link to user $sql = "UPDATE ".MAIN_DB_PREFIX."user SET"; - $sql.= " fk_member = ".$this->id; - $sql.= " WHERE rowid = ".$this->user_id; + $sql .= " fk_member = ".$this->id; + $sql .= " WHERE rowid = ".$this->user_id; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { - $this->error='Failed to update user to make link with member'; + $this->error = 'Failed to update user to make link with member'; $this->db->rollback(); return -4; } } - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('MEMBER_CREATE', $user); + $result = $this->call_trigger('MEMBER_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } @@ -502,7 +558,7 @@ class Adherent extends CommonObject } else { - $this->error='Failed to get last insert id'; + $this->error = 'Failed to get last insert id'; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); $this->db->rollback(); return -2; @@ -510,7 +566,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -532,27 +588,27 @@ class Adherent extends CommonObject { global $conf, $langs, $hookmanager; - $nbrowsaffected=0; - $error=0; + $nbrowsaffected = 0; + $error = 0; dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncuser=".$nosyncuser.", nosyncuserpass=".$nosyncuserpass." nosyncthirdparty=".$nosyncthirdparty.", email=".$this->email); // Clean parameters - $this->lastname = trim($this->lastname)?trim($this->lastname):trim($this->lastname); - $this->firstname = trim($this->firstname)?trim($this->firstname):trim($this->firstname); + $this->lastname = trim($this->lastname) ?trim($this->lastname) : trim($this->lastname); + $this->firstname = trim($this->firstname) ?trim($this->firstname) : trim($this->firstname); $this->gender = trim($this->gender); - $this->address = ($this->address?$this->address:$this->address); - $this->zip = ($this->zip?$this->zip:$this->zip); - $this->town = ($this->town?$this->town:$this->town); - $this->country_id = ($this->country_id > 0?$this->country_id:$this->country_id); - $this->state_id = ($this->state_id > 0?$this->state_id:$this->state_id); - if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname=ucwords(trim($this->lastname)); - if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname=ucwords(trim($this->firstname)); - $this->note_public = ($this->note_public?$this->note_public:$this->note_public); - $this->note_private = ($this->note_private?$this->note_private:$this->note_private); + $this->address = ($this->address ? $this->address : $this->address); + $this->zip = ($this->zip ? $this->zip : $this->zip); + $this->town = ($this->town ? $this->town : $this->town); + $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); + $this->state_id = ($this->state_id > 0 ? $this->state_id : $this->state_id); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords(trim($this->lastname)); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords(trim($this->firstname)); + $this->note_public = ($this->note_public ? $this->note_public : $this->note_public); + $this->note_private = ($this->note_private ? $this->note_private : $this->note_private); // Check parameters - if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) + if (!empty($conf->global->ADHERENT_MAIL_REQUIRED) && !isValidEMail($this->email)) { $langs->load("errors"); $this->error = $langs->trans("ErrorBadEMail", $this->email); @@ -562,49 +618,49 @@ class Adherent extends CommonObject $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " civility = ".($this->civility_id?"'".$this->db->escape($this->civility_id)."'":"null"); - $sql.= ", firstname = ".($this->firstname?"'".$this->db->escape($this->firstname)."'":"null"); - $sql.= ", lastname = ".($this->lastname?"'".$this->db->escape($this->lastname)."'":"null"); - $sql.= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' - $sql.= ", login = ".($this->login?"'".$this->db->escape($this->login)."'":"null"); - $sql.= ", societe = ".($this->company?"'".$this->db->escape($this->company)."'":($this->societe?"'".$this->db->escape($this->societe)."'":"null")); - $sql.= ", fk_soc = ".($this->socid > 0?$this->db->escape($this->socid):"null"); - $sql.= ", address = ".($this->address?"'".$this->db->escape($this->address)."'":"null"); - $sql.= ", zip = ".($this->zip?"'".$this->db->escape($this->zip)."'":"null"); - $sql.= ", town = ".($this->town?"'".$this->db->escape($this->town)."'":"null"); - $sql.= ", country = ".($this->country_id>0?$this->db->escape($this->country_id):"null"); - $sql.= ", state_id = ".($this->state_id>0?$this->db->escape($this->state_id):"null"); - $sql.= ", email = '".$this->db->escape($this->email)."'"; - $sql.= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'"; - $sql.= ", phone = ".($this->phone?"'".$this->db->escape($this->phone)."'":"null"); - $sql.= ", phone_perso = ".($this->phone_perso?"'".$this->db->escape($this->phone_perso)."'":"null"); - $sql.= ", phone_mobile = ".($this->phone_mobile?"'".$this->db->escape($this->phone_mobile)."'":"null"); - $sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); - $sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); - $sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null"); - $sql.= ", public = '".$this->db->escape($this->public)."'"; - $sql.= ", statut = ".$this->db->escape($this->statut); - $sql.= ", fk_adherent_type = ".$this->db->escape($this->typeid); - $sql.= ", morphy = '".$this->db->escape($this->morphy)."'"; - $sql.= ", birth = ".($this->birth?"'".$this->db->idate($this->birth)."'":"null"); - if ($this->socid) $sql.= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party - if ($this->datefin) $sql.= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription - if ($this->datevalid) $sql.= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member - $sql.= ", fk_user_mod = ".($user->id>0?$user->id:'null'); // Can be null because member can be create by a guest - $sql.= " WHERE rowid = ".$this->id; + $sql .= " civility = ".($this->civility_id ? "'".$this->db->escape($this->civility_id)."'" : "null"); + $sql .= ", firstname = ".($this->firstname ? "'".$this->db->escape($this->firstname)."'" : "null"); + $sql .= ", lastname = ".($this->lastname ? "'".$this->db->escape($this->lastname)."'" : "null"); + $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' + $sql .= ", login = ".($this->login ? "'".$this->db->escape($this->login)."'" : "null"); + $sql .= ", societe = ".($this->company ? "'".$this->db->escape($this->company)."'" : ($this->societe ? "'".$this->db->escape($this->societe)."'" : "null")); + $sql .= ", fk_soc = ".($this->socid > 0 ? $this->db->escape($this->socid) : "null"); + $sql .= ", address = ".($this->address ? "'".$this->db->escape($this->address)."'" : "null"); + $sql .= ", zip = ".($this->zip ? "'".$this->db->escape($this->zip)."'" : "null"); + $sql .= ", town = ".($this->town ? "'".$this->db->escape($this->town)."'" : "null"); + $sql .= ", country = ".($this->country_id > 0 ? $this->db->escape($this->country_id) : "null"); + $sql .= ", state_id = ".($this->state_id > 0 ? $this->db->escape($this->state_id) : "null"); + $sql .= ", email = '".$this->db->escape($this->email)."'"; + $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'"; + $sql .= ", phone = ".($this->phone ? "'".$this->db->escape($this->phone)."'" : "null"); + $sql .= ", phone_perso = ".($this->phone_perso ? "'".$this->db->escape($this->phone_perso)."'" : "null"); + $sql .= ", phone_mobile = ".($this->phone_mobile ? "'".$this->db->escape($this->phone_mobile)."'" : "null"); + $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); + $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); + $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null"); + $sql .= ", public = '".$this->db->escape($this->public)."'"; + $sql .= ", statut = ".$this->db->escape($this->statut); + $sql .= ", fk_adherent_type = ".$this->db->escape($this->typeid); + $sql .= ", morphy = '".$this->db->escape($this->morphy)."'"; + $sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null"); + if ($this->socid) $sql .= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party + if ($this->datefin) $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription + if ($this->datevalid) $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member + $sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest + $sql .= " WHERE rowid = ".$this->id; // If we change the type of membership, we set also label of new type - if (! empty($this->oldcopy) && $this->typeid != $this->oldcopy->typeid) + if (!empty($this->oldcopy) && $this->typeid != $this->oldcopy->typeid) { $sql2 = "SELECT libelle as label"; - $sql2.= " FROM ".MAIN_DB_PREFIX."adherent_type"; - $sql2.= " WHERE rowid = ".$this->typeid; + $sql2 .= " FROM ".MAIN_DB_PREFIX."adherent_type"; + $sql2 .= " WHERE rowid = ".$this->typeid; $resql2 = $this->db->query($sql2); if ($resql2) { - while ($obj=$this->db->fetch_object($resql2)) + while ($obj = $this->db->fetch_object($resql2)) { - $this->type=$obj->label; + $this->type = $obj->label; } } } @@ -618,14 +674,14 @@ class Adherent extends CommonObject unset($this->state_code); unset($this->state); - $nbrowsaffected+=$this->db->affected_rows($resql); + $nbrowsaffected += $this->db->affected_rows($resql); - $action='update'; + $action = 'update'; // Actions on extra fields - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -633,48 +689,48 @@ class Adherent extends CommonObject } // Update password - if (! $error && $this->pass) + if (!$error && $this->pass) { dol_syslog(get_class($this)."::update update password"); if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) { - $isencrypted = empty($conf->global->DATABASE_PWD_ENCRYPTED)?0:1; + $isencrypted = empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1; // If password to set differs from the one found into database - $result=$this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass); - if (! $nbrowsaffected) $nbrowsaffected++; + $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass); + if (!$nbrowsaffected) $nbrowsaffected++; } } // Remove links to user and replace with new one - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::update update link to user"); $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } + if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -5; } // If there is a user linked to this member if ($this->user_id > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id." WHERE rowid = ".$this->user_id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } + if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -5; } } } - if (! $error && $nbrowsaffected) // If something has change in main data + if (!$error && $nbrowsaffected) // If something has change in main data { // Update information on linked user if it is an update - if (! $error && $this->user_id > 0 && ! $nosyncuser) + if (!$error && $this->user_id > 0 && !$nosyncuser) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; dol_syslog(get_class($this)."::update update linked user"); - $luser=new User($this->db); - $result=$luser->fetch($this->user_id); + $luser = new User($this->db); + $result = $luser->fetch($this->user_id); if ($result >= 0) { @@ -682,47 +738,47 @@ class Adherent extends CommonObject //var_dump($this->login);exit; // If option ADHERENT_LOGIN_NOT_REQUIRED is on, there is no login of member, so we do not overwrite user login to keep existing one. - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $luser->login=$this->login; + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $luser->login = $this->login; - $luser->civility_id=$this->civility_id; - $luser->firstname=$this->firstname; - $luser->lastname=$this->lastname; - $luser->gender=$this->gender; - $luser->pass=$this->pass; + $luser->civility_id = $this->civility_id; + $luser->firstname = $this->firstname; + $luser->lastname = $this->lastname; + $luser->gender = $this->gender; + $luser->pass = $this->pass; //$luser->socid=$this->fk_soc; // We do not enable this. This may transform a user into an external user. - $luser->birth=$this->birth; + $luser->birth = $this->birth; - $luser->address=$this->address; - $luser->zip=$this->zip; - $luser->town=$this->town; - $luser->country_id=$this->country_id; - $luser->state_id=$this->state_id; + $luser->address = $this->address; + $luser->zip = $this->zip; + $luser->town = $this->town; + $luser->country_id = $this->country_id; + $luser->state_id = $this->state_id; - $luser->email=$this->email; - $luser->socialnetworks=$this->socialnetworks; - $luser->office_phone=$this->phone; - $luser->user_mobile=$this->phone_mobile; + $luser->email = $this->email; + $luser->socialnetworks = $this->socialnetworks; + $luser->office_phone = $this->phone; + $luser->user_mobile = $this->phone_mobile; - $luser->fk_member=$this->id; + $luser->fk_member = $this->id; - $result=$luser->update($user, 0, 1, 1); // Use nosync to 1 to avoid cyclic updates + $result = $luser->update($user, 0, 1, 1); // Use nosync to 1 to avoid cyclic updates if ($result < 0) { - $this->error=$luser->error; + $this->error = $luser->error; dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); $error++; } } else { - $this->error=$luser->error; + $this->error = $luser->error; $error++; } } // Update information on linked thirdparty if it is an update - if (! $error && $this->fk_soc > 0 && ! $nosyncthirdparty) + if (!$error && $this->fk_soc > 0 && !$nosyncthirdparty) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; @@ -730,48 +786,48 @@ class Adherent extends CommonObject // This member is linked with a thirdparty, so we also update thirdparty informations // if this is an update. - $lthirdparty=new Societe($this->db); - $result=$lthirdparty->fetch($this->fk_soc); + $lthirdparty = new Societe($this->db); + $result = $lthirdparty->fetch($this->fk_soc); if ($result > 0) { - $lthirdparty->address=$this->address; - $lthirdparty->zip=$this->zip; - $lthirdparty->town=$this->town; - $lthirdparty->email=$this->email; - $lthirdparty->socialnetworks=$this->socialnetworks; - $lthirdparty->phone=$this->phone; - $lthirdparty->state_id=$this->state_id; - $lthirdparty->country_id=$this->country_id; + $lthirdparty->address = $this->address; + $lthirdparty->zip = $this->zip; + $lthirdparty->town = $this->town; + $lthirdparty->email = $this->email; + $lthirdparty->socialnetworks = $this->socialnetworks; + $lthirdparty->phone = $this->phone; + $lthirdparty->state_id = $this->state_id; + $lthirdparty->country_id = $this->country_id; //$lthirdparty->phone_mobile=$this->phone_mobile; - $result=$lthirdparty->update($this->fk_soc, $user, 0, 1, 1, 'update'); // Use sync to 0 to avoid cyclic updates + $result = $lthirdparty->update($this->fk_soc, $user, 0, 1, 1, 'update'); // Use sync to 0 to avoid cyclic updates if ($result < 0) { - $this->error=$lthirdparty->error; - $this->errors=$lthirdparty->errors; + $this->error = $lthirdparty->error; + $this->errors = $lthirdparty->errors; dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); $error++; } } elseif ($result < 0) { - $this->error=$lthirdparty->error; + $this->error = $lthirdparty->error; $error++; } } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('MEMBER_MODIFY', $user); + $result = $this->call_trigger('MEMBER_MODIFY', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $nbrowsaffected; @@ -785,7 +841,7 @@ class Adherent extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -2; } } @@ -806,31 +862,31 @@ class Adherent extends CommonObject // Search for last subscription id and end date $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."subscription"; - $sql.= " WHERE fk_adherent=".$this->id; - $sql.= " ORDER by dateadh DESC"; // Sort by start subscription date + $sql .= " FROM ".MAIN_DB_PREFIX."subscription"; + $sql .= " WHERE fk_adherent=".$this->id; + $sql .= " ORDER by dateadh DESC"; // Sort by start subscription date dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); - $dateop=$this->db->jdate($obj->dateop); - $datedeb=$this->db->jdate($obj->datedeb); - $datefin=$this->db->jdate($obj->datefin); + $obj = $this->db->fetch_object($resql); + $dateop = $this->db->jdate($obj->dateop); + $datedeb = $this->db->jdate($obj->datedeb); + $datefin = $this->db->jdate($obj->datefin); $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " datefin=".($datefin != '' ? "'".$this->db->idate($datefin)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " datefin=".($datefin != '' ? "'".$this->db->idate($datefin)."'" : "null"); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->last_subscription_date=$dateop; - $this->last_subscription_date_start=$datedeb; - $this->last_subscription_date_end=$datefin; - $this->datefin=$datefin; + $this->last_subscription_date = $dateop; + $this->last_subscription_date_start = $datedeb; + $this->last_subscription_date_end = $datefin; + $this->datefin = $datefin; $this->db->commit(); return 1; } @@ -842,7 +898,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -861,18 +917,18 @@ class Adherent extends CommonObject global $conf, $langs; $result = 0; - $error=0; - $errorflag=0; + $error = 0; + $errorflag = 0; // Check parameters - if (empty($rowid)) $rowid=$this->id; + if (empty($rowid)) $rowid = $this->id; $this->db->begin(); - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('MEMBER_DELETE', $user); + $result = $this->call_trigger('MEMBER_DELETE', $user); if ($result < 0) $error++; // End call triggers } @@ -880,70 +936,70 @@ class Adherent extends CommonObject // Remove category $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_member WHERE fk_member = ".$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); - $errorflag=-1; + $errorflag = -1; } // Remove subscription - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."subscription WHERE fk_adherent = ".$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); - $errorflag=-2; + $errorflag = -2; } } // Remove linked user - if (! $error) + if (!$error) { - $ret=$this->setUserId(0); + $ret = $this->setUserId(0); if ($ret < 0) { $error++; $this->error .= $this->db->lasterror(); - $errorflag=-3; + $errorflag = -3; } } // Removed extrafields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; - $errorflag=-4; + $errorflag = -4; dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); } } } // Remove adherent - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."adherent WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); - $errorflag=-5; + $errorflag = -5; } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -970,22 +1026,22 @@ class Adherent extends CommonObject { global $conf, $langs; - $error=0; + $error = 0; dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." isencrypted=".$isencrypted); // If new password not provided, we generate one - if (! $password) + if (!$password) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $password=getRandomPassword(false); + $password = getRandomPassword(false); } // Crypt password $password_crypted = dol_hash($password); $password_indatabase = ''; - if (! $isencrypted) + if (!$isencrypted) { $password_indatabase = $password; } @@ -994,61 +1050,61 @@ class Adherent extends CommonObject // Mise a jour $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; - $sql.= " SET pass_crypted = '".$this->db->escape($password_crypted)."'"; + $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."'"; //if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) if ($isencrypted) { - $sql.= ", pass = null"; + $sql .= ", pass = null"; } else { - $sql.= ", pass = '".$this->db->escape($password_indatabase)."'"; + $sql .= ", pass = '".$this->db->escape($password_indatabase)."'"; } - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; //dol_syslog("Adherent::Password sql=hidden"); dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $nbaffectedrows=$this->db->affected_rows($result); + $nbaffectedrows = $this->db->affected_rows($result); if ($nbaffectedrows) { - $this->pass=$password; - $this->pass_indatabase=$password_indatabase; - $this->pass_indatabase_crypted=$password_crypted; + $this->pass = $password; + $this->pass_indatabase = $password_indatabase; + $this->pass_indatabase_crypted = $password_crypted; - if ($this->user_id && ! $nosyncuser) + if ($this->user_id && !$nosyncuser) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // This member is linked with a user, so we also update users informations // if this is an update. - $luser=new User($this->db); - $result=$luser->fetch($this->user_id); + $luser = new User($this->db); + $result = $luser->fetch($this->user_id); if ($result >= 0) { - $result=$luser->setPassword($user, $this->pass, 0, 0, 1); + $result = $luser->setPassword($user, $this->pass, 0, 0, 1); if ($result < 0) { - $this->error=$luser->error; + $this->error = $luser->error; dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR); $error++; } } else { - $this->error=$luser->error; + $this->error = $luser->error; $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('MEMBER_NEW_PASSWORD', $user); + $result = $this->call_trigger('MEMBER_NEW_PASSWORD', $user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers } @@ -1087,16 +1143,16 @@ class Adherent extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -1; } + if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -1; } // Set link to user if ($userid > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id; - $sql.= " WHERE rowid = ".$userid; + $sql .= " WHERE rowid = ".$userid; dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -2; } + if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -2; } } $this->db->commit(); @@ -1121,15 +1177,15 @@ class Adherent extends CommonObject if ($thirdpartyid > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = null"; - $sql.= " WHERE fk_soc = '".$thirdpartyid."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE fk_soc = '".$thirdpartyid."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); $resql = $this->db->query($sql); } // Add link to third party for current member - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid>0 ? $thirdpartyid : 'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid > 0 ? $thirdpartyid : 'null'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); $resql = $this->db->query($sql); @@ -1140,7 +1196,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1160,10 +1216,10 @@ class Adherent extends CommonObject global $conf; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; - $sql.= " WHERE login='".$this->db->escape($login)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE login='".$this->db->escape($login)."'"; + $sql .= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -1192,11 +1248,11 @@ class Adherent extends CommonObject global $conf; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; - $sql.= " WHERE firstname='".$this->db->escape($firstname)."'"; - $sql.= " AND lastname='".$this->db->escape($lastname)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE firstname='".$this->db->escape($firstname)."'"; + $sql .= " AND lastname='".$this->db->escape($lastname)."'"; + $sql .= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -1227,113 +1283,113 @@ class Adherent extends CommonObject global $langs; $sql = "SELECT d.rowid, d.ref_ext, d.civility as civility_code, d.gender, d.firstname, d.lastname, d.societe as company, d.fk_soc, d.statut, d.public, d.address, d.zip, d.town, d.note_private,"; - $sql.= " d.note_public,"; - $sql.= " d.email, d.socialnetworks, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,"; - $sql.= " d.photo, d.fk_adherent_type, d.morphy, d.entity,"; - $sql.= " d.datec as datec,"; - $sql.= " d.tms as datem,"; - $sql.= " d.datefin as datefin,"; - $sql.= " d.birth as birthday,"; - $sql.= " d.datevalid as datev,"; - $sql.= " d.country,"; - $sql.= " d.state_id,"; - $sql.= " d.model_pdf,"; - $sql.= " c.rowid as country_id, c.code as country_code, c.label as country,"; - $sql.= " dep.nom as state, dep.code_departement as state_code,"; - $sql.= " t.libelle as type, t.subscription as subscription,"; - $sql.= " u.rowid as user_id, u.login as user_login"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member"; - $sql.= " WHERE d.fk_adherent_type = t.rowid"; - if ($rowid) $sql.= " AND d.rowid=".$rowid; + $sql .= " d.note_public,"; + $sql .= " d.email, d.socialnetworks, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,"; + $sql .= " d.photo, d.fk_adherent_type, d.morphy, d.entity,"; + $sql .= " d.datec as datec,"; + $sql .= " d.tms as datem,"; + $sql .= " d.datefin as datefin,"; + $sql .= " d.birth as birthday,"; + $sql .= " d.datevalid as datev,"; + $sql .= " d.country,"; + $sql .= " d.state_id,"; + $sql .= " d.model_pdf,"; + $sql .= " c.rowid as country_id, c.code as country_code, c.label as country,"; + $sql .= " dep.nom as state, dep.code_departement as state_code,"; + $sql .= " t.libelle as type, t.subscription as subscription,"; + $sql .= " u.rowid as user_id, u.login as user_login"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member"; + $sql .= " WHERE d.fk_adherent_type = t.rowid"; + if ($rowid) $sql .= " AND d.rowid=".$rowid; elseif ($ref || $fk_soc) { - $sql.= " AND d.entity IN (".getEntity('adherent').")"; - if ($ref) $sql.= " AND d.rowid='".$this->db->escape($ref)."'"; - elseif ($fk_soc > 0) $sql.= " AND d.fk_soc=".$fk_soc; + $sql .= " AND d.entity IN (".getEntity('adherent').")"; + if ($ref) $sql .= " AND d.rowid='".$this->db->escape($ref)."'"; + elseif ($fk_soc > 0) $sql .= " AND d.fk_soc=".$fk_soc; } elseif ($ref_ext) { - $sql.= " AND d.ref_ext='".$this->db->escape($ref_ext)."'"; + $sql .= " AND d.ref_ext='".$this->db->escape($ref_ext)."'"; } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->entity = $obj->entity; - $this->ref = $obj->rowid; - $this->id = $obj->rowid; - $this->ref_ext = $obj->ref_ext; + $this->entity = $obj->entity; + $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref_ext = $obj->ref_ext; - $this->civility_id = $obj->civility_code; // Bad. Kept for backard compatibility + $this->civility_id = $obj->civility_code; // Bad. Kept for backard compatibility $this->civility_code = $obj->civility_code; - $this->civility = $obj->civility_code?($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code):''; + $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : ''; $this->firstname = $obj->firstname; $this->lastname = $obj->lastname; - $this->gender = $obj->gender; + $this->gender = $obj->gender; $this->login = $obj->login; $this->societe = $obj->company; $this->company = $obj->company; $this->socid = $obj->fk_soc; - $this->fk_soc = $obj->fk_soc; // For backward compatibility + $this->fk_soc = $obj->fk_soc; // For backward compatibility $this->address = $obj->address; - $this->zip = $obj->zip; + $this->zip = $obj->zip; $this->town = $obj->town; $this->pass = $obj->pass; - $this->pass_indatabase = $obj->pass; + $this->pass_indatabase = $obj->pass; $this->pass_indatabase_crypted = $obj->pass_crypted; - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_id?$obj->state_code:''; - $this->state = $obj->state_id?$obj->state:''; + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_id ? $obj->state_code : ''; + $this->state = $obj->state_id ? $obj->state : ''; $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; + $this->country_code = $obj->country_code; if ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) $this->country = $langs->transnoentitiesnoconv("Country".$obj->country_code); else - $this->country=$obj->country; + $this->country = $obj->country; $this->phone = $obj->phone; - $this->phone_perso = $obj->phone_perso; - $this->phone_mobile = $obj->phone_mobile; + $this->phone_perso = $obj->phone_perso; + $this->phone_mobile = $obj->phone_mobile; $this->email = $obj->email; $this->socialnetworks = (array) json_decode($obj->socialnetworks, true); - $this->photo = $obj->photo; + $this->photo = $obj->photo; $this->statut = $obj->statut; $this->public = $obj->public; $this->datec = $this->db->jdate($obj->datec); $this->date_creation = $this->db->jdate($obj->datec); $this->datem = $this->db->jdate($obj->datem); - $this->date_modification= $this->db->jdate($obj->datem); - $this->datefin = $this->db->jdate($obj->datefin); - $this->datevalid = $this->db->jdate($obj->datev); - $this->date_validation = $this->db->jdate($obj->datev); - $this->birth = $this->db->jdate($obj->birthday); + $this->date_modification = $this->db->jdate($obj->datem); + $this->datefin = $this->db->jdate($obj->datefin); + $this->datevalid = $this->db->jdate($obj->datev); + $this->date_validation = $this->db->jdate($obj->datev); + $this->birth = $this->db->jdate($obj->birthday); - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; $this->morphy = $obj->morphy; $this->typeid = $obj->fk_adherent_type; - $this->type = $obj->type; - $this->need_subscription = $obj->subscription; + $this->type = $obj->type; + $this->need_subscription = $obj->subscription; - $this->user_id = $obj->user_id; - $this->user_login = $obj->user_login; + $this->user_id = $obj->user_id; + $this->user_login = $obj->user_login; - $this->model_pdf = $obj->model_pdf; + $this->model_pdf = $obj->model_pdf; // Retreive all extrafield // fetch optionals attributes and labels @@ -1343,7 +1399,7 @@ class Adherent extends CommonObject // Load other properties if ($fetch_subscriptions) { - $result=$this->fetch_subscriptions(); + $result = $this->fetch_subscriptions(); } return $this->id; @@ -1355,7 +1411,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -1377,47 +1433,47 @@ class Adherent extends CommonObject require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $sql = "SELECT c.rowid, c.fk_adherent, c.subscription, c.note, c.fk_bank,"; - $sql.= " c.tms as datem,"; - $sql.= " c.datec as datec,"; - $sql.= " c.dateadh as dateh,"; - $sql.= " c.datef as datef"; - $sql.= " FROM ".MAIN_DB_PREFIX."subscription as c"; - $sql.= " WHERE c.fk_adherent = ".$this->id; - $sql.= " ORDER BY c.dateadh"; + $sql .= " c.tms as datem,"; + $sql .= " c.datec as datec,"; + $sql .= " c.dateadh as dateh,"; + $sql .= " c.datef as datef"; + $sql .= " FROM ".MAIN_DB_PREFIX."subscription as c"; + $sql .= " WHERE c.fk_adherent = ".$this->id; + $sql .= " ORDER BY c.dateadh"; dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->subscriptions=array(); + $this->subscriptions = array(); - $i=0; + $i = 0; while ($obj = $this->db->fetch_object($resql)) { - if ($i==0) + if ($i == 0) { - $this->first_subscription_date=$this->db->jdate($obj->datec); - $this->first_subscription_date_start=$this->db->jdate($obj->dateh); - $this->first_subscription_date_end=$this->db->jdate($obj->datef); - $this->first_subscription_amount=$obj->subscription; + $this->first_subscription_date = $this->db->jdate($obj->datec); + $this->first_subscription_date_start = $this->db->jdate($obj->dateh); + $this->first_subscription_date_end = $this->db->jdate($obj->datef); + $this->first_subscription_amount = $obj->subscription; } - $this->last_subscription_date=$this->db->jdate($obj->datec); - $this->last_subscription_date_start=$this->db->jdate($obj->datef); - $this->last_subscription_date_end=$this->db->jdate($obj->datef); - $this->last_subscription_amount=$obj->subscription; + $this->last_subscription_date = $this->db->jdate($obj->datec); + $this->last_subscription_date_start = $this->db->jdate($obj->datef); + $this->last_subscription_date_end = $this->db->jdate($obj->datef); + $this->last_subscription_amount = $obj->subscription; - $subscription=new Subscription($this->db); - $subscription->id=$obj->rowid; - $subscription->fk_adherent=$obj->fk_adherent; - $subscription->amount=$obj->subscription; - $subscription->note=$obj->note; - $subscription->fk_bank=$obj->fk_bank; - $subscription->datem=$this->db->jdate($obj->datem); - $subscription->datec=$this->db->jdate($obj->datec); - $subscription->dateh=$this->db->jdate($obj->dateh); - $subscription->datef=$this->db->jdate($obj->datef); + $subscription = new Subscription($this->db); + $subscription->id = $obj->rowid; + $subscription->fk_adherent = $obj->fk_adherent; + $subscription->amount = $obj->subscription; + $subscription->note = $obj->note; + $subscription->fk_bank = $obj->fk_bank; + $subscription->datem = $this->db->jdate($obj->datem); + $subscription->datec = $this->db->jdate($obj->datec); + $subscription->dateh = $this->db->jdate($obj->dateh); + $subscription->datef = $this->db->jdate($obj->datef); - $this->subscriptions[]=$subscription; + $this->subscriptions[] = $subscription; $i++; } @@ -1425,7 +1481,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->error().' sql='.$sql; + $this->error = $this->db->error().' sql='.$sql; return -1; } } @@ -1447,20 +1503,20 @@ class Adherent extends CommonObject */ public function subscription($date, $amount, $accountid = 0, $operation = '', $label = '', $num_chq = '', $emetteur_nom = '', $emetteur_banque = '', $datesubend = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; - $error=0; + $error = 0; // Clean parameters - if (! $amount) $amount=0; + if (!$amount) $amount = 0; $this->db->begin(); if ($datesubend) { - $datefin=$datesubend; + $datefin = $datesubend; } else { @@ -1470,30 +1526,30 @@ class Adherent extends CommonObject } // Create subscription - $subscription=new Subscription($this->db); - $subscription->fk_adherent=$this->id; - $subscription->dateh=$date; // Date of new subscription - $subscription->datef=$datefin; // End data of new subscription - $subscription->amount=$amount; - $subscription->note=$label; // deprecated - $subscription->note_public=$label; + $subscription = new Subscription($this->db); + $subscription->fk_adherent = $this->id; + $subscription->dateh = $date; // Date of new subscription + $subscription->datef = $datefin; // End data of new subscription + $subscription->amount = $amount; + $subscription->note = $label; // deprecated + $subscription->note_public = $label; - $rowid=$subscription->create($user); + $rowid = $subscription->create($user); if ($rowid > 0) { // Update denormalized subscription end date (read database subscription to find values) // This will also update this->datefin - $result=$this->update_end_date($user); + $result = $this->update_end_date($user); if ($result > 0) { // Change properties of object (used by triggers) - $this->last_subscription_date=dol_now(); - $this->last_subscription_date_start=$date; - $this->last_subscription_date_end=$datefin; - $this->last_subscription_amount=$amount; + $this->last_subscription_date = dol_now(); + $this->last_subscription_date_start = $date; + $this->last_subscription_date_end = $datefin; + $this->last_subscription_amount = $amount; } - if (! $error) + if (!$error) { $this->db->commit(); return $rowid; @@ -1506,8 +1562,8 @@ class Adherent extends CommonObject } else { - $this->error=$subscription->error; - $this->errors=$subscription->errors; + $this->error = $subscription->error; + $this->errors = $subscription->errors; $this->db->rollback(); return -1; } @@ -1537,7 +1593,7 @@ class Adherent extends CommonObject $error = 0; - $this->invoice = null; // This will contains invoice if an invoice is created + $this->invoice = null; // This will contains invoice if an invoice is created dol_syslog("subscriptionComplementaryActions subscriptionid=".$subscriptionid." option=".$option." accountid=".$accountid." datesubscription=".$datesubscription." paymentdate=".$paymentdate." label=".$label." amount=".$amount." num_chq=".$num_chq." autocreatethirdparty=".$autocreatethirdparty); @@ -1546,42 +1602,42 @@ class Adherent extends CommonObject { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acct=new Account($this->db); - $result=$acct->fetch($accountid); + $acct = new Account($this->db); + $result = $acct->fetch($accountid); - $dateop=$paymentdate; + $dateop = $paymentdate; - $insertid=$acct->addline($dateop, $operation, $label, $amount, $num_chq, '', $user, $emetteur_nom, $emetteur_banque); + $insertid = $acct->addline($dateop, $operation, $label, $amount, $num_chq, '', $user, $emetteur_nom, $emetteur_banque); if ($insertid > 0) { - $inserturlid=$acct->add_url_line($insertid, $this->id, DOL_URL_ROOT.'/adherents/card.php?rowid=', $this->getFullname($langs), 'member'); + $inserturlid = $acct->add_url_line($insertid, $this->id, DOL_URL_ROOT.'/adherents/card.php?rowid=', $this->getFullname($langs), 'member'); if ($inserturlid > 0) { // Update table subscription - $sql ="UPDATE ".MAIN_DB_PREFIX."subscription SET fk_bank=".$insertid; - $sql.=" WHERE rowid=".$subscriptionid; + $sql = "UPDATE ".MAIN_DB_PREFIX."subscription SET fk_bank=".$insertid; + $sql .= " WHERE rowid=".$subscriptionid; dol_syslog("subscription::subscription", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) + if (!$resql) { $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->error; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; } } else { $error++; - $this->error=$acct->error; - $this->errors=$acct->errors; + $this->error = $acct->error; + $this->errors = $acct->errors; } } else { $error++; - $this->error=$acct->error; - $this->errors=$acct->errors; + $this->error = $acct->error; + $this->errors = $acct->errors; } } @@ -1591,31 +1647,31 @@ class Adherent extends CommonObject require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/paymentterm.class.php'; - $invoice=new Facture($this->db); - $customer=new Societe($this->db); + $invoice = new Facture($this->db); + $customer = new Societe($this->db); - if (! $error) + if (!$error) { - if (! ($this->fk_soc > 0)) // If not yet linked to a company + if (!($this->fk_soc > 0)) // If not yet linked to a company { if ($autocreatethirdparty) { // Create a linked thirdparty to member - $companyalias=''; + $companyalias = ''; $fullname = $this->getFullName($langs); if ($this->morphy == 'mor') { - $companyname=$this->company; - if (! empty($fullname)) $companyalias=$fullname; + $companyname = $this->company; + if (!empty($fullname)) $companyalias = $fullname; } else { - $companyname=$fullname; - if (! empty($this->company)) $companyalias=$this->company; + $companyname = $fullname; + if (!empty($this->company)) $companyalias = $this->company; } - $result=$customer->create_from_member($this, $companyname, $companyalias); + $result = $customer->create_from_member($this, $companyname, $companyalias); if ($result < 0) { $this->error = $customer->error; @@ -1630,54 +1686,54 @@ class Adherent extends CommonObject else { $langs->load("errors"); - $this->error=$langs->trans("ErrorMemberNotLinkedToAThirpartyLinkOrCreateFirst"); - $this->errors[]=$this->error; + $this->error = $langs->trans("ErrorMemberNotLinkedToAThirpartyLinkOrCreateFirst"); + $this->errors[] = $this->error; $error++; } } } - if (! $error) + if (!$error) { - $result=$customer->fetch($this->fk_soc); + $result = $customer->fetch($this->fk_soc); if ($result <= 0) { - $this->error=$customer->error; - $this->errors=$customer->errors; + $this->error = $customer->error; + $this->errors = $customer->errors; $error++; } } - if (! $error) + if (!$error) { // Create draft invoice - $invoice->type=Facture::TYPE_STANDARD; - $invoice->cond_reglement_id=$customer->cond_reglement_id; + $invoice->type = Facture::TYPE_STANDARD; + $invoice->cond_reglement_id = $customer->cond_reglement_id; if (empty($invoice->cond_reglement_id)) { - $paymenttermstatic=new PaymentTerm($this->db); - $invoice->cond_reglement_id=$paymenttermstatic->getDefaultId(); + $paymenttermstatic = new PaymentTerm($this->db); + $invoice->cond_reglement_id = $paymenttermstatic->getDefaultId(); if (empty($invoice->cond_reglement_id)) { $error++; - $this->error='ErrorNoPaymentTermRECEPFound'; - $this->errors[]=$this->error; + $this->error = 'ErrorNoPaymentTermRECEPFound'; + $this->errors[] = $this->error; } } - $invoice->socid=$this->fk_soc; - $invoice->date=$datesubscription; + $invoice->socid = $this->fk_soc; + $invoice->date = $datesubscription; // Possibility to add external linked objects with hooks $invoice->linked_objects['subscription'] = $subscriptionid; - if (! empty($_POST['other_linked_objects']) && is_array($_POST['other_linked_objects'])) + if (!empty($_POST['other_linked_objects']) && is_array($_POST['other_linked_objects'])) { $invoice->linked_objects = array_merge($invoice->linked_objects, $_POST['other_linked_objects']); } - $result=$invoice->create($user); + $result = $invoice->create($user); if ($result <= 0) { - $this->error=$invoice->error; - $this->errors=$invoice->errors; + $this->error = $invoice->error; + $this->errors = $invoice->errors; $error++; } else @@ -1686,46 +1742,46 @@ class Adherent extends CommonObject } } - if (! $error) + if (!$error) { // Add line to draft invoice - $idprodsubscription=0; - if (! empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (! empty($conf->product->enabled) || ! empty($conf->service->enabled))) $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS; + $idprodsubscription = 0; + if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS; - $vattouse=0; + $vattouse = 0; if (isset($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) && $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS == 'defaultforfoundationcountry') { - $vattouse=get_default_tva($mysoc, $mysoc, $idprodsubscription); + $vattouse = get_default_tva($mysoc, $mysoc, $idprodsubscription); } //print xx".$vattouse." - ".$mysoc." - ".$customer;exit; - $result=$invoice->addline($label, 0, 1, $vattouse, 0, 0, $idprodsubscription, 0, $datesubscription, '', 0, 0, '', 'TTC', $amount, 1); + $result = $invoice->addline($label, 0, 1, $vattouse, 0, 0, $idprodsubscription, 0, $datesubscription, '', 0, 0, '', 'TTC', $amount, 1); if ($result <= 0) { - $this->error=$invoice->error; - $this->errors=$invoice->errors; + $this->error = $invoice->error; + $this->errors = $invoice->errors; $error++; } } - if (! $error) + if (!$error) { // Validate invoice - $result=$invoice->validate($user); + $result = $invoice->validate($user); if ($result <= 0) { - $this->error=$invoice->error; - $this->errors=$invoice->errors; + $this->error = $invoice->error; + $this->errors = $invoice->errors; $error++; } } - if (! $error) + if (!$error) { // TODO Link invoice with subscription ? } // Add payment onto invoice - if (! $error && $option == 'bankviainvoice' && $accountid) + if (!$error && $option == 'bankviainvoice' && $accountid) { require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -1741,61 +1797,61 @@ class Adherent extends CommonObject $paiement->num_payment = $num_chq; $paiement->note_public = $label; - if (! $error) + if (!$error) { // Create payment line for invoice $paiement_id = $paiement->create($user); - if (! $paiement_id > 0) + if (!$paiement_id > 0) { - $this->error=$paiement->error; - $this->errors=$paiement->errors; + $this->error = $paiement->error; + $this->errors = $paiement->errors; $error++; } } - if (! $error) + if (!$error) { // Add transaction into bank account - $bank_line_id=$paiement->addPaymentToBank($user, 'payment', '(SubscriptionPayment)', $accountid, $emetteur_nom, $emetteur_banque); - if (! ($bank_line_id > 0)) + $bank_line_id = $paiement->addPaymentToBank($user, 'payment', '(SubscriptionPayment)', $accountid, $emetteur_nom, $emetteur_banque); + if (!($bank_line_id > 0)) { - $this->error=$paiement->error; - $this->errors=$paiement->errors; + $this->error = $paiement->error; + $this->errors = $paiement->errors; $error++; } } - if (! $error && !empty($bank_line_id)) + if (!$error && !empty($bank_line_id)) { // Update fk_bank into subscription table $sql = 'UPDATE '.MAIN_DB_PREFIX.'subscription SET fk_bank='.$bank_line_id; - $sql.= ' WHERE rowid='.$subscriptionid; + $sql .= ' WHERE rowid='.$subscriptionid; $result = $this->db->query($sql); - if (! $result) + if (!$result) { $error++; } } - if (! $error) + if (!$error) { // Set invoice as paid $invoice->set_paid($user); } } - if (! $error) + if (!$error) { // Define output language $outputlangs = $langs; $newlang = ''; - $lang_id=GETPOST('lang_id'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($lang_id)) + $lang_id = GETPOST('lang_id'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($lang_id)) $newlang = $lang_id; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $customer->default_lang; - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -1825,10 +1881,10 @@ class Adherent extends CommonObject */ public function validate($user) { - global $langs,$conf; + global $langs, $conf; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); // Check parameters if ($this->statut == 1) @@ -1840,19 +1896,19 @@ class Adherent extends CommonObject $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " statut = 1"; - $sql.= ", datevalid = '".$this->db->idate($now)."'"; - $sql.= ", fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " statut = 1"; + $sql .= ", datevalid = '".$this->db->idate($now)."'"; + $sql .= ", fk_user_valid=".$user->id; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::validate", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $this->statut=1; + $this->statut = 1; // Call trigger - $result=$this->call_trigger('MEMBER_VALIDATE', $user); + $result = $this->call_trigger('MEMBER_VALIDATE', $user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers @@ -1863,7 +1919,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1878,9 +1934,9 @@ class Adherent extends CommonObject */ public function resiliate($user) { - global $langs,$conf; + global $langs, $conf; - $error=0; + $error = 0; // Check parameters if ($this->statut == 0) @@ -1892,17 +1948,17 @@ class Adherent extends CommonObject $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " statut = 0"; - $sql.= ", fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " statut = 0"; + $sql .= ", fk_user_valid=".$user->id; + $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); if ($result) { - $this->statut=0; + $this->statut = 0; // Call trigger - $result=$this->call_trigger('MEMBER_RESILIATE', $user); + $result = $this->call_trigger('MEMBER_RESILIATE', $user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers @@ -1911,7 +1967,7 @@ class Adherent extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1927,43 +1983,43 @@ class Adherent extends CommonObject public function add_to_abo() { // phpcs:enable - global $conf,$langs; + global $conf, $langs; include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; - $mailmanspip=new MailmanSpip($this->db); + $mailmanspip = new MailmanSpip($this->db); - $err=0; + $err = 0; // mailman - if (! empty($conf->global->ADHERENT_USE_MAILMAN) && ! empty($conf->mailmanspip->enabled)) + if (!empty($conf->global->ADHERENT_USE_MAILMAN) && !empty($conf->mailmanspip->enabled)) { - $result=$mailmanspip->add_to_mailman($this); + $result = $mailmanspip->add_to_mailman($this); if ($result < 0) { - if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; - $err+=1; + if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; + $err += 1; } foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) { $langs->load("errors"); - $this->errors[]=$langs->trans("ErrorFailedToAddToMailmanList", $tmpemail, $tmplist); + $this->errors[] = $langs->trans("ErrorFailedToAddToMailmanList", $tmpemail, $tmplist); } foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) { $langs->load("mailmanspip"); - $this->mesgs[]=$langs->trans("SuccessToAddToMailmanList", $tmpemail, $tmplist); + $this->mesgs[] = $langs->trans("SuccessToAddToMailmanList", $tmpemail, $tmplist); } } // spip - if (! empty($conf->global->ADHERENT_USE_SPIP) && ! empty($conf->mailmanspip->enabled)) + if (!empty($conf->global->ADHERENT_USE_SPIP) && !empty($conf->mailmanspip->enabled)) { - $result=$mailmanspip->add_to_spip($this); + $result = $mailmanspip->add_to_spip($this); if ($result < 0) { - $this->errors[]=$mailmanspip->error; - $err+=1; + $this->errors[] = $mailmanspip->error; + $err += 1; } } if ($err) @@ -1986,42 +2042,42 @@ class Adherent extends CommonObject public function del_to_abo() { // phpcs:enable - global $conf,$langs; + global $conf, $langs; include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; - $mailmanspip=new MailmanSpip($this->db); + $mailmanspip = new MailmanSpip($this->db); - $err=0; + $err = 0; // mailman - if (! empty($conf->global->ADHERENT_USE_MAILMAN)) + if (!empty($conf->global->ADHERENT_USE_MAILMAN)) { - $result=$mailmanspip->del_to_mailman($this); + $result = $mailmanspip->del_to_mailman($this); if ($result < 0) { - if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; - $err+=1; + if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; + $err += 1; } foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) { $langs->load("errors"); - $this->errors[]=$langs->trans("ErrorFailedToRemoveToMailmanList", $tmpemail, $tmplist); + $this->errors[] = $langs->trans("ErrorFailedToRemoveToMailmanList", $tmpemail, $tmplist); } foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) { $langs->load("mailmanspip"); - $this->mesgs[]=$langs->trans("SuccessToRemoveToMailmanList", $tmpemail, $tmplist); + $this->mesgs[] = $langs->trans("SuccessToRemoveToMailmanList", $tmpemail, $tmplist); } } - if ($conf->global->ADHERENT_USE_SPIP && ! empty($conf->mailmanspip->enabled)) + if ($conf->global->ADHERENT_USE_SPIP && !empty($conf->mailmanspip->enabled)) { - $result=$mailmanspip->del_to_spip($this); + $result = $mailmanspip->del_to_spip($this); if ($result < 0) { - $this->errors[]=$mailmanspip->error; - $err+=1; + $this->errors[] = $mailmanspip->error; + $err += 1; } } if ($err) @@ -2046,7 +2102,7 @@ class Adherent extends CommonObject global $langs; $langs->load("dict"); - $code=(empty($this->civility_id)?'':$this->civility_id); + $code = (empty($this->civility_id) ? '' : $this->civility_id); if (empty($code)) return ''; return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); } @@ -2067,27 +2123,27 @@ class Adherent extends CommonObject { global $conf, $langs; - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg=0; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg = 0; - $result=''; $label=''; - $linkstart=''; $linkend=''; + $result = ''; $label = ''; + $linkstart = ''; $linkend = ''; - if (! empty($this->photo)) + if (!empty($this->photo)) { - $label.= '
'; - $label.= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photowithmargin photologintooltip', 'small', 0, 1); - $label.= '
'; + $label .= '
'; + $label .= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photowithmargin photologintooltip', 'small', 0, 1); + $label .= '
'; } - $label.= '
'; - $label.= '' . $langs->trans("Member") . ''; - if (! empty($this->ref)) - $label.= '
' . $langs->trans('Ref') . ': ' . $this->ref; - if (! empty($this->firstname) || ! empty($this->lastname)) - $label.= '
' . $langs->trans('Name') . ': ' . $this->getFullName($langs); - if (! empty($this->company)) - $label.= '
' . $langs->trans('Company') . ': ' . $this->company; - $label.='
'; + $label .= '
'; + $label .= ''.$langs->trans("Member").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->firstname) || !empty($this->lastname)) + $label .= '
'.$langs->trans('Name').': '.$this->getFullName($langs); + if (!empty($this->company)) + $label .= '
'.$langs->trans('Company').': '.$this->company; + $label .= '
'; $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id; if ($option == 'subscription') @@ -2098,54 +2154,54 @@ class Adherent extends CommonObject if ($option != 'nolink') { // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($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.= '
global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $langs->load("users"); - $label=$langs->trans("ShowUser"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowUser"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.= ' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - $linkstart.=$linkclose.'>'; - $linkend=''; + $linkstart .= $linkclose.'>'; + $linkend = ''; - $result.=$linkstart; - if ($withpictoimg) $result.='
'; + $result .= $linkstart; + if ($withpictoimg) $result .= '
'; if ($withpictoimg) { - $paddafterimage=''; - if (abs($withpictoimg) == 1) $paddafterimage='style="margin-right: 3px;"'; + $paddafterimage = ''; + if (abs($withpictoimg) == 1) $paddafterimage = 'style="margin-right: 3px;"'; // Only picto - if ($withpictoimg > 0) $picto=''.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).''; + if ($withpictoimg > 0) $picto = ''.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).''; // Picto must be a photo else { - $picto=''; - $picto.=Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg==-3?'small':''), 'mini', 0, 1); - $picto.=''; + $picto = ''; + $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1); + $picto .= ''; } - $result.=$picto; + $result .= $picto; } if ($withpictoimg > -2 && $withpictoimg != 2) { - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.=''; - if ($mode == 'login') $result.=dol_trunc($this->login, $maxlen); - elseif ($mode == 'ref') $result.=$this->id; - else $result.=$this->getFullName($langs, '', ($mode == 'firstname' ? 2 : -1), $maxlen); - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.=''; + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= ''; + if ($mode == 'login') $result .= dol_trunc($this->login, $maxlen); + elseif ($mode == 'ref') $result .= $this->id; + else $result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : -1), $maxlen); + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= ''; } - if ($withpictoimg) $result.='
'; - $result.=$linkend; + if ($withpictoimg) $result .= '
'; + $result .= $linkend; return $result; } @@ -2194,7 +2250,7 @@ class Adherent extends CommonObject $labelStatus = $langs->trans("MemberStatusNoSubscription"); $labelStatusShort = $langs->trans("MemberStatusNoSubscriptionShort"); } - elseif (! $date_end_subscription) + elseif (!$date_end_subscription) { $statusType = 'status1'; $labelStatus = $langs->trans("MemberStatusActive"); @@ -2237,16 +2293,16 @@ class Adherent extends CommonObject $this->nb = array(); $sql = "SELECT count(a.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; - $sql.= " WHERE a.statut > 0"; - $sql.= " AND a.entity IN (".getEntity('adherent').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; + $sql .= " WHERE a.statut > 0"; + $sql .= " AND a.entity IN (".getEntity('adherent').")"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $this->nb["members"]=$obj->nb; + $this->nb["members"] = $obj->nb; } $this->db->free($resql); return 1; @@ -2254,7 +2310,7 @@ class Adherent extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2264,9 +2320,10 @@ class Adherent extends CommonObject * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Objet user + * @param string $mode "expired" for membership to renew, "shift" for member to validate * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - public function load_board($user) + public function load_board($user, $mode) { // phpcs:enable global $conf, $langs; @@ -2279,20 +2336,46 @@ class Adherent extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; $sql.= ", ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " WHERE a.fk_adherent_type = t.rowid"; - $sql.= " AND a.statut = 1"; - $sql.= " AND a.entity IN (".getEntity('adherent').")"; - $sql.= " AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND t.subscription = 1)"; + if ($mode == 'expired') + { + $sql.= " AND a.statut = 1"; + $sql.= " AND a.entity IN (".getEntity('adherent').")"; + $sql.= " AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND t.subscription = 1)"; + } + elseif ($mode == 'shift') + { + $sql.= " AND a.statut = -1"; + $sql.= " AND a.entity IN (".getEntity('adherent').")"; + } $resql=$this->db->query($sql); if ($resql) { $langs->load("members"); + $warning_delay = 0; + $url = ''; + $label = ''; + $labelShort = ''; + + if ($mode == 'expired') { + $warning_delay = $conf->adherent->subscription->warning_delay/60/60/24; + $label = $langs->trans("MembersWithSubscriptionToReceive"); + $labelShort = $langs->trans("MembersWithSubscriptionToReceiveShort"); + $url = DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=1&filter=outofdate'; + } + elseif ($mode == 'shift') { + $warning_delay = $conf->adherent->subscription->warning_delay/60/60/24; + $url = DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=-1'; + $label = $langs->trans("MembersListToValid"); + $labelShort = $langs->trans("ToValidate"); + } + $response = new WorkboardResponse(); - $response->warning_delay=$conf->adherent->subscription->warning_delay/60/60/24; - $response->label=$langs->trans("MembersWithSubscriptionToReceive"); - $response->labelShort=$langs->trans("MembersWithSubscriptionToReceiveShort"); - $response->url=DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=1&filter=outofdate'; + $response->warning_delay=$warning_delay; + $response->label=$label; + $response->labelShort=$labelShort; + $response->url=$url; $response->img=img_object('', "user"); $adherentstatic = new Adherent($this->db); @@ -2314,7 +2397,7 @@ class Adherent extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2333,16 +2416,16 @@ class Adherent extends CommonObject */ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) { - global $conf,$langs; + global $conf, $langs; $langs->load("orders"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'standard'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->ADHERENT_ADDON_PDF)) { + } elseif (!empty($conf->global->ADHERENT_ADDON_PDF)) { $modele = $conf->global->ADHERENT_ADDON_PDF; } } @@ -2362,17 +2445,17 @@ class Adherent extends CommonObject */ public function initAsSpecimen() { - global $user,$langs; + global $user, $langs; // Initialise parametres - $this->id=0; - $this->specimen=1; + $this->id = 0; + $this->specimen = 1; $this->civility_id = 0; $this->lastname = 'DOLIBARR'; $this->firstname = 'SPECIMEN'; - $this->gender='man'; - $this->login='dolibspec'; - $this->pass='dolibspec'; + $this->gender = 'man'; + $this->login = 'dolibspec'; + $this->pass = 'dolibspec'; $this->company = 'Societe ABC'; $this->address = '61 jump street'; $this->zip = '75000'; @@ -2391,28 +2474,28 @@ class Adherent extends CommonObject $this->phone = '0999999999'; $this->phone_perso = '0999999998'; $this->phone_mobile = '0999999997'; - $this->note_private='No comment'; - $this->birth=time(); - $this->photo=''; - $this->public=1; - $this->statut=0; + $this->note_private = 'No comment'; + $this->birth = time(); + $this->photo = ''; + $this->public = 1; + $this->statut = 0; - $this->datefin=time(); - $this->datevalid=time(); + $this->datefin = time(); + $this->datevalid = time(); - $this->typeid=1; // Id type adherent - $this->type='Type adherent'; // Libelle type adherent - $this->need_subscription=0; + $this->typeid = 1; // Id type adherent + $this->type = 'Type adherent'; // Libelle type adherent + $this->need_subscription = 0; - $this->first_subscription_date=time(); - $this->first_subscription_date_start=$this->first_subscription_date; - $this->first_subscription_date_end=dol_time_plus_duree($this->first_subscription_date_start, 1, 'y'); - $this->first_subscription_amount=10; + $this->first_subscription_date = time(); + $this->first_subscription_date_start = $this->first_subscription_date; + $this->first_subscription_date_end = dol_time_plus_duree($this->first_subscription_date_start, 1, 'y'); + $this->first_subscription_amount = 10; - $this->last_subscription_date=$this->first_subscription_date; - $this->last_subscription_date_start=$this->first_subscription_date; - $this->last_subscription_date_end=dol_time_plus_duree($this->last_subscription_date_start, 1, 'y'); - $this->last_subscription_amount=10; + $this->last_subscription_date = $this->first_subscription_date; + $this->last_subscription_date_start = $this->first_subscription_date; + $this->last_subscription_date_end = dol_time_plus_duree($this->last_subscription_date_start, 1, 'y'); + $this->last_subscription_amount = 10; } @@ -2431,10 +2514,10 @@ class Adherent extends CommonObject { // phpcs:enable global $conf; - $dn=''; - if ($mode==0) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; - if ($mode==1) $dn=$conf->global->LDAP_MEMBER_DN; - if ($mode==2) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; + $dn = ''; + if ($mode == 0) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; + if ($mode == 1) $dn = $conf->global->LDAP_MEMBER_DN; + if ($mode == 2) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; return $dn; } @@ -2449,15 +2532,15 @@ class Adherent extends CommonObject public function _load_ldap_info() { // phpcs:enable - global $conf,$langs; + global $conf, $langs; - $info=array(); - $keymodified=false; + $info = array(); + $keymodified = false; // Object classes - $info["objectclass"]=explode(',', $conf->global->LDAP_MEMBER_OBJECT_CLASS); + $info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_OBJECT_CLASS); - $this->fullname=$this->getFullName($langs); + $this->fullname = $this->getFullName($langs); // For avoid ldap error when firstname and lastname are empty if ($this->morphy == 'mor' && (empty($this->fullname) || $this->fullname == $this->company)) { @@ -2477,53 +2560,53 @@ class Adherent extends CommonObject // Member foreach ($ldapkey as $constname => $varname) { - if (! empty($this->$varname) && ! empty($conf->global->$constname)) + if (!empty($this->$varname) && !empty($conf->global->$constname)) { $info[$conf->global->$constname] = $this->$varname; // Check if it is the LDAP key and if its value has been changed - if (! empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) + if (!empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) { - if (! empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified=true; // For check if LDAP key has been modified + if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified = true; // For check if LDAP key has been modified } } } - if ($this->firstname && ! empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; - if ($this->poste && ! empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; - if ($this->company && ! empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company; - if ($this->address && ! empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; - if ($this->zip && ! empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; - if ($this->town && ! empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; - if ($this->country_code && ! empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; - if ($this->skype && ! empty($conf->global->LDAP_MEMBER_FIELD_SKYPE)) $info[$conf->global->LDAP_MEMBER_FIELD_SKYPE] = $this->skype; - if ($this->twitter && ! empty($conf->global->LDAP_MEMBER_FIELD_TWITTER)) $info[$conf->global->LDAP_MEMBER_FIELD_TWITTER] = $this->twitter; - if ($this->facebook && ! empty($conf->global->LDAP_MEMBER_FIELD_FACEBOOK)) $info[$conf->global->LDAP_MEMBER_FIELD_FACEBOOK] = $this->facebook; - if ($this->linkedin && ! empty($conf->global->LDAP_MEMBER_FIELD_LINKEDIN)) $info[$conf->global->LDAP_MEMBER_FIELD_LINKEDIN] = $this->linkedin; - if ($this->phone && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; - if ($this->phone_perso && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; - if ($this->phone_mobile && ! empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; - if ($this->fax && ! empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; - if ($this->note_private && ! empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); - if ($this->note_public && ! empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2); - if ($this->birth && ! empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap'); - if (isset($this->statut) && ! empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; - if ($this->datefin && ! empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap'); + if ($this->firstname && !empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; + if ($this->poste && !empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; + if ($this->company && !empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company; + if ($this->address && !empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; + if ($this->zip && !empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; + if ($this->town && !empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; + if ($this->country_code && !empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; + if ($this->skype && !empty($conf->global->LDAP_MEMBER_FIELD_SKYPE)) $info[$conf->global->LDAP_MEMBER_FIELD_SKYPE] = $this->skype; + if ($this->twitter && !empty($conf->global->LDAP_MEMBER_FIELD_TWITTER)) $info[$conf->global->LDAP_MEMBER_FIELD_TWITTER] = $this->twitter; + if ($this->facebook && !empty($conf->global->LDAP_MEMBER_FIELD_FACEBOOK)) $info[$conf->global->LDAP_MEMBER_FIELD_FACEBOOK] = $this->facebook; + if ($this->linkedin && !empty($conf->global->LDAP_MEMBER_FIELD_LINKEDIN)) $info[$conf->global->LDAP_MEMBER_FIELD_LINKEDIN] = $this->linkedin; + if ($this->phone && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; + if ($this->phone_perso && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; + if ($this->phone_mobile && !empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; + if ($this->fax && !empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; + if ($this->note_private && !empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); + if ($this->note_public && !empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2); + if ($this->birth && !empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap'); + if (isset($this->statut) && !empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; + if ($this->datefin && !empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap'); // When password is modified - if (! empty($this->pass)) + if (!empty($this->pass)) { - if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte - if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) } // Set LDAP password if possible elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password { - if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) + if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { // Just for the default MD5 ! if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) { - if ($this->pass_indatabase_crypted && ! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { + if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { // Create OpenLDAP MD5 password from Dolibarr MD5 password // Note: This suppose that "pass_indatabase_crypted" is a md5 (guaranted by the previous test if "(empty($conf->global->MAIN_SECURITY_HASH_ALGO))" $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = '{md5}'.base64_encode(hex2bin($this->pass_indatabase_crypted)); @@ -2531,18 +2614,18 @@ class Adherent extends CommonObject } } // Use $this->pass_indatabase value if exists - elseif (! empty($this->pass_indatabase)) + elseif (!empty($this->pass_indatabase)) { - if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte - if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption } } // Subscriptions - if ($this->first_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap'); - if (isset($this->first_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; - if ($this->last_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap'); - if (isset($this->last_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; + if ($this->first_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap'); + if (isset($this->first_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; + if ($this->last_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap'); + if (isset($this->last_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; return $info; } @@ -2557,14 +2640,14 @@ class Adherent extends CommonObject public function info($id) { $sql = 'SELECT a.rowid, a.datec as datec,'; - $sql.= ' a.datevalid as datev,'; - $sql.= ' a.tms as datem,'; - $sql.= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'adherent as a'; - $sql.= ' WHERE a.rowid = '.$id; + $sql .= ' a.datevalid as datev,'; + $sql .= ' a.tms as datem,'; + $sql .= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'adherent as a'; + $sql .= ' WHERE a.rowid = '.$id; dol_syslog(get_class($this)."::info", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -2575,7 +2658,7 @@ class Adherent extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) @@ -2613,22 +2696,22 @@ class Adherent extends CommonObject public function getNbOfEMailings() { $sql = "SELECT count(mc.email) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; - $sql.= " WHERE mc.email = '".$this->db->escape($this->email)."'"; - $sql.= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes + $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; + $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'"; + $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - $nb=$obj->nb; + $nb = $obj->nb; $this->db->free($resql); return $nb; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2651,7 +2734,7 @@ class Adherent extends CommonObject } // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $c = new Categorie($this->db); $existing = $c->containing($this->id, Categorie::TYPE_MEMBER, 'id'); @@ -2707,7 +2790,7 @@ class Adherent extends CommonObject //Only valid members if ($this->statut <= 0) return false; - if (! $this->datefin) return false; + if (!$this->datefin) return false; $now = dol_now(); @@ -2729,7 +2812,7 @@ class Adherent extends CommonObject $error = 0; $this->output = ''; - $this->error=''; + $this->error = ''; $blockingerrormsg = ''; @@ -2753,24 +2836,24 @@ class Adherent extends CommonObject $listofmembersok = array(); $listofmembersko = array(); - $arraydaysbeforeend=explode(';', $daysbeforeendlist); - foreach($arraydaysbeforeend as $daysbeforeend) // Loop on each delay + $arraydaysbeforeend = explode(';', $daysbeforeendlist); + foreach ($arraydaysbeforeend as $daysbeforeend) // Loop on each delay { dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG); - if (! is_numeric($daysbeforeend)) + if (!is_numeric($daysbeforeend)) { - $blockingerrormsg="Value for delta is not a positive or negative numeric"; + $blockingerrormsg = "Value for delta is not a positive or negative numeric"; $nbko++; break; } - $tmp=dol_getdate($now); + $tmp = dol_getdate($now); $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year']), $daysbeforeend, 'd'); $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'adherent'; - $sql.= " WHERE entity = ".$conf->entity; // Do not use getEntity('adherent').")" here, we want the batch to be on its entity only; - $sql.= " AND datefin = '".$this->db->idate($datetosearchfor)."'"; + $sql .= " WHERE entity = ".$conf->entity; // Do not use getEntity('adherent').")" here, we want the batch to be on its entity only; + $sql .= " AND datefin = '".$this->db->idate($datetosearchfor)."'"; $resql = $this->db->query($sql); if ($resql) @@ -2781,7 +2864,7 @@ class Adherent extends CommonObject $adherent = new Adherent($this->db); $formmail = new FormMail($this->db); - $i=0; + $i = 0; while ($i < $num_rows) { $obj = $this->db->fetch_object($resql); @@ -2791,7 +2874,7 @@ class Adherent extends CommonObject if (empty($adherent->email)) { $nbko++; - $listofmembersko[$adherent->id]=$adherent->id; + $listofmembersko[$adherent->id] = $adherent->id; } else { @@ -2807,14 +2890,14 @@ class Adherent extends CommonObject $outputlangs->loadLangs(array("main", "members")); dol_syslog("sendReminderForExpiredSubscription Language for member id ".$adherent->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang); - $arraydefaultmessage=null; + $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION; - if (! empty($labeltouse)) $arraydefaultmessage=$formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse); - if (! empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) + if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { - $substitutionarray=getCommonSubstitutionArray($outputlangs, 0, null, $adherent); + $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent); //if (is_array($adherent->thirdparty)) $substitutionarraycomp = ... complete_substitutions_array($substitutionarray, $outputlangs, $adherent); @@ -2824,42 +2907,42 @@ class Adherent extends CommonObject $to = $adherent->email; $trackid = 'mem'.$adherent->id; - $moreinheader='X-Dolibarr-Info: sendReminderForExpiredSubscription'."\r\n"; + $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredSubscription'."\r\n"; include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), '', '', 0, 1, '', '', $trackid, $moreinheader); $result = $cmail->sendfile(); - if (! $result) + if (!$result) { $error++; $this->error = $cmail->error; - if (! is_null($cmail->errors)) { + if (!is_null($cmail->errors)) { $this->errors += $cmail->errors; } $nbko++; - $listofmembersko[$adherent->id]=$adherent->id; + $listofmembersko[$adherent->id] = $adherent->id; } else { $nbok++; - $listofmembersok[$adherent->id]=$adherent->id; + $listofmembersok[$adherent->id] = $adherent->id; $message = $msg; $sendto = $to; $sendtocc = ''; $sendtobcc = ''; - $actioncode='EMAIL'; - $extraparams=''; + $actioncode = 'EMAIL'; + $extraparams = ''; - $actionmsg=''; - $actionmsg2=$langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from, 4, 0, 1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto, 4, 0, 1); + $actionmsg = ''; + $actionmsg2 = $langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from, 4, 0, 1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto, 4, 0, 1); if ($message) { - $actionmsg=$langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); - $actionmsg=dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . dol_escape_htmltag($sendtocc)); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc)); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $message); } @@ -2868,22 +2951,22 @@ class Adherent extends CommonObject // 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->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...) $actioncomm->code = 'AC_'.$actioncode; $actioncomm->label = $actionmsg2; - $actioncomm->note_private= $actionmsg; + $actioncomm->note_private = $actionmsg; $actioncomm->fk_project = 0; $actioncomm->datep = $now; $actioncomm->datef = $now; - $actioncomm->percentage = -1; // Not applicable + $actioncomm->percentage = -1; // Not applicable $actioncomm->socid = $adherent->thirdparty->id; $actioncomm->contactid = 0; - $actioncomm->authorid = $user->id; // User saving action - $actioncomm->userownerid = $user->id; // Owner of action + $actioncomm->authorid = $user->id; // User saving action + $actioncomm->userownerid = $user->id; // Owner of action // Fields when action is en email (content should be added into note) $actioncomm->email_msgid = $cmail->msgid; $actioncomm->email_from = $from; - $actioncomm->email_sender= ''; + $actioncomm->email_sender = ''; $actioncomm->email_to = $to; $actioncomm->email_tocc = $sendtocc; $actioncomm->email_tobcc = $sendtobcc; @@ -2900,10 +2983,10 @@ class Adherent extends CommonObject } else { - $blockingerrormsg="Can't find email template, defined into member module setup, to use for reminding"; + $blockingerrormsg = "Can't find email template, defined into member module setup, to use for reminding"; $nbko++; - $listofmembersko[$adherent->id]=$adherent->id; + $listofmembersko[$adherent->id] = $adherent->id; break; } @@ -2927,10 +3010,10 @@ class Adherent extends CommonObject else { $this->output = 'Found '.($nbok + $nbko).' members to send reminder to.'; - $this->output.= ' Send email successfuly to '.$nbok.' members'; + $this->output .= ' Send email successfuly to '.$nbok.' members'; if (is_array($listofmembersok)) { $listofids = ''; $i = 0; - foreach($listofmembersok as $idmember) { + foreach ($listofmembersok as $idmember) { if ($i > 100) { $listofids .= ', ...'; break; @@ -2944,10 +3027,10 @@ class Adherent extends CommonObject $this->output .= $listofids; } if ($nbko) { - $this->output.= ' - Canceled for '.$nbko.' member (no email or email sending error)'; + $this->output .= ' - Canceled for '.$nbko.' member (no email or email sending error)'; if (is_array($listofmembersko)) { $listofids = ''; $i = 0; - foreach($listofmembersko as $idmember) { + foreach ($listofmembersko as $idmember) { if ($i > 100) { $listofids .= ', ...'; break; diff --git a/htdocs/adherents/class/subscription.class.php b/htdocs/adherents/class/subscription.class.php index e2fc13edadf..99a0c113e9a 100644 --- a/htdocs/adherents/class/subscription.class.php +++ b/htdocs/adherents/class/subscription.class.php @@ -42,6 +42,11 @@ class Subscription extends CommonObject */ public $table_element='subscription'; + /** + * @var int Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by fk_soc, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 'fk_adherent@adherent'; + /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ @@ -88,6 +93,21 @@ class Subscription extends CommonObject */ public $fk_bank; + 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), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>20), + 'fk_adherent' =>array('type'=>'integer', 'label'=>'Member', 'enabled'=>1, 'visible'=>-1, 'position'=>25), + 'dateadh' =>array('type'=>'datetime', 'label'=>'DateSubscription', 'enabled'=>1, 'visible'=>-1, 'position'=>30), + 'datef' =>array('type'=>'date', 'label'=>'DateEndSubscription', 'enabled'=>1, 'visible'=>-1, 'position'=>35), + 'subscription' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'position'=>40, 'isameasure'=>1), + 'fk_bank' =>array('type'=>'integer', 'label'=>'BankId', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + 'note' =>array('type'=>'text', 'label'=>'Note', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'fk_type' =>array('type'=>'integer', 'label'=>'MemberType', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>60), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + ); + /** * Constructor diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 30ecafcf3e4..03dee569b84 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -531,7 +531,7 @@ if ($rowid > 0) { print ''.$langs->trans("Categories").''; print ''; - print $form->showCategories($object->id, 'member', 1); + print $form->showCategories($object->id, Categorie::TYPE_MEMBER, 1); print ''; } diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php index 11360ad4652..28594fdea40 100644 --- a/htdocs/adherents/type.php +++ b/htdocs/adherents/type.php @@ -65,7 +65,7 @@ $subscription = GETPOST("subscription", "int"); $duration_value = GETPOST('duration_value', 'int'); $duration_unit = GETPOST('duration_unit', 'alpha'); $vote = GETPOST("vote", "int"); -$comment = GETPOST("comment", 'alphanohtml'); +$comment = GETPOST("comment", 'none'); $mail_valid = GETPOST("mail_valid", 'none'); // Security check @@ -364,7 +364,9 @@ if ($action == 'create') print ''; print ''.$langs->trans("Description").''; - print ''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('comment', $object->note, '', 280, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, 15, '90%'); + $doleditor->Create(); print ''.$langs->trans("WelcomeEMail").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -807,10 +809,12 @@ if ($rowid > 0) print ''; print ''.$langs->trans("Description").''; - print ''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('comment', $object->note, '', 280, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, 15, '90%'); + $doleditor->Create(); + print ""; print ''.$langs->trans("WelcomeEMail").''; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('mail_valid', $object->mail_valid, '', 280, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, 15, '90%'); $doleditor->Create(); print ""; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index 0ea6a932fe7..5338010772f 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -235,7 +235,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/action/doc/"); + $dir = dol_buildpath($reldir."core/modules/action/doc"); if (is_dir($dir)) { @@ -257,7 +257,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print (empty($module->name) ? $name : $module->name); print "\n"; print "\n"; - require_once $dir.$file; + require_once $dir.'/'.$file; $module = new $classname($db, $specimenthirdparty); if (method_exists($module, 'info')) print $module->info($langs); diff --git a/htdocs/admin/agenda_xcal.php b/htdocs/admin/agenda_xcal.php index 3f6484ef639..7df74ba6a9d 100644 --- a/htdocs/admin/agenda_xcal.php +++ b/htdocs/admin/agenda_xcal.php @@ -178,6 +178,7 @@ $message .= $langs->trans("AgendaUrlOptionsNotAdmin", $user->login, $user->login $message .= $langs->trans("AgendaUrlOptions4", $user->login, $user->login).'
'; $message .= $langs->trans("AgendaUrlOptionsProject", $user->login, $user->login).'
'; $message .= $langs->trans("AgendaUrlOptionsNotAutoEvent", 'systemauto', 'systemauto').'
'; +$message .= $langs->trans("AgendaUrlOptionsIncludeHolidays", '1', '1').'
'; print info_admin($message); diff --git a/htdocs/admin/bom.php b/htdocs/admin/bom.php index 9a10c2f3886..6d37def3187 100644 --- a/htdocs/admin/bom.php +++ b/htdocs/admin/bom.php @@ -350,7 +350,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/bom".$valdir); + $realpath = $reldir."core/modules/bom".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -382,7 +383,6 @@ foreach ($dirmodels as $reldir) if ($modulequalified) { - $var = !$var; print ''; print (empty($module->name) ? $name : $module->name); print "\n"; @@ -425,7 +425,9 @@ foreach ($dirmodels as $reldir) { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $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("WatermarkOnDraftBOMs").': '.yn($module->option_draft_watermark, 1, 1); diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php index 2688b252d58..e8163c72f56 100644 --- a/htdocs/admin/commande.php +++ b/htdocs/admin/commande.php @@ -403,7 +403,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/commande".$valdir); + $realpath = $reldir."core/modules/commande".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -471,20 +472,22 @@ foreach ($dirmodels as $reldir) print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $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("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); - $htmltooltip.='
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); - //$htmltooltip.='
'.$langs->trans("Discounts").': '.yn($module->option_escompte,1,1); - //$htmltooltip.='
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note,1,1); - $htmltooltip.='
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + //$htmltooltip .= '
'.$langs->trans("Discounts").': '.yn($module->option_escompte,1,1); + //$htmltooltip .= '
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note,1,1); + $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); print ''; diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index df72e1bde04..b269e83fc80 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -181,6 +181,13 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha')) } } + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_FACEBOOK_URL", GETPOST("facebookurl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TWITTER_URL", GETPOST("twitterurl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_LINKEDIN_URL", GETPOST("linkedinurl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_INSTAGRAM_URL", GETPOST("instagramurl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_YOUTUBE_URL", GETPOST("youtubeurl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_GITHUB_URL", GETPOST("githuburl", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_MANAGERS", GETPOST("MAIN_INFO_SOCIETE_MANAGERS", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_GDPR", GETPOST("MAIN_INFO_GDPR", 'nohtml'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_INFO_CAPITAL", GETPOST("capital", 'nohtml'), 'chaine', 0, '', $conf->entity); @@ -407,32 +414,26 @@ print ''; print ''."\n"; // Name - print ''."\n"; - -// Addresse +print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' autofocus="autofocus"').'>'."\n"; +// Address print ''."\n"; - +print ''."\n"; print ''."\n"; - +print ''."\n"; print ''."\n"; +print ''."\n"; // Country - print ''."\n"; - print ''."\n"; - +// Currency print ''."\n"; - +// Phone print ''; print ''."\n"; - +// Fax print ''; print ''."\n"; - +// Email print ''; print ''."\n"; @@ -516,6 +517,45 @@ print ''; print '
'.$langs->trans("CompanyInfo").''.$langs->trans("Value").'
'; -print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' autofocus="autofocus"').'>
'; -print '
'; -print '
'; -print '
'; //if (empty($country_selected)) $country_selected=substr($langs->defaultlang,-2); // By default, country of localization print $form->select_country($mysoc->country_id, 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
'; $state_id = 0; if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) @@ -443,22 +444,22 @@ if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) $formcompany->select_departement($state_id, $mysoc->country_code, 'state_id'); print '
'; print $form->selectCurrency($conf->currency, "currency"); print '
'; print '
'; print '
'; print '
'; +// Social networks +print '
'; +print ''; +print ''; +print ''; +print "\n"; + +// Facebook +print ''; +print ''."\n"; + +// Twitter +print ''; +print ''."\n"; + +// LinkedIn +print ''; +print ''."\n"; + +// Instagram +print ''; +print ''."\n"; + +// Youtube +print ''; +print ''."\n"; + +// Github +print ''; +print ''."\n"; + +print "
'.$langs->trans("SocialNetworksInformation").''.$langs->trans("Value").'
'; +print '
'; +print '
'; +print '
'; +print '
'; +print '
'; +print '
"; + print '
'; // IDs of the company (country-specific) @@ -525,24 +565,20 @@ print ''.$langs->trans("CompanyId $langs->load("companies"); // Managing Director(s) - print ''; print ''; // GDPR contact - print ''; print $form->textwithpicto($langs->trans("GDPRContact"), $langs->trans("GDPRContactDesc")); print ''; print ''; // Capital - print ''; print ''; // Juridical Status - print ''; if ($mysoc->country_code) { print $formcompany->select_juridicalstatus($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE, $mysoc->country_code, '', 'forme_juridique_code'); @@ -551,7 +587,7 @@ if ($mysoc->country_code) { } print ''; -// ProfID1 +// ProfId1 if ($langs->transcountry("ProfId1", $mysoc->country_code) != '-') { print ''; @@ -641,14 +677,12 @@ if ($langs->transcountry("ProfId6", $mysoc->country_code) != '-') print ''; } -// TVA Intra - +// Intra-community VAT number print ''; print ''; print ''; // Object of the company - print ''; print ''; print ''; diff --git a/htdocs/admin/contract.php b/htdocs/admin/contract.php index 3c727fe1397..ae0c9c89b38 100644 --- a/htdocs/admin/contract.php +++ b/htdocs/admin/contract.php @@ -339,7 +339,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/contract".$valdir); + $realpath = $reldir."core/modules/contract".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -407,18 +408,20 @@ foreach ($dirmodels as $reldir) print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $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("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); - $htmltooltip.='
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); - $htmltooltip.='
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark, 1, 1); print ''; diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php index ac893c1d658..5b756c21017 100644 --- a/htdocs/admin/delais.php +++ b/htdocs/admin/delais.php @@ -107,6 +107,10 @@ $modules = array( array( 'code' => 'MAIN_DELAY_MEMBERS', 'img' => 'user' + ), + array( + 'code' => 'MAIN_DELAY_MEMBERS_SHIFT', + 'img' => 'user' ) ), 'expensereport' => array( diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 669e9e4f5a9..8d917088d51 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -36,13 +36,13 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'other', 'bills')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='invoice'; +$type = 'invoice'; /* @@ -53,22 +53,22 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconstinvoice=GETPOST('maskconstinvoice', 'alpha'); - $maskconstreplacement=GETPOST('maskconstreplacement', 'alpha'); - $maskconstcredit=GETPOST('maskconstcredit', 'alpha'); - $maskconstdeposit=GETPOST('maskconstdeposit', 'alpha'); - $maskinvoice=GETPOST('maskinvoice', 'alpha'); - $maskreplacement=GETPOST('maskreplacement', 'alpha'); - $maskcredit=GETPOST('maskcredit', 'alpha'); - $maskdeposit=GETPOST('maskdeposit', 'alpha'); + $maskconstinvoice = GETPOST('maskconstinvoice', 'alpha'); + $maskconstreplacement = GETPOST('maskconstreplacement', 'alpha'); + $maskconstcredit = GETPOST('maskconstcredit', 'alpha'); + $maskconstdeposit = GETPOST('maskconstdeposit', 'alpha'); + $maskinvoice = GETPOST('maskinvoice', 'alpha'); + $maskreplacement = GETPOST('maskreplacement', 'alpha'); + $maskcredit = GETPOST('maskcredit', 'alpha'); + $maskdeposit = GETPOST('maskdeposit', 'alpha'); if ($maskconstinvoice) $res = dolibarr_set_const($db, $maskconstinvoice, $maskinvoice, 'chaine', 0, '', $conf->entity); if ($maskconstreplacement) $res = dolibarr_set_const($db, $maskconstreplacement, $maskreplacement, 'chaine', 0, '', $conf->entity); if ($maskconstcredit) $res = dolibarr_set_const($db, $maskconstcredit, $maskcredit, 'chaine', 0, '', $conf->entity); if ($maskconstdeposit) $res = dolibarr_set_const($db, $maskconstdeposit, $maskdeposit, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -79,20 +79,20 @@ if ($action == 'updateMask') } elseif ($action == 'specimen') { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $facture = new Facture($db); $facture->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/facture/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/facture/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -167,9 +167,9 @@ elseif ($action == 'setribchq') $res = dolibarr_set_const($db, "FACTURE_RIB_NUMBER", $rib, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "FACTURE_CHQ_NUMBER", $chq, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -184,9 +184,9 @@ elseif ($action == 'set_FACTURE_DRAFT_WATERMARK') $res = dolibarr_set_const($db, "FACTURE_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -198,13 +198,13 @@ elseif ($action == 'set_FACTURE_DRAFT_WATERMARK') elseif ($action == 'set_INVOICE_FREE_TEXT') { - $freetext = GETPOST('INVOICE_FREE_TEXT', 'none'); // No alpha here, we want exact string + $freetext = GETPOST('INVOICE_FREE_TEXT', 'none'); // No alpha here, we want exact string $res = dolibarr_set_const($db, "INVOICE_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -219,9 +219,9 @@ elseif ($action == 'setforcedate') $res = dolibarr_set_const($db, "FAC_FORCE_DATE_VALIDATION", $forcedate, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -232,19 +232,19 @@ elseif ($action == 'setforcedate') } elseif ($action == 'setDefaultPDFModulesByType') { - $invoicetypemodels = GETPOST('invoicetypemodels'); + $invoicetypemodels = GETPOST('invoicetypemodels'); - if(!empty($invoicetypemodels) && is_array($invoicetypemodels)) + if (!empty($invoicetypemodels) && is_array($invoicetypemodels)) { $error = 0; foreach ($invoicetypemodels as $type => $value) { $res = dolibarr_set_const($db, 'FACTURE_ADDON_PDF_'.intval($type), $value, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; } - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -260,14 +260,14 @@ elseif ($action == 'setDefaultPDFModulesByType') * View */ -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", $langs->trans("BillsSetup"), 'EN:Invoice_Configuration|FR:Configuration_module_facture|ES:ConfiguracionFactura'); -$form=new Form($db); +$form = new Form($db); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("BillsSetup"), $linkback, 'title_setup'); $head = invoice_admin_prepare_head(); @@ -298,24 +298,24 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - if (! is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) + if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility - if (! is_file($dir.$filebis)) + if (!is_file($dir.$filebis)) { $filebis = $file."/".$file.".modules.php"; $classname = "mod_facture_".$file; } // Check if there is a filter on country preg_match('/\-(.*)_(.*)$/', $classname, $reg); - if (! empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; + if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue; $classname = preg_replace('/\-.*$/', '', $classname); - if (! class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis)-3, 3) == 'php') + if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php') { // Charging the numbering class require_once $dir.$filebis; @@ -323,7 +323,7 @@ foreach ($dirmodels as $reldir) $module = new $classname($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) @@ -338,9 +338,9 @@ foreach ($dirmodels as $reldir) // Show example of numbering module print ''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print ''."\n"; @@ -356,62 +356,62 @@ foreach ($dirmodels as $reldir) } print ''; - $facture=new Facture($db); + $facture = new Facture($db); $facture->initAsSpecimen(); // Example for standard invoice - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $facture->type=0; - $nextval=$module->getNextValue($mysoc, $facture); + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + $facture->type = 0; + $nextval = $module->getNextValue($mysoc, $facture); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=$langs->trans("NextValueForInvoices").': '; + $htmltooltip .= $langs->trans("NextValueForInvoices").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } // Example for remplacement - $facture->type=1; - $nextval=$module->getNextValue($mysoc, $facture); + $facture->type = 1; + $nextval = $module->getNextValue($mysoc, $facture); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=$langs->trans("NextValueForReplacements").': '; + $htmltooltip .= $langs->trans("NextValueForReplacements").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } // Example for credit invoice - $facture->type=2; - $nextval=$module->getNextValue($mysoc, $facture); + $facture->type = 2; + $nextval = $module->getNextValue($mysoc, $facture); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=$langs->trans("NextValueForCreditNotes").': '; + $htmltooltip .= $langs->trans("NextValueForCreditNotes").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } // Example for deposit invoice - $facture->type=3; - $nextval=$module->getNextValue($mysoc, $facture); + $facture->type = 3; + $nextval = $module->getNextValue($mysoc, $facture); if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval - $htmltooltip.=$langs->trans("NextValueForDeposit").': '; + $htmltooltip .= $langs->trans("NextValueForDeposit").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval; + $htmltooltip .= $nextval; } else { - $htmltooltip.=$langs->trans($module->error); + $htmltooltip .= $langs->trans($module->error); } } @@ -420,7 +420,7 @@ foreach ($dirmodels as $reldir) if ($conf->global->FACTURE_ADDON.'.php' == $file) // If module is the one used, we show existing errors { - if (! empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1); + if (!empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1); } print ''; @@ -445,17 +445,17 @@ print '
'; print load_fiche_titre($langs->trans("BillsPDFModules"), '', ''); // Load array def with activated templates -$type='invoice'; +$type = 'invoice'; $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -484,42 +484,43 @@ $activatedModels = array(); foreach ($dirmodels as $reldir) { - foreach (array('','/doc') as $valdir) + foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/facture".$valdir); + $realpath = $reldir."core/modules/facture".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $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 (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -554,20 +555,22 @@ foreach ($dirmodels as $reldir) print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $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("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); - $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); - $htmltooltip.='
'.$langs->trans("Discounts").': '.yn($module->option_escompte, 1, 1); - $htmltooltip.='
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note, 1, 1); - $htmltooltip.='
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); - $htmltooltip.='
'.$langs->trans("WatermarkOnDraftInvoices").': '.yn($module->option_draft_watermark, 1, 1); + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); + $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); + $htmltooltip .= '
'.$langs->trans("Discounts").': '.yn($module->option_escompte, 1, 1); + $htmltooltip .= '
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note, 1, 1); + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + $htmltooltip .= '
'.$langs->trans("WatermarkOnDraftInvoices").': '.yn($module->option_draft_watermark, 1, 1); print ''; @@ -597,7 +600,7 @@ foreach ($dirmodels as $reldir) } print ''; -if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf +if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf { /* * Document templates generators @@ -614,13 +617,13 @@ if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf print ''; print "\n"; - $listtype=array( + $listtype = array( Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), ); - if (! empty($conf->global->INVOICE_USE_SITUATION)) + if (!empty($conf->global->INVOICE_USE_SITUATION)) { $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); } @@ -628,7 +631,7 @@ if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf foreach ($listtype as $type => $trans) { $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type; - $current = !empty($conf->global->{$thisTypeConfName})?$conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF; + $current = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF; print ''; print ''.$trans.''; print ''.$form->selectarray('invoicetypemodels['.$type.']', ModelePDFFactures::liste_modeles($db), $current, 0, 0, 0).''; @@ -660,14 +663,14 @@ print "\n"; print ''; print "".$langs->trans("SuggestPaymentByRIBOnAccount").""; print ""; -if (! empty($conf->banque->enabled)) +if (!empty($conf->banque->enabled)) { $sql = "SELECT rowid, label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE clos = 0"; - $sql.= " AND courant = 1"; - $sql.= " AND entity IN (".getEntity('bank_account').")"; - $resql=$db->query($sql); + $sql .= " FROM ".MAIN_DB_PREFIX."bank_account"; + $sql .= " WHERE clos = 0"; + $sql .= " AND courant = 1"; + $sql .= " AND entity IN (".getEntity('bank_account').")"; + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -681,7 +684,7 @@ if (! empty($conf->banque->enabled)) $row = $db->fetch_row($resql); print ''; $i++; @@ -705,15 +708,15 @@ print "".$langs->trans("SuggestPaymentByChequeToAddress").""; print ""; print '\n"; print ''; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print '
'; print ''; print ''; print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='INVOICE_FREE_TEXT'; +$variablename = 'INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -777,7 +780,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index 149a1e0376d..055384c0084 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -409,7 +409,8 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/fichinter/doc/"); + $realpath = $reldir."core/modules/fichinter/doc"; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -480,6 +481,8 @@ foreach ($dirmodels as $reldir) $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); diff --git a/htdocs/admin/holiday.php b/htdocs/admin/holiday.php index 8cef5be5f26..aafe01bf5bd 100644 --- a/htdocs/admin/holiday.php +++ b/htdocs/admin/holiday.php @@ -355,7 +355,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/holiday".$valdir); + $realpath = $reldir."core/modules/holiday".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -429,7 +430,9 @@ foreach ($dirmodels as $reldir) { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index 44f13173669..3a9eed62fd0 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -83,7 +83,7 @@ if ($action == 'update') { dolibarr_set_const($db, "MAIN_LANG_DEFAULT", $_POST["MAIN_LANG_DEFAULT"], 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV+1, 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["MAIN_MULTILANGS"], 'chaine', 0, '', $conf->entity); + //dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["MAIN_MULTILANGS"], 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_THEME", $_POST["main_theme"], 'chaine', 0, '', $conf->entity); @@ -241,13 +241,15 @@ print ''; // Default language print ''.$langs->trans("DefaultLanguage").''; print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'MAIN_LANG_DEFAULT', 1, 0, 0, 0, 0, 'minwidth300', 2); +print ''; print ''; print ' '; print ''; // Multilingual GUI print ''.$langs->trans("EnableMultilangInterface").''; -print $form->selectyesno('MAIN_MULTILANGS', $conf->global->MAIN_MULTILANGS, 1); +//print $form->selectyesno('MAIN_MULTILANGS', $conf->global->MAIN_MULTILANGS, 1); +print ajax_constantonoff('MAIN_MULTILANGS'); print ''; print ' '; print ''; diff --git a/htdocs/admin/limits.php b/htdocs/admin/limits.php index e48f1b729f4..8bc356e18d9 100644 --- a/htdocs/admin/limits.php +++ b/htdocs/admin/limits.php @@ -1,6 +1,6 @@ - * Copyright (C) 2009-2012 Regis Houssin + * Copyright (C) 2009-2018 Regis Houssin * Copyright (C) 2010 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -32,31 +32,37 @@ $langs->loadLangs(array('companies', 'products', 'admin')); if (! $user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); +$currencycode = GETPOST('currencycode', 'alpha'); + +$mainmaxdecimalsunit = 'MAIN_MAX_DECIMALS_UNIT'.(! empty($currencycode)?'_'.$currencycode:''); +$mainmaxdecimalstot = 'MAIN_MAX_DECIMALS_TOT'.(! empty($currencycode)?'_'.$currencycode:''); +$mainmaxdecimalsshown = 'MAIN_MAX_DECIMALS_SHOWN'.(! empty($currencycode)?'_'.$currencycode:''); +$mainroundingruletot = 'MAIN_ROUNDING_RULE_TOT'.(! empty($currencycode)?'_'.$currencycode:''); if ($action == 'update') { - $error=0; - $MAXDEC=8; - if ($_POST["MAIN_MAX_DECIMALS_UNIT"] > $MAXDEC - || $_POST["MAIN_MAX_DECIMALS_TOT"] > $MAXDEC - || $_POST["MAIN_MAX_DECIMALS_SHOWN"] > $MAXDEC) + $error=0; + $MAXDEC=8; + if ($_POST[$mainmaxdecimalsunit] > $MAXDEC + || $_POST[$mainmaxdecimalstot] > $MAXDEC + || $_POST[$mainmaxdecimalsshown] > $MAXDEC) { $error++; setEventMessages($langs->trans("ErrorDecimalLargerThanAreForbidden", $MAXDEC), null, 'errors'); } - if ($_POST["MAIN_MAX_DECIMALS_UNIT"] < 0 - || $_POST["MAIN_MAX_DECIMALS_TOT"] < 0 - || $_POST["MAIN_MAX_DECIMALS_SHOWN"] < 0) + if ($_POST[$mainmaxdecimalsunit].(! empty($currencycode)?'_'.$currencycode:'') < 0 + || $_POST[$mainmaxdecimalstot] < 0 + || $_POST[$mainmaxdecimalsshown] < 0) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorNegativeValueNotAllowed"), null, 'errors'); } - if ($_POST["MAIN_ROUNDING_RULE_TOT"]) + if ($_POST[$mainroundingruletot]) { - if ($_POST["MAIN_ROUNDING_RULE_TOT"] * pow(10, $_POST["MAIN_MAX_DECIMALS_TOT"]) < 1) + if ($_POST[$mainroundingruletot] * pow(10, $_POST[$mainmaxdecimalstot]) < 1) { $langs->load("errors"); $error++; @@ -66,22 +72,21 @@ if ($action == 'update') if (! $error) { - dolibarr_set_const($db, "MAIN_MAX_DECIMALS_UNIT", $_POST["MAIN_MAX_DECIMALS_UNIT"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_MAX_DECIMALS_TOT", $_POST["MAIN_MAX_DECIMALS_TOT"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_MAX_DECIMALS_SHOWN", $_POST["MAIN_MAX_DECIMALS_SHOWN"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, $mainmaxdecimalsunit, $_POST[$mainmaxdecimalsunit], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, $mainmaxdecimalstot, $_POST[$mainmaxdecimalstot], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, $mainmaxdecimalsshown, $_POST[$mainmaxdecimalsshown], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_ROUNDING_RULE_TOT", $_POST["MAIN_ROUNDING_RULE_TOT"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, $mainroundingruletot, $_POST[$mainroundingruletot], 'chaine', 0, '', $conf->entity); - header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); + header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup".(! empty($currencycode)?'¤cycode='.$currencycode:'')); exit; } } - /* * View -*/ + */ $form=new Form($db); @@ -89,6 +94,31 @@ llxHeader(); print load_fiche_titre($langs->trans("LimitsSetup"), '', 'title_setup'); +$currencycode = (! empty($currencycode)?$currencycode:$conf->currency); +$aCurrencies = array($conf->currency); // Default currency always first position + +if (! empty($conf->multicurrency->enabled) && ! empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) +{ + require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php'; + + $sql = 'SELECT rowid, code FROM '.MAIN_DB_PREFIX.'multicurrency'; + $sql.= ' WHERE entity = '.$conf->entity; + $sql.= ' AND code != "'.$conf->currency.'"'; // Default currency always first position + $resql = $db->query($sql); + if ($resql) + { + while ($obj = $db->fetch_object($resql)) + { + $aCurrencies[] = $obj->code; + } + } + + if (! empty($aCurrencies) && count($aCurrencies) > 1) + { + $head = multicurrencyLimitPrepareHead($aCurrencies); + dol_fiche_head($head, $currencycode, '', -1, "multicurrency"); + } +} print ''.$langs->trans("LimitsDesc")."
\n"; print "
\n"; @@ -98,29 +128,29 @@ if ($action == 'edit') print ''; print ''; print ''; + if (! empty($conf->multicurrency->enabled) && ! empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) { + print ''; + } clearstatcache(); print ''; print ''; - print ''; + print ''; - - print ''; + print ''; + print ''; + print ''; - print ''; - - - print ''; + print ''; print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_UNIT"), $langs->trans("ParameterActiveForNextInputOnly")); - print '
'; + print '
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_TOT"), $langs->trans("ParameterActiveForNextInputOnly")); - print '
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").'
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").'
'; + print '
'; print $form->textwithpicto($langs->trans("MAIN_ROUNDING_RULE_TOT"), $langs->trans("ParameterActiveForNextInputOnly")); - print '
'; @@ -138,31 +168,35 @@ else print ''; print ''; - print ''; + print ''; - - print ''; + print ''; + print ''; + print ''; - print ''; - - - print ''; + print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_UNIT"), $langs->trans("ParameterActiveForNextInputOnly")); - print ''.$conf->global->MAIN_MAX_DECIMALS_UNIT.'
'.(isset($conf->global->$mainmaxdecimalsunit)?$conf->global->$mainmaxdecimalsunit:$conf->global->MAIN_MAX_DECIMALS_UNIT).'
'; + print '
'; print $form->textwithpicto($langs->trans("MAIN_MAX_DECIMALS_TOT"), $langs->trans("ParameterActiveForNextInputOnly")); - print ''.$conf->global->MAIN_MAX_DECIMALS_TOT.'
'.(isset($conf->global->$mainmaxdecimalstot)?$conf->global->$mainmaxdecimalstot:$conf->global->MAIN_MAX_DECIMALS_TOT).'
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").''.(isset($conf->global->$mainmaxdecimalsshown)?$conf->global->$mainmaxdecimalsshown:$conf->global->MAIN_MAX_DECIMALS_SHOWN).'
'.$langs->trans("MAIN_MAX_DECIMALS_SHOWN").''.$conf->global->MAIN_MAX_DECIMALS_SHOWN.'
'; + print '
'; print $form->textwithpicto($langs->trans("MAIN_ROUNDING_RULE_TOT"), $langs->trans("ParameterActiveForNextInputOnly")); - print ''.$conf->global->MAIN_ROUNDING_RULE_TOT.'
'.(isset($conf->global->$mainroundingruletot)?$conf->global->$mainroundingruletot:$conf->global->MAIN_ROUNDING_RULE_TOT).'
'; - print '
'; - print ''.$langs->trans("Modify").''; + print '
'; + print ''.$langs->trans("Modify").''; print '
'; } +if (! empty($conf->multicurrency->enabled) && ! empty($conf->global->MULTICURRENCY_USE_LIMIT_BY_CURRENCY)) +{ + if (! empty($aCurrencies) && count($aCurrencies) > 1) + { + dol_fiche_end(); + } +} if (empty($mysoc->country_code)) { @@ -197,7 +231,6 @@ else print " - ".$langs->trans("VAT").": ".$vat.'%'; print "   ->   ".$langs->trans("TotalPriceAfterRounding").": ".$tmparray[0].' / '.$tmparray[1].' / '.$tmparray[2]."
\n"; - // Add vat rates examples specific to country $vat_rates=array(); diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index 474c6020610..f74ee2fac7d 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -638,7 +638,7 @@ else $liste['user'] = $langs->trans('UserEmail'); $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? $langs->trans("NotDefined") : $conf->global->MAIN_INFO_SOCIETE_MAIL).')'; $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile'; - $sql.= ' WHERE active = 1 AND (private = 0 OR private = '.$user->id.')'; + $sql .= ' WHERE active = 1 AND (private = 0 OR private = '.$user->id.')'; $resql = $db->query($sql); if ($resql) { diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php index a0ebbc16e34..137d4129929 100644 --- a/htdocs/admin/mails_senderprofile_list.php +++ b/htdocs/admin/mails_senderprofile_list.php @@ -108,9 +108,9 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], - 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), + 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], - 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]) + 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]) ); } } @@ -451,7 +451,7 @@ foreach ($object->fields as $key => $val) elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } - elseif (! preg_match('/^(date|timestamp)/', $val['type'])) print ''; + elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; print ''; } } @@ -555,10 +555,10 @@ while ($i < ($limit ? min($num, $limit) : $num)) // Action column print ''; $url = $_SERVER["PHP_SELF"].'?action=list&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); + 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 '   '; print ''.img_delete().'   '; diff --git a/htdocs/admin/mrp.php b/htdocs/admin/mrp.php index 32af954f059..9c59b5cf6da 100644 --- a/htdocs/admin/mrp.php +++ b/htdocs/admin/mrp.php @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp.lib.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'errors', 'mrp', 'other')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); @@ -48,14 +48,14 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'updateMask') { - $maskconstmrp=GETPOST('maskconstMo', 'alpha'); - $maskmrp=GETPOST('maskMo', 'alpha'); + $maskconstmrp = GETPOST('maskconstMo', 'alpha'); + $maskmrp = GETPOST('maskMo', 'alpha'); if ($maskconstmrp) $res = dolibarr_set_const($db, $maskconstmrp, $maskmrp, 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -67,20 +67,20 @@ if ($action == 'updateMask') elseif ($action == 'specimen') { - $modele=GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $mo = new MO($db); $mrp->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $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; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -156,9 +156,9 @@ elseif ($action == 'set_MRP_MO_DRAFT_WATERMARK') $draft = GETPOST("MRP_MO_DRAFT_WATERMARK"); $res = dolibarr_set_const($db, "MRP_MO_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -170,13 +170,13 @@ elseif ($action == 'set_MRP_MO_DRAFT_WATERMARK') 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", 'none'); // 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 (!$res > 0) $error++; - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -191,13 +191,13 @@ elseif ($action == 'set_MRP_MO_FREE_TEXT') * View */ -$form=new Form($db); +$form = new Form($db); -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); llxHeader("", $langs->trans("MrpSetupPage")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("MrpSetupPage"), $linkback, 'title_setup'); $head = mrpAdminPrepareHead(); @@ -230,18 +230,18 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + 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); + $file = substr($file, 0, dol_strlen($file) - 4); require_once $dir.$file.'.php'; $module = new $file($db); // Show modules according to features level - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; if ($module->isEnabled()) @@ -252,9 +252,9 @@ foreach ($dirmodels as $reldir) // Show example of numbering model print ''; - $tmp=$module->getExample(); + $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; - elseif ($tmp=='NotConfigured') print $langs->trans($tmp); + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); else print $tmp; print ''."\n"; @@ -271,22 +271,22 @@ foreach ($dirmodels as $reldir) } print ''; - $mrp=new MO($db); + $mrp = new MO($db); $mrp->initAsSpecimen(); // Info - $htmltooltip=''; - $htmltooltip.=''.$langs->trans("Version").': '.$module->getVersion().'
'; - $mrp->type=0; - $nextval=$module->getNextValue($mysoc, $mrp); + $htmltooltip = ''; + $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").': '; + $htmltooltip .= ''.$langs->trans("NextValue").': '; if ($nextval) { - if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured') + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') $nextval = $langs->trans($nextval); - $htmltooltip.=$nextval.'
'; + $htmltooltip .= $nextval.'
'; } else { - $htmltooltip.=$langs->trans($module->error).'
'; + $htmltooltip .= $langs->trans($module->error).'
'; } } @@ -314,14 +314,14 @@ print load_fiche_titre($langs->trans("MOsModelModule"), '', ''); // Load array def with activated templates $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -349,43 +349,43 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - foreach (array('','/doc') as $valdir) + foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/mrp".$valdir); + $realpath = $reldir."core/modules/mrp".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $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) { - $var = !$var; print ''; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -420,15 +420,17 @@ foreach ($dirmodels as $reldir) print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $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("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $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("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); print ''; @@ -472,18 +474,18 @@ print ''.$langs->trans("Value").''; print " \n"; print "\n"; -$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); -$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); +$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); +$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); $htmltext = ''.$langs->trans("AvailableVariables").':
'; -foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; -$htmltext.='
'; +foreach ($substitutionarray as $key => $val) $htmltext .= $key.'
'; +$htmltext .= ''; print ''; print ''; print ''; print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnMOs"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; -$variablename='MRP_MO_FREE_TEXT'; +$variablename = 'MRP_MO_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { print ''; @@ -491,7 +493,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php index fb5ff1df202..88f973b8a20 100644 --- a/htdocs/admin/notification.php +++ b/htdocs/admin/notification.php @@ -53,6 +53,7 @@ if ($action == 'setvalue' && $user->admin) if (!$error && is_array($_POST)) { //var_dump($_POST); + $reg = array(); foreach ($_POST as $key => $val) { if (!preg_match('/^NOTIF_(.*)_key$/', $key, $reg)) continue; diff --git a/htdocs/admin/order_extrafields.php b/htdocs/admin/order_extrafields.php index eba9fd76ff6..2c72c55697f 100644 --- a/htdocs/admin/order_extrafields.php +++ b/htdocs/admin/order_extrafields.php @@ -41,13 +41,13 @@ $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); +$tmptype2label = ExtraFields::$type2label; +$type2label = array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action=GETPOST('action', 'alpha'); -$attrname=GETPOST('attrname', 'alpha'); -$elementtype='commande'; //Must be the $table_element of the class that manage extrafield +$action = GETPOST('action', 'alpha'); +$attrname = GETPOST('attrname', 'alpha'); +$elementtype = 'commande'; //Must be the $table_element of the class that manage extrafield if (!$user->admin) accessforbidden(); @@ -64,11 +64,11 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; * View */ -$textobject=$langs->transnoentitiesnoconv("Orders"); +$textobject = $langs->transnoentitiesnoconv("Orders"); llxHeader('', $langs->trans("OrdersSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("OrdersSetup"), $linkback, 'title_setup'); $head = order_admin_prepare_head(); @@ -108,7 +108,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && ! empty($attrname)) +if ($action == 'edit' && !empty($attrname)) { print "
"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/orderdet_extrafields.php b/htdocs/admin/orderdet_extrafields.php index 9204bbc251c..55732a40a51 100644 --- a/htdocs/admin/orderdet_extrafields.php +++ b/htdocs/admin/orderdet_extrafields.php @@ -42,13 +42,13 @@ $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); +$tmptype2label = ExtraFields::$type2label; +$type2label = array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); -$action=GETPOST('action', 'alpha'); -$attrname=GETPOST('attrname', 'alpha'); -$elementtype='commandedet'; //Must be the $table_element of the class that manage extrafield +$action = GETPOST('action', 'alpha'); +$attrname = GETPOST('attrname', 'alpha'); +$elementtype = 'commandedet'; //Must be the $table_element of the class that manage extrafield if (!$user->admin) accessforbidden(); @@ -65,11 +65,11 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; * View */ -$textobject=$langs->transnoentitiesnoconv("Orders"); +$textobject = $langs->transnoentitiesnoconv("Orders"); llxHeader('', $langs->trans("OrdersSetup")); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("OrdersSetup"), $linkback, 'title_setup'); $head = order_admin_prepare_head(); @@ -109,7 +109,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && ! empty($attrname)) +if ($action == 'edit' && !empty($attrname)) { print "
"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/admin/perms.php b/htdocs/admin/perms.php index 1f811c325dd..b11f909bd37 100644 --- a/htdocs/admin/perms.php +++ b/htdocs/admin/perms.php @@ -35,6 +35,8 @@ $action = GETPOST('action', 'aZ09'); if (!$user->admin) accessforbidden(); +$entity=$conf->entity; + /* * Actions @@ -70,14 +72,12 @@ print ''.$langs->trans("DefaultRightsDesc")." ".$lan $db->begin(); -// Charge les modules soumis a permissions +// Search all modules with permission and reload permissions def. $modules = array(); $modulesdir = dolGetModulesDirs(); foreach ($modulesdir as $dir) { - // Load modules attributes in arrays (name, numero, orders) from dir directory - //print $dir."\n
"; $handle = @opendir(dol_osencode($dir)); if (is_resource($handle)) { @@ -102,7 +102,7 @@ foreach ($modulesdir as $dir) // Load all permissions if ($objMod->rights_class) { - $ret = $objMod->insert_permissions(0); + $ret = $objMod->insert_permissions(0, $entity); $modules[$objMod->rights_class] = $objMod; //print "modules[".$objMod->rights_class."]=$objMod;"; } @@ -122,35 +122,58 @@ dol_fiche_head($head, 'default', $langs->trans("Security"), -1); // Show warning about external users print info_admin(showModulesExludedForExternal($modules)).'
'."\n"; +print "\n"; print '
'; print ''; -// Show permissions lines -$sql = "SELECT r.id, r.libelle, r.module, r.perms, r.subperms, r.bydefault"; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''."\n"; + +//print "xx".$conf->global->MAIN_USE_ADVANCED_PERMS; +$sql = "SELECT r.id, r.libelle as label, r.module, r.module_position, r.perms, r.subperms, r.bydefault"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r"; $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous" -$sql .= " AND entity = ".$conf->entity; +$sql .= " AND r.entity = ".$entity; if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled -$sql .= " ORDER BY r.module, r.id"; +$sql .= " ORDER BY r.family_position, r.module_position, r.module, r.id"; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; - $oldmod = ""; + $oldmod = ''; while ($i < $num) { $obj = $db->fetch_object($result); - // Si la ligne correspond a un module qui n'existe plus (absent de includes/module), on l'ignore - if (!$modules[$obj->module]) + // If line is for a module that doe snot existe anymore (absent of includes/module), we ignore it + if (empty($modules[$obj->module])) { $i++; continue; } + // Save field module_position in database if value is still zero + if (empty($obj->module_position)) + { + if (is_object($modules[$obj->module]) && ($modules[$obj->module]->module_position > 0)) + { + // TODO Define familyposition + $family = $modules[$obj->module]->family_position; + $familyposition = 0; + $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."rights_def SET module_position = ".$modules[$obj->module]->module_position.","; + $sqlupdate.= " family_position = ".$familyposition; + $sqlupdate.= " WHERE module_position = 0 AND module = '".$db->escape($obj->module)."'"; + $db->query($sqlupdate); + } + } + // Check if permission we found is inside a module definition. If not, we discard it. $found = false; foreach ($modules[$obj->module]->rights as $key => $val) @@ -169,49 +192,65 @@ if ($result) } // Break found, it's a new module to catch - if ($oldmod <> $obj->module) + if (isset($obj->module) && ($oldmod <> $obj->module)) { $oldmod = $obj->module; + + // Break detected, we get objMod $objMod = $modules[$obj->module]; $picto = ($objMod->picto ? $objMod->picto : 'generic'); - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + // Show break line + print ''; + print ''; + print ''; + print ''; + print ''; + print ''."\n"; } + $perm_libelle = ($conf->global->MAIN_USE_ADVANCED_PERMS && ($langs->trans("PermissionAdvanced".$obj->id) != ("PermissionAdvanced".$obj->id)) ? $langs->trans("PermissionAdvanced".$obj->id) : (($langs->trans("Permission".$obj->id) != ("Permission".$obj->id)) ? $langs->trans("Permission".$obj->id) : $obj->label)); print ''; - print ''; - $perm_libelle = ($conf->global->MAIN_USE_ADVANCED_PERMS && ($langs->trans("PermissionAdvanced".$obj->id) != ("PermissionAdvanced".$obj->id)) ? $langs->trans("PermissionAdvanced".$obj->id) : (($langs->trans("Permission".$obj->id) != ("Permission".$obj->id)) ? $langs->trans("Permission".$obj->id) : $obj->libelle)); + // Tick + if ($obj->bydefault == 1) + { + print ''; + print ''; + } + else + { + print ''; + print ''; + } + + // Permission and tick print ''; - print ''."\n"; - print ''; $i++; } } - +else dol_print_error($db); print '
'.$langs->trans("Module").' '.$langs->trans("Default").''.$langs->trans("Permissions").'
'.$langs->trans("Module").''.$langs->trans("Permission").''.$langs->trans("Default").' 
'; + print img_object('', $picto, 'class="pictoobjectwidth"').' '.$objMod->getName(); + print ''; + print '   
'; - print img_object('', $picto, 'class="pictoobjectwidth"').' '.$objMod->getName(); - print ' '; + + // Picto and label of module + print ''; + //print img_object('', $picto, 'class="pictoobjectwidth"').' '.$objMod->getName(); + //print ' '; print ''; + print ''.img_edit_remove().''; + print ''; + print img_picto($langs->trans("Active"), 'tick'); + print ''; + print ''.img_edit_add().''; + print ''; + print ' '; + print ''.$perm_libelle.''; - if ($obj->bydefault == 1) - { - print img_picto($langs->trans("Active"), 'tick'); - print ''; - print ''.img_edit_remove().''; - } - else - { - print ' '; - print ''; - print ''.img_edit_add().''; - } + print '
'; print '
'; diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index ee814ec46fb..781d7da5f6f 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -271,7 +271,7 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/propale/"); + $dir = dol_buildpath($reldir."core/modules/propale"); if (is_dir($dir)) { @@ -284,7 +284,7 @@ foreach ($dirmodels as $reldir) { $file = substr($file, 0, dol_strlen($file) - 4); - require_once $dir.$file.'.php'; + require_once $dir.'/'.$file.'.php'; $module = new $file; @@ -399,7 +399,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/propale".$valdir); + $realpath = $reldir."core/modules/propale".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -474,7 +475,9 @@ foreach ($dirmodels as $reldir) { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); diff --git a/htdocs/admin/reception_setup.php b/htdocs/admin/reception_setup.php index 6ee3eeb8f05..312038d3fcc 100644 --- a/htdocs/admin/reception_setup.php +++ b/htdocs/admin/reception_setup.php @@ -221,7 +221,7 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/reception/"); + $dir = dol_buildpath($reldir."core/modules/reception"); if (is_dir($dir)) { @@ -234,7 +234,7 @@ foreach ($dirmodels as $reldir) { $file = substr($file, 0, dol_strlen($file) - 4); - require_once $dir.$file.'.php'; + require_once $dir.'/'.$file.'.php'; $module = new $file; @@ -353,7 +353,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/reception".$valdir); + $realpath = $reldir."core/modules/reception".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -427,7 +428,9 @@ foreach ($dirmodels as $reldir) { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index f2fa67eba57..f1cbea504d3 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -461,6 +461,7 @@ print "\n"; print ''; +/* print '
'; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { @@ -471,7 +472,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print ''."\n"; // Example with a yes / no select - /*print ''; + print ''; print ''.$langs->trans("INVENTORY_DISABLE_VIRTUAL").''; print ''; if ($conf->use_javascript_ajax) { @@ -481,10 +482,10 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print $form->selectarray("INVENTORY_DISABLE_VIRTUAL", $arrval, $conf->global->INVENTORY_DISABLE_VIRTUAL); } print ''; - */ + // Example with a yes / no select - /*print ''; + print ''; print ''.$langs->trans("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA").''; print ''; if ($conf->use_javascript_ajax) { @@ -494,7 +495,7 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print $form->selectarray("INVENTORY_USE_MIN_PA_IF_NO_LAST_PA", $arrval, $conf->global->INVENTORY_USE_MIN_PA_IF_NO_LAST_PA); } print ''; - */ + // Example with a yes / no select print ''; @@ -507,8 +508,10 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) print $form->selectarray("INVENTORY_USE_INVENTORY_DATE_FOR_DATE_OF_MVT", $arrval, $conf->global->INVENTORY_USE_INVENTORY_DATE_FOR_DATE_OF_MVT); } print ''; + print ''; } +*/ /* I keep the option/feature, but hidden to end users for the moment. If feature is used by module, no need to have users see it. If not used by a module, I still need to understand in which case user may need this now we can set rule on product page. diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index bfbe5eb0f96..9a17916cb49 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -90,7 +90,7 @@ if ($action == 'specimen') // For invoices $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/supplier_invoice/pdf/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/supplier_invoice/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { $filefound = 1; @@ -230,7 +230,7 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_invoice/"); + $dir = dol_buildpath($reldir."core/modules/supplier_invoice"); if (is_dir($dir)) { @@ -243,7 +243,7 @@ foreach ($dirmodels as $reldir) { $file = substr($file, 0, dol_strlen($file) - 4); - require_once $dir.$file.'.php'; + require_once $dir.'/'.$file.'.php'; $module = new $file; @@ -360,7 +360,8 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_invoice/pdf/"); + $realpath = $reldir."core/modules/supplier_invoice/doc"; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -385,7 +386,7 @@ foreach ($dirmodels as $reldir) print (empty($module->name) ? $name : $module->name); print "\n"; print "\n"; - require_once $dir.$file; + require_once $dir.'/'.$file; $module = new $classname($db, $specimenthirdparty); if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -434,6 +435,8 @@ foreach ($dirmodels as $reldir) $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index 55c14a22e4d..15e1a452dff 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -86,7 +86,7 @@ elseif ($action == 'specimen') // For orders $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { - $file = dol_buildpath($reldir."core/modules/supplier_order/pdf/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/supplier_order/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { $filefound = 1; @@ -388,7 +388,8 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_order/pdf/"); + $realpath = $reldir."core/modules/supplier_order/doc"; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -411,7 +412,7 @@ foreach ($dirmodels as $reldir) print (empty($module->name) ? $name : $module->name); print "\n"; print "\n"; - require_once $dir.$file; + require_once $dir.'/'.$file; $module = new $classname($db, $specimenthirdparty); if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -456,6 +457,8 @@ foreach ($dirmodels as $reldir) $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); diff --git a/htdocs/admin/supplier_payment.php b/htdocs/admin/supplier_payment.php index 1f368eb2b50..d533ba0d8eb 100644 --- a/htdocs/admin/supplier_payment.php +++ b/htdocs/admin/supplier_payment.php @@ -332,7 +332,8 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_payment/doc/"); + $realpath = $reldir."core/modules/supplier_payment/doc"; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -356,7 +357,7 @@ foreach ($dirmodels as $reldir) print (empty($module->name) ? $name : $module->name); print "\n"; print "\n"; - require_once $dir.$file; + require_once $dir.'/'.$file; $module = new $classname($db, $specimenthirdparty); if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -405,6 +406,8 @@ foreach ($dirmodels as $reldir) $htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); print ''; diff --git a/htdocs/admin/supplier_proposal.php b/htdocs/admin/supplier_proposal.php index 6f297514999..c1007623a54 100644 --- a/htdocs/admin/supplier_proposal.php +++ b/htdocs/admin/supplier_proposal.php @@ -239,7 +239,7 @@ print ''."\n"; clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/supplier_proposal/"); + $dir = dol_buildpath($reldir."core/modules/supplier_proposal"); if (is_dir($dir)) { @@ -252,7 +252,7 @@ foreach ($dirmodels as $reldir) { $file = substr($file, 0, dol_strlen($file) - 4); - require_once $dir.$file.'.php'; + require_once $dir.'/'.$file.'.php'; $module = new $file; @@ -366,7 +366,8 @@ foreach ($dirmodels as $reldir) { foreach (array('', '/doc') as $valdir) { - $dir = dol_buildpath($reldir."core/modules/supplier_proposal".$valdir); + $realpath = $reldir."core/modules/supplier_proposal".$valdir; + $dir = dol_buildpath($realpath); if (is_dir($dir)) { @@ -440,7 +441,9 @@ foreach ($dirmodels as $reldir) { $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg, 1, 1); $htmltooltip .= '
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg, 1, 1); diff --git a/htdocs/admin/system/phpinfo.php b/htdocs/admin/system/phpinfo.php index bcc3aba20d4..09da33c071e 100644 --- a/htdocs/admin/system/phpinfo.php +++ b/htdocs/admin/system/phpinfo.php @@ -28,6 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("admin"); +$langs->load("install"); +$langs->load("errors"); if (! $user->admin) accessforbidden(); @@ -66,21 +68,123 @@ if ($maxphp > 0 && $maxphp2 > 0 && $maxphp > $maxphp2) print '
'; } - print ''; print ''; print "\n"; +$ErrorPicturePath = "../../theme/eldy/img/error.png"; +$WarningPicturePath = "../../theme/eldy/img/warning.png"; +$OkayPicturePath = "../../theme/eldy/img/tick.png"; -// Get PHP version -$phpversion=version_php(); -print '\n"; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("Version")."".$phpversion."
'.$langs->trans("Version").''; +$arrayphpminversionerror = array(5,5,0); +$arrayphpminversionwarning = array(5,5,0); +if (versioncompare(versionphparray(), $arrayphpminversionerror) < 0) +{ + print 'Error '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionerror)); +} +elseif (versioncompare(versionphparray(), $arrayphpminversionwarning) < 0) +{ + print 'Warning '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionwarning)); +} +else +{ + print 'Ok '.versiontostring(versionphparray()); +} + +print '
GET and POST support'; + +if (! isset($_GET["testget"]) && ! isset($_POST["testpost"]) && ! isset($_GET["mainmenu"])) +{ + print 'Warning '.$langs->trans("PHPSupportPOSTGETKo"); + print ' ('.$langs->trans("Recheck").')'; +} +else +{ + print 'Ok '.$langs->trans("PHPSupportPOSTGETOk"); +} + +print '
Sessions support'; + +if (! function_exists("session_id")) +{ + print 'Error '.$langs->trans("ErrorPHPDoesNotSupportSessions"); +} +else +{ + print 'Ok '.$langs->trans("PHPSupportSessions"); +} + +print '
GD support'; + +if (! function_exists("imagecreate")) +{ + print 'Warning '.$langs->trans("ErrorPHPDoesNotSupportGD"); +} +else +{ + print 'Ok '.$langs->trans("PHPSupportGD"); +} + +print '
Curl support'; + +if (! function_exists("curl_init")) +{ + print 'Warning '.$langs->trans("ErrorPHPDoesNotSupportCurl"); +} +else +{ + print 'Ok '.$langs->trans("PHPSupportCurl"); +} + +print '
UTF-8 support'; + +if (! function_exists("utf8_encode")) +{ + print 'Warning '.$langs->trans("ErrorPHPDoesNotSupportUTF8"); +} +else +{ + print 'Ok '.$langs->trans("PHPSupportUTF8"); +} + +print '
Intl support'; + +if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@localhost') +{ + if (! function_exists("locale_get_primary_language") || ! function_exists("locale_get_region")) + { + print 'Warning '.$langs->trans("ErrorPHPDoesNotSupportIntl"); + } + else + { + print 'Ok '.$langs->trans("PHPSupportIntl"); + } +} + +print '
Zip support'; + +if (!class_exists('ZipArchive')) +{ + print 'Warning '.$langs->trans("ErrorPHPDoesNotSupport", "Zip"); +} +else +{ + print 'Ok '.$langs->trans("PHPSupport", "Zip"); +} + +print '
'; + print '
'; - - // Get php_info array $phparray=phpinfo_array(); foreach($phparray as $key => $value) diff --git a/htdocs/admin/ticket.php b/htdocs/admin/ticket.php index 97d81a3e03c..dba1f827748 100644 --- a/htdocs/admin/ticket.php +++ b/htdocs/admin/ticket.php @@ -209,7 +209,7 @@ print "\n"; clearstatcache(); foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/ticket/"); + $dir = dol_buildpath($reldir."core/modules/ticket"); if (is_dir($dir)) { $handle = opendir($dir); @@ -219,7 +219,7 @@ foreach ($dirmodels as $reldir) { $file = $reg[1]; $classname = substr($file, 4); - include_once $dir.$file.'.php'; + include_once $dir.'/'.$file.'.php'; $module = new $file; diff --git a/htdocs/admin/tools/dolibarr_export.php b/htdocs/admin/tools/dolibarr_export.php index e5f6dae4852..854fd130bc5 100644 --- a/htdocs/admin/tools/dolibarr_export.php +++ b/htdocs/admin/tools/dolibarr_export.php @@ -29,18 +29,18 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $langs->load("admin"); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); -if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) $sortfield="date"; +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "date"; if (empty($page) || $page == -1) { $page = 0; } -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if (! $user->admin) +if (!$user->admin) accessforbidden(); @@ -52,33 +52,33 @@ if ($action == 'delete') { if (preg_match('/^backup\//', GETPOST('urlfile', 'alpha'))) { - $file=$conf->admin->dir_output.'/backup/'.basename(GETPOST('urlfile', 'alpha')); - $ret=dol_delete_file($file, 1); + $file = $conf->admin->dir_output.'/backup/'.basename(GETPOST('urlfile', 'alpha')); + $ret = dol_delete_file($file, 1); if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); } else { - $file=$conf->admin->dir_output.'/documents/'.basename(GETPOST('urlfile', 'alpha')); - $ret=dol_delete_file($file, 1); + $file = $conf->admin->dir_output.'/documents/'.basename(GETPOST('urlfile', 'alpha')); + $ret = dol_delete_file($file, 1); if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs'); else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors'); } - $action=''; + $action = ''; } /* * View */ -$form=new Form($db); +$form = new Form($db); $formfile = new FormFile($db); -$label=$db::LABEL; -$type=$db->type; +$label = $db::LABEL; +$type = $db->type; //var_dump($db); -$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad'; +$help_url = 'EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad'; llxHeader('', '', $help_url); print ''."\n"; } - + /** + * Output HTML string to total value + * + * @return string HTML string to total value + */ + public function total() + { + $value = 0; + foreach ($this->data as $valarray) // Loop on each x + { + $value += $valarray[1]; + } + return $value; + } /** * Output HTML string to show graph * - * @param int $shownographyet Show graph to say there is not enough data - * @return string HTML string to show graph + * @param int|string $shownographyet Show graph to say there is not enough data or the message in $shownographyet if it is a string. + * @return string HTML string to show graph */ public function show($shownographyet = 0) { @@ -1142,7 +1155,13 @@ class DolGraph if ($shownographyet) { $s = '
'; - $s .= '
'.$langs->trans("NotEnoughDataYet").'
'; + $s .= '
'; + if (is_numeric($shownographyet)) { + $s .= $langs->trans("NotEnoughDataYet"); + } else { + $s .= $shownographyet; + } + $s .= '
'; return $s; } diff --git a/htdocs/core/class/dolreceiptprinter.class.php b/htdocs/core/class/dolreceiptprinter.class.php index ba46419d39c..4738ea92974 100644 --- a/htdocs/core/class/dolreceiptprinter.class.php +++ b/htdocs/core/class/dolreceiptprinter.class.php @@ -30,7 +30,8 @@ * Use font A of printer * Use font B of printer * Use font C of printer - * Text Bold + * Text Bold + * Disable Text Bold * Text double height * Text double width * Underline text @@ -101,10 +102,11 @@ * */ -require_once DOL_DOCUMENT_ROOT .'/includes/mike42/escpos-php/autoload.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/mike42/escpos-php/autoload.php'; use Mike42\Escpos\PrintConnectors\FilePrintConnector; use Mike42\Escpos\PrintConnectors\NetworkPrintConnector; use Mike42\Escpos\PrintConnectors\WindowsPrintConnector; +use Mike42\Escpos\PrintConnectors\DummyPrintConnector; use Mike42\Escpos\CapabilityProfile; use Mike42\Escpos\Printer; use Mike42\Escpos\EscposImage; @@ -136,7 +138,7 @@ class dolReceiptPrinter extends Printer /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Error codes (or messages) @@ -150,7 +152,7 @@ class dolReceiptPrinter extends Printer */ public function __construct($db) { - $this->db=$db; + $this->db = $db; $this->tags = array( 'dol_line_feed', 'dol_line_feed_reverse', @@ -161,7 +163,7 @@ class dolReceiptPrinter extends Printer 'dol_use_font_b', 'dol_use_font_c', 'dol_bold', - '/dol_bold', + 'dol_bold_disabled', 'dol_double_height', '/dol_double_height', 'dol_double_width', @@ -250,8 +252,8 @@ class dolReceiptPrinter extends Printer $line = 0; $obj = array(); $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql.= ' WHERE entity = '.$conf->entity; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' WHERE entity = '.$conf->entity; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -318,8 +320,8 @@ class dolReceiptPrinter extends Printer $line = 0; $obj = array(); $sql = 'SELECT rowid, name, template'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql.= ' WHERE entity = '.$conf->entity; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' WHERE entity = '.$conf->entity; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -398,10 +400,10 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt'; - $sql.= ' (name, fk_type, fk_profile, parameter, entity)'; - $sql.= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')'; + $sql .= ' (name, fk_type, fk_profile, parameter, entity)'; + $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')'; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; $this->errors[] = $this->db->lasterror; } @@ -423,13 +425,13 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt'; - $sql.= ' SET name="'.$this->db->escape($name).'"'; - $sql.= ', fk_type='.$type; - $sql.= ', fk_profile='.$profile; - $sql.= ', parameter="'.$this->db->escape($parameter).'"'; - $sql.= ' WHERE rowid='.$printerid; + $sql .= ' SET name="'.$this->db->escape($name).'"'; + $sql .= ', fk_type='.$type; + $sql .= ', fk_profile='.$profile; + $sql .= ', parameter="'.$this->db->escape($parameter).'"'; + $sql .= ' WHERE rowid='.$printerid; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; $this->errors[] = $this->db->lasterror; } @@ -447,9 +449,9 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql.= ' WHERE rowid='.$printerid; + $sql .= ' WHERE rowid='.$printerid; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; $this->errors[] = $this->db->lasterror; } @@ -468,10 +470,10 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql.= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"'; - $sql.= ', "'.$this->db->escape($template).'", '.$conf->entity.')'; + $sql .= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"'; + $sql .= ', "'.$this->db->escape($template).'", '.$conf->entity.')'; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; $this->errors[] = $this->db->lasterror; } @@ -492,11 +494,11 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql.= ' SET name="'.$this->db->escape($name).'"'; - $sql.= ', template="'.$this->db->escape($template).'"'; - $sql.= ' WHERE rowid='.$templateid; + $sql .= ' SET name="'.$this->db->escape($name).'"'; + $sql .= ', template="'.$this->db->escape($template).'"'; + $sql .= ' WHERE rowid='.$templateid; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; $this->errors[] = $this->db->lasterror; } @@ -517,7 +519,7 @@ class dolReceiptPrinter extends Printer $img = EscposImage::load(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo_bw.png'); //$this->profile = CapabilityProfile::load("TM-T88IV"); $ret = $this->initPrinter($printerid); - if ($ret>0) { + if ($ret > 0) { setEventMessages($this->error, $this->errors, 'errors'); } else { try { @@ -529,7 +531,13 @@ class dolReceiptPrinter extends Printer $this->printer->text("Most simple example\n"); $this->printer->feed(); $this->printer->cut(); - //print '
'.print_r($this->connector, true).'
'; + + // If is DummyPrintConnector send to log to debugging + if ($this->printer->connector instanceof DummyPrintConnector) + { + $data = $this->printer->connector-> getData(); + dol_syslog($data); + } $this->printer->close(); } catch (Exception $e) { $this->errors[] = $e->getMessage(); @@ -602,11 +610,11 @@ class dolReceiptPrinter extends Printer $level = 0; $nbcharactbyline = 48; $ret = $this->initPrinter($printerid); - if ($ret>0) { + if ($ret > 0) { setEventMessages($this->error, $this->errors, 'errors'); } else { $nboflines = count($vals); - for ($tplline=0; $tplline < $nboflines; $tplline++) { + for ($tplline = 0; $tplline < $nboflines; $tplline++) { //var_dump($vals[$tplline]['value']); switch ($vals[$tplline]['tag']) { case 'DOL_PRINT_TEXT': @@ -615,7 +623,7 @@ class dolReceiptPrinter extends Printer case 'DOL_PRINT_OBJECT_LINES': foreach ($object->lines as $line) { //var_dump($line); - $spacestoadd = $nbcharactbyline - strlen($line->ref)- strlen($line->qty) - 10 - 1; + $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; $spaces = str_repeat(' ', $spacestoadd); $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n"); @@ -627,10 +635,10 @@ class dolReceiptPrinter extends Printer foreach ($object->lines as $line) { $vatarray[$line->tva_tx] += $line->total_tva; } - foreach($vatarray as $vatkey => $vatvalue) { - $spacestoadd = $nbcharactbyline - strlen($vatkey)- 12; + foreach ($vatarray as $vatkey => $vatvalue) { + $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12; $spaces = str_repeat(' ', $spacestoadd); - $this->printer->text($spaces. $vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n"); + $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n"); } break; case 'DOL_PRINT_OBJECT_TOTAL': @@ -679,11 +687,11 @@ class dolReceiptPrinter extends Printer } break; case 'DOL_PRINT_LOGO': - $img = EscposImage::load(DOL_DATA_ROOT .'/mycompany/logos/'.$mysoc->logo); + $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); $this->printer->graphics($img); break; case 'DOL_PRINT_LOGO_OLD': - $img = EscposImage::load(DOL_DATA_ROOT .'/mycompany/logos/'.$mysoc->logo); + $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo); $this->printer->bitImage($img); break; case 'DOL_PRINT_QRCODE': @@ -704,6 +712,12 @@ class dolReceiptPrinter extends Printer break; case 'DOL_USE_FONT_C': $this->printer->setFont(Printer::FONT_C); + break; + case 'DOL_BOLD': + $this->printer->setEmphasis(true); + break; + case 'DOL_BOLD_DISABLED': + $this->printer->setEmphasis(false); break; default: $this->printer->text($vals[$tplline]['tag']); @@ -713,9 +727,13 @@ class dolReceiptPrinter extends Printer break; } } - // Close and print - // uncomment next line to see content sent to printer - //print '
'.print_r($this->connector, true).'
'; + // If is DummyPrintConnector send to log to debugging + if ($this->printer->connector instanceof DummyPrintConnector) + { + $data = $this->printer->connector->getData(); + dol_syslog($data); + } + // Close and print $this->printer->close(); } return $error; @@ -732,9 +750,9 @@ class dolReceiptPrinter extends Printer global $conf; $error = 0; $sql = 'SELECT template'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; - $sql.= ' WHERE rowid='.$templateid; - $sql.= ' AND entity = '.$conf->entity; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template'; + $sql .= ' WHERE rowid='.$templateid; + $sql .= ' AND entity = '.$conf->entity; $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_array($resql); @@ -762,11 +780,11 @@ class dolReceiptPrinter extends Printer public function initPrinter($printerid) { global $conf; - $error=0; + $error = 0; $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; - $sql.= ' WHERE rowid = '.$printerid; - $sql.= ' AND entity = '.$conf->entity; + $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt'; + $sql .= ' WHERE rowid = '.$printerid; + $sql .= ' AND entity = '.$conf->entity; $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_array($resql); @@ -778,12 +796,11 @@ class dolReceiptPrinter extends Printer $error++; $this->errors[] = 'PrinterDontExist'; } - if (! $error) { + if (!$error) { $parameter = $obj['parameter']; try { switch ($obj['fk_type']) { case 1: - require_once DOL_DOCUMENT_ROOT .'/includes/mike42/escpos-php/src/DummyPrintConnector.php'; $this->connector = new DummyPrintConnector(); break; case 2: diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 36b83bb32b7..5d5540d77b8 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -208,7 +208,7 @@ class ExtraFields * * @param string $attrname Code of attribute * @param string $label label of attribute - * @param int $type Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...) + * @param string $type Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...) * @param int $pos Position of attribute * @param string $size Size/length definition of attribute ('5', '24,8', ...). For float, it contains 2 numeric separated with a comma. * @param string $elementtype Element type. Same value than object->table_element (Example 'member', 'product', 'thirdparty', ...) @@ -232,24 +232,25 @@ class ExtraFields if (empty($attrname)) return -1; if (empty($label)) return -1; - if ($elementtype == 'thirdparty') $elementtype='societe'; - if ($elementtype == 'contact') $elementtype='socpeople'; + if ($type == 'separate') { $unique = 0; $required = 0; } // Force unique and not required if this is a separator field to avoid troubles. + if ($elementtype == 'thirdparty') $elementtype = 'societe'; + if ($elementtype == 'contact') $elementtype = 'socpeople'; // Create field into database except for separator type which is not stored in database if ($type != 'separate') { - $result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help); + $result = $this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help); } - $err1=$this->errno; + $err1 = $this->errno; if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate') { // Add declaration of field into table - $result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable); - $err2=$this->errno; + $result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable); + $err2 = $this->errno; if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) { - $this->error=''; - $this->errno=0; + $this->error = ''; + $this->errno = 0; return 1; } else return -2; @@ -402,56 +403,56 @@ class ExtraFields } else { - $params=''; + $params = ''; } $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields("; - $sql.= " name,"; - $sql.= " label,"; - $sql.= " type,"; - $sql.= " pos,"; - $sql.= " size,"; - $sql.= " entity,"; - $sql.= " elementtype,"; - $sql.= " fieldunique,"; - $sql.= " fieldrequired,"; - $sql.= " param,"; - $sql.= " alwayseditable,"; - $sql.= " perms,"; - $sql.= " langs,"; - $sql.= " list,"; - $sql.= " fielddefault,"; - $sql.= " fieldcomputed,"; - $sql.= " fk_user_author,"; - $sql.= " fk_user_modif,"; - $sql.= " datec,"; - $sql.= " enabled,"; - $sql.= " help,"; - $sql.= " totalizable"; - $sql.= " )"; - $sql.= " VALUES('".$attrname."',"; - $sql.= " '".$this->db->escape($label)."',"; - $sql.= " '".$this->db->escape($type)."',"; - $sql.= " ".$pos.","; - $sql.= " '".$this->db->escape($size)."',"; - $sql.= " ".($entity===''?$conf->entity:$entity).","; - $sql.= " '".$this->db->escape($elementtype)."',"; - $sql.= " ".$unique.","; - $sql.= " ".$required.","; - $sql.= " '".$this->db->escape($params)."',"; - $sql.= " ".$alwayseditable.","; - $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; - $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").","; - $sql.= " '".$this->db->escape($list)."',"; - $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; - $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; - $sql .= " " . (is_object($user) ? $user->id : 0). ","; - $sql .= " " . (is_object($user) ? $user->id : 0). ","; - $sql .= "'" . $this->db->idate(dol_now()) . "',"; - $sql.= " ".($enabled?"'".$this->db->escape($enabled)."'":"1").","; - $sql.= " ".($help?"'".$this->db->escape($help)."'":"null").","; - $sql.= " ".($totalizable?'1':'0'); - $sql.=')'; + $sql .= " name,"; + $sql .= " label,"; + $sql .= " type,"; + $sql .= " pos,"; + $sql .= " size,"; + $sql .= " entity,"; + $sql .= " elementtype,"; + $sql .= " fieldunique,"; + $sql .= " fieldrequired,"; + $sql .= " param,"; + $sql .= " alwayseditable,"; + $sql .= " perms,"; + $sql .= " langs,"; + $sql .= " list,"; + $sql .= " fielddefault,"; + $sql .= " fieldcomputed,"; + $sql .= " fk_user_author,"; + $sql .= " fk_user_modif,"; + $sql .= " datec,"; + $sql .= " enabled,"; + $sql .= " help,"; + $sql .= " totalizable"; + $sql .= " )"; + $sql .= " VALUES('".$attrname."',"; + $sql .= " '".$this->db->escape($label)."',"; + $sql .= " '".$this->db->escape($type)."',"; + $sql .= " ".$pos.","; + $sql .= " '".$this->db->escape($size)."',"; + $sql .= " ".($entity === '' ? $conf->entity : $entity).","; + $sql .= " '".$this->db->escape($elementtype)."',"; + $sql .= " ".$unique.","; + $sql .= " ".$required.","; + $sql .= " '".$this->db->escape($params)."',"; + $sql .= " ".$alwayseditable.","; + $sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").","; + $sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").","; + $sql .= " '".$this->db->escape($list)."',"; + $sql .= " ".($default ? "'".$this->db->escape($default)."'" : "null").","; + $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; + $sql .= " ".(is_object($user) ? $user->id : 0).","; + $sql .= " ".(is_object($user) ? $user->id : 0).","; + $sql .= "'".$this->db->idate(dol_now())."',"; + $sql .= " ".($enabled ? "'".$this->db->escape($enabled)."'" : "1").","; + $sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null").","; + $sql .= " ".($totalizable ? '1' : '0'); + $sql .= ')'; dol_syslog(get_class($this)."::create_label", LOG_DEBUG); if ($this->db->query($sql)) @@ -896,55 +897,55 @@ class ExtraFields // We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label'] if ($tab->type != 'separate') { - $array_name_label[$tab->name]=$tab->label; + $array_name_label[$tab->name] = $tab->label; } // Old usage - $this->attribute_type[$tab->name]=$tab->type; - $this->attribute_label[$tab->name]=$tab->label; - $this->attribute_size[$tab->name]=$tab->size; - $this->attribute_elementtype[$tab->name]=$tab->elementtype; - $this->attribute_default[$tab->name]=$tab->fielddefault; - $this->attribute_computed[$tab->name]=$tab->fieldcomputed; - $this->attribute_unique[$tab->name]=$tab->fieldunique; - $this->attribute_required[$tab->name]=$tab->fieldrequired; - $this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : ''); - $this->attribute_pos[$tab->name]=$tab->pos; - $this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable; - $this->attribute_perms[$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms); - $this->attribute_langfile[$tab->name]=$tab->langs; - $this->attribute_list[$tab->name]=$tab->list; - $this->attribute_totalizable[$tab->name]=$tab->totalizable; - $this->attribute_entityid[$tab->name]=$tab->entity; + $this->attribute_type[$tab->name] = $tab->type; + $this->attribute_label[$tab->name] = $tab->label; + $this->attribute_size[$tab->name] = $tab->size; + $this->attribute_elementtype[$tab->name] = $tab->elementtype; + $this->attribute_default[$tab->name] = $tab->fielddefault; + $this->attribute_computed[$tab->name] = $tab->fieldcomputed; + $this->attribute_unique[$tab->name] = $tab->fieldunique; + $this->attribute_required[$tab->name] = $tab->fieldrequired; + $this->attribute_param[$tab->name] = ($tab->param ? unserialize($tab->param) : ''); + $this->attribute_pos[$tab->name] = $tab->pos; + $this->attribute_alwayseditable[$tab->name] = $tab->alwayseditable; + $this->attribute_perms[$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms); + $this->attribute_langfile[$tab->name] = $tab->langs; + $this->attribute_list[$tab->name] = $tab->list; + $this->attribute_totalizable[$tab->name] = $tab->totalizable; + $this->attribute_entityid[$tab->name] = $tab->entity; // New usage - $this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type; - $this->attributes[$tab->elementtype]['label'][$tab->name]=$tab->label; - $this->attributes[$tab->elementtype]['size'][$tab->name]=$tab->size; - $this->attributes[$tab->elementtype]['elementtype'][$tab->name]=$tab->elementtype; - $this->attributes[$tab->elementtype]['default'][$tab->name]=$tab->fielddefault; - $this->attributes[$tab->elementtype]['computed'][$tab->name]=$tab->fieldcomputed; - $this->attributes[$tab->elementtype]['unique'][$tab->name]=$tab->fieldunique; - $this->attributes[$tab->elementtype]['required'][$tab->name]=$tab->fieldrequired; - $this->attributes[$tab->elementtype]['param'][$tab->name]=($tab->param ? unserialize($tab->param) : ''); - $this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos; - $this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable; - $this->attributes[$tab->elementtype]['perms'][$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms); - $this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs; - $this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list; - $this->attributes[$tab->elementtype]['totalizable'][$tab->name]=$tab->totalizable; - $this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity; - $this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled; - $this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help; + $this->attributes[$tab->elementtype]['type'][$tab->name] = $tab->type; + $this->attributes[$tab->elementtype]['label'][$tab->name] = $tab->label; + $this->attributes[$tab->elementtype]['size'][$tab->name] = $tab->size; + $this->attributes[$tab->elementtype]['elementtype'][$tab->name] = $tab->elementtype; + $this->attributes[$tab->elementtype]['default'][$tab->name] = $tab->fielddefault; + $this->attributes[$tab->elementtype]['computed'][$tab->name] = $tab->fieldcomputed; + $this->attributes[$tab->elementtype]['unique'][$tab->name] = $tab->fieldunique; + $this->attributes[$tab->elementtype]['required'][$tab->name] = $tab->fieldrequired; + $this->attributes[$tab->elementtype]['param'][$tab->name] = ($tab->param ? unserialize($tab->param) : ''); + $this->attributes[$tab->elementtype]['pos'][$tab->name] = $tab->pos; + $this->attributes[$tab->elementtype]['alwayseditable'][$tab->name] = $tab->alwayseditable; + $this->attributes[$tab->elementtype]['perms'][$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms); + $this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs; + $this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list; + $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = $tab->totalizable; + $this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity; + $this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled; + $this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help; - $this->attributes[$tab->elementtype]['loaded']=1; + $this->attributes[$tab->elementtype]['loaded'] = 1; } } - if ($elementtype) $this->attributes[$elementtype]['loaded']=1; // If nothing found, we also save tag 'loaded' + if ($elementtype) $this->attributes[$elementtype]['loaded'] = 1; // If nothing found, we also save tag 'loaded' } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR); } @@ -1466,7 +1467,7 @@ class ExtraFields } // We have to join on extrafield table - if (strpos($InfoFieldList[4], 'extra') !== false) { + 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 { @@ -1594,60 +1595,60 @@ class ExtraFields */ public function showOutputField($key, $value, $moreparam = '', $extrafieldsobjectkey = '') { - global $conf,$langs; + global $conf, $langs; - if (! empty($extrafieldsobjectkey)) + if (!empty($extrafieldsobjectkey)) { - $label=$this->attributes[$extrafieldsobjectkey]['label'][$key]; - $type=$this->attributes[$extrafieldsobjectkey]['type'][$key]; - $size=$this->attributes[$extrafieldsobjectkey]['size'][$key]; - $default=$this->attributes[$extrafieldsobjectkey]['default'][$key]; - $computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key]; - $unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key]; - $required=$this->attributes[$extrafieldsobjectkey]['required'][$key]; - $param=$this->attributes[$extrafieldsobjectkey]['param'][$key]; - $perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1); - $langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key]; - $list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1); - $help=$this->attributes[$extrafieldsobjectkey]['help'][$key]; - $hidden=(empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + $label = $this->attributes[$extrafieldsobjectkey]['label'][$key]; + $type = $this->attributes[$extrafieldsobjectkey]['type'][$key]; + $size = $this->attributes[$extrafieldsobjectkey]['size'][$key]; + $default = $this->attributes[$extrafieldsobjectkey]['default'][$key]; + $computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key]; + $unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key]; + $required = $this->attributes[$extrafieldsobjectkey]['required'][$key]; + $param = $this->attributes[$extrafieldsobjectkey]['param'][$key]; + $perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1); + $langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key]; + $list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1); + $help = $this->attributes[$extrafieldsobjectkey]['help'][$key]; + $hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) } else // Old usage { //dol_syslog("Warning: parameter 'extrafieldsobjectkey' is missing", LOG_WARNING); - $label=$this->attribute_label[$key]; - $type=$this->attribute_type[$key]; - $size=$this->attribute_size[$key]; - $default=$this->attribute_default[$key]; - $computed=$this->attribute_computed[$key]; - $unique=$this->attribute_unique[$key]; - $required=$this->attribute_required[$key]; - $param=$this->attribute_param[$key]; - $perms=dol_eval($this->attribute_perms[$key], 1); - $langfile=$this->attribute_langfile[$key]; - $list=dol_eval($this->attribute_list[$key], 1); - $help=''; // Not supported with old syntax - $hidden=(empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + $label = $this->attribute_label[$key]; + $type = $this->attribute_type[$key]; + $size = $this->attribute_size[$key]; + $default = $this->attribute_default[$key]; + $computed = $this->attribute_computed[$key]; + $unique = $this->attribute_unique[$key]; + $required = $this->attribute_required[$key]; + $param = $this->attribute_param[$key]; + $perms = dol_eval($this->attribute_perms[$key], 1); + $langfile = $this->attribute_langfile[$key]; + $list = dol_eval($this->attribute_list[$key], 1); + $help = ''; // Not supported with old syntax + $hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) } - if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method. + if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method. //if ($computed) $value = // $value is already calculated into $value before calling this method - $showsize=0; + $showsize = 0; if ($type == 'date') { - $showsize=10; - $value=dol_print_date($value, 'day'); + $showsize = 10; + $value = dol_print_date($value, 'day'); } elseif ($type == 'datetime') { - $showsize=19; - $value=dol_print_date($value, 'dayhour'); + $showsize = 19; + $value = dol_print_date($value, 'dayhour'); } elseif ($type == 'int') { - $showsize=10; + $showsize = 10; } elseif ($type == 'double') { @@ -1802,20 +1803,20 @@ class ExtraFields $keyList .= implode(', ', $fields_label); } - $sql = 'SELECT ' . $keyList; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + $sql = 'SELECT '.$keyList; + $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0]; if (strpos($InfoFieldList[4], 'extra') !== false) { $sql .= ' as main'; } // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; // $sql.= ' AND entity = '.$conf->entity; - dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst', LOG_DEBUG); + dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $value = ''; // value was used, so now we reste it to use it to build final output - $toprint=array(); - while ( $obj = $this->db->fetch_object($resql) ) { + $toprint = array(); + while ($obj = $this->db->fetch_object($resql)) { // Several field into label (eq table:code|libelle:rowid) $fields_label = explode('|', $InfoFieldList[1]); if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { @@ -2068,35 +2069,35 @@ class ExtraFields { // Clean parameters // TODO GMT date in memory must be GMT so we should add gm=true in parameters - $value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]); + $value_key = dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]); } elseif (in_array($key_type, array('datetime'))) { // Clean parameters // TODO GMT date in memory must be GMT so we should add gm=true in parameters - $value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]); + $value_key = dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]); } - elseif (in_array($key_type, array('checkbox','chkbxlst'))) + elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) { - $value_arr=GETPOST("options_".$key, 'array'); // check if an array + $value_arr = GETPOST("options_".$key, 'array'); // check if an array if (!empty($value_arr)) { - $value_key=implode($value_arr, ','); - }else { - $value_key=''; + $value_key = implode($value_arr, ','); + } else { + $value_key = ''; } } - elseif (in_array($key_type, array('price','double'))) + elseif (in_array($key_type, array('price', 'double'))) { - $value_arr=GETPOST("options_".$key, 'alpha'); - $value_key=price2num($value_arr); + $value_arr = GETPOST("options_".$key, 'alpha'); + $value_key = price2num($value_arr); } else { - $value_key=GETPOST("options_".$key); + $value_key = GETPOST("options_".$key); if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = ''; } - $object->array_options["options_".$key]=$value_key; + $object->array_options["options_".$key] = $value_key; } if ($nofillrequired) { @@ -2149,13 +2150,13 @@ class ExtraFields if (in_array($key_type, array('date', 'datetime'))) { - if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)."year") continue; // Value was not provided, we should not set it. + if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)."year") continue; // Value was not provided, we should not set it. // Clean parameters $value_key = dol_mktime(GETPOST($keysuffix."options_".$key.$keyprefix."hour", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."min", 'int'), 0, GETPOST($keysuffix."options_".$key.$keyprefix."month", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."day", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."year", 'int')); } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) { - if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. + if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. $value_arr = GETPOST($keysuffix."options_".$key.$keyprefix); // Make sure we get an array even if there's only one checkbox $value_arr = (array) $value_arr; @@ -2163,13 +2164,13 @@ class ExtraFields } elseif (in_array($key_type, array('price', 'double', 'int'))) { - if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. + if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. $value_arr = GETPOST($keysuffix."options_".$key.$keyprefix); $value_key = price2num($value_arr); } else { - if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. + if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it. $value_key = GETPOST($keysuffix."options_".$key.$keyprefix); } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index cba66729d8c..b8ec41c7c16 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -690,18 +690,19 @@ class Form /** * Return combo list of activated countries, into language of user * - * @param string $selected Id or Code or Label of preselected country - * @param string $htmlname Name of html select object - * @param string $htmloption More html options on select object - * @param integer $maxlength Max length for labels (0=no limit) - * @param string $morecss More css class - * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key - * @param int $showempty Show empty choice - * @param int $disablefavorites 1=Disable favorites, - * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...) - * @return string HTML string with select + * @param string $selected Id or Code or Label of preselected country + * @param string $htmlname Name of html select object + * @param string $htmloption More html options on select object + * @param integer $maxlength Max length for labels (0=no limit) + * @param string $morecss More css class + * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key + * @param int $showempty Show empty choice + * @param int $disablefavorites 1=Disable favorites, + * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...) + * @param array $exclude_country_code Array of country code (iso2) to exclude + * @return string HTML string with select */ - public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0) + public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array()) { // phpcs:enable global $conf, $langs, $mysoc; @@ -733,6 +734,7 @@ class Form while ($i < $num) { $obj = $this->db->fetch_object($resql); + $countryArray[$i]['rowid'] = $obj->rowid; $countryArray[$i]['code_iso'] = $obj->code_iso; $countryArray[$i]['code_iso3'] = $obj->code_iso3; @@ -765,6 +767,7 @@ class Form { //if (empty($showempty) && empty($row['rowid'])) continue; if (empty($row['rowid'])) continue; + if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue; // exclude some countries if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++; if (empty($row['favorite']) && $atleastonefavorite) @@ -2640,7 +2643,7 @@ class Form $langs->load("stocks"); $tmpproduct = new Product($this->db); - $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after) + $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after) $tmpproduct->load_virtual_stock(); $virtualstock = $tmpproduct->stock_theorique; @@ -5913,7 +5916,7 @@ class Form //var_dump($objecttmp->filter); $prefixforautocompletemode = $objecttmp->element; if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company'; - if ($prefixforautocompletemode == 'product') $prefixforautocompletemode='produit'; + if ($prefixforautocompletemode == 'product') $prefixforautocompletemode = 'produit'; $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG); @@ -6034,16 +6037,23 @@ class Form // Search data $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t"; - if ($objecttmp->ismultientitymanaged == 2) + if (isset($objecttmp->ismultientitymanaged) && ! is_numeric($objecttmp->ismultientitymanaged)) { + $tmparray = explode('@', $objecttmp->ismultientitymanaged); + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON parenttable.rowid = t.'.$tmparray[0]; + } + if ($objecttmp->ismultientitymanaged == 'fk_soc@societe') if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE 1=1"; - if (!empty($objecttmp->ismultientitymanaged)) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")"; + if (isset($objecttmp->ismultientitymanaged) && $objecttmp->ismultientitymanaged == 1) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")"; + if (isset($objecttmp->ismultientitymanaged) && ! is_numeric($objecttmp->ismultientitymanaged)) { + $sql .= ' AND parenttable.entity = t.'.$tmparray[0]; + } if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) { if ($objecttmp->element == 'societe') $sql .= " AND t.rowid = ".$user->socid; else $sql .= " AND t.fk_soc = ".$user->socid; } if ($searchkey != '') $sql .= natural_search(explode(',', $fieldstoshow), $searchkey); - if ($objecttmp->ismultientitymanaged == 2) { + if ($objecttmp->ismultientitymanaged == 'fk_soc@societe') { if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" @@ -6239,7 +6249,7 @@ class Form if (is_array($id)) { if (in_array($key, $id) && !$disabled) $out .= ' selected'; // To preselect a value } else { - $id = (string) $id; // if $id = 0, then $id = '0' + $id = (string) $id; // if $id = 0, then $id = '0' if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value } if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"'; @@ -6494,7 +6504,7 @@ class Form * @param int $translate Translate and encode value * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95% * @param string $moreattrib Add more options on select component. Example: 'disabled' - * @param string $elemtype Type of element we show ('category', ...) + * @param string $elemtype Type of element we show ('category', ...). Will execute a formating function on it. To use in readonly mode if js component support HTML formatting. * @param string $placeholder String to use as placeholder * @param int $addjscombo Add js combo * @return string HTML multiselect string @@ -6549,7 +6559,7 @@ class Form templateResult: formatResult, /* For 4.0 */ // Specify format function for selected item formatSelection: formatSelection, - templateResult: formatSelection /* For 4.0 */ + templateSelection: formatSelection /* For 4.0 */ }); });'."\n"; } @@ -7294,14 +7304,23 @@ class Form { $ret .= ''; } - elseif ($fieldref != 'none') $ret .= dol_htmlentities($object->$fieldref); - + elseif ($fieldref != 'none') + { + $ret.=dol_htmlentities($object->$fieldref); + } if ($morehtmlref) { - $ret .= ' '.$morehtmlref; + // don't add a additional space, when "$morehtmlref" starts with a HTML div tag + if(substr($morehtmlref, 0, 4) != 'global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true; + + if (empty($projectsListId)) + { + if (empty($usertofilter->rights->projet->all->lire)) + { + $projectstatic = new Project($this->db); + $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1); + } + } + + // Search all projects + $sql = 'SELECT f.rowid, f.ref as fref, "nolabel" as flabel, p.rowid as pid, f.ref, + p.title, p.fk_soc, p.fk_statut, p.public,'; + $sql .= ' s.nom as name'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,'; + $sql .= ' '.MAIN_DB_PREFIX.'facture as f'; + $sql .= " WHERE p.entity IN (".getEntity('project').")"; + $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement + //if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")"; + //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)"; + //if ($socid > 0) $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)"; + $sql .= " GROUP BY f.ref ORDER BY p.ref, f.ref ASC"; + + $resql = $this->db->query($sql); + if ($resql) + { + // Use select2 selector + if (!empty($conf->use_javascript_ajax)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus); + $out .= $comboenhancement; + $morecss = 'minwidth200imp maxwidth500'; + } + + if (empty($option_only)) { + $out .= ''; + } + + print $out; + + $this->db->free($resql); + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Output the component to make advanced search criteries + * + * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...) + * @param array $search_component_params Array of selected search criterias + * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list. + * @return string HTML component for advanced search + */ + public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array()) + { + global $conf, $langs; + + $ret = ''; + + $ret .= '
'; + //$ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= $langs->trans("Filters"); + $ret .= ''; + //$ret .= ''; + $ret .= '
'; + $ret .= ''; + $ret .= '
'; + foreach($arrayofcriterias as $criterias) { + foreach($criterias as $criteriafamilykey => $criteriafamilyval) { + if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) continue; + if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) continue; + if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) { + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + $ret .= ''; + } + else { + $ret .= ''; + } + } + } + $ret .= '
'; + + + return $ret; + } } diff --git a/htdocs/core/class/html.formaccounting.class.php b/htdocs/core/class/html.formaccounting.class.php index 0909df72417..64e027db537 100644 --- a/htdocs/core/class/html.formaccounting.class.php +++ b/htdocs/core/class/html.formaccounting.class.php @@ -3,7 +3,7 @@ * Copyright (C) 2013-2014 Olivier Geffroy * Copyright (C) 2015 Ari Elbaz (elarifr) * Copyright (C) 2016 Marcos García - * Copyright (C) 2016-2017 Alexandre Spangaro + * Copyright (C) 2016-2020 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -292,7 +292,7 @@ class FormAccounting extends Form { $trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT) ? 50 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT; - $sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version"; + $sql = "SELECT DISTINCT aa.account_number, aa.label, aa.labelshort, aa.rowid, aa.fk_pcg_version"; $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 asy.rowid = ".$conf->global->CHARTOFACCOUNTS; @@ -309,11 +309,20 @@ class FormAccounting extends Form return -1; } - $selected = $selectid; // selectid can be -1, 0, 123 + $selected = $selectid; // selectid can be -1, 0, 123 while ($obj = $this->db->fetch_object($resql)) { - $label = length_accountg($obj->account_number).' - '.$obj->label; - $label = dol_trunc($label, $trunclength); + if (empty($obj->labelshort)) + { + $labeltoshow = $obj->label; + } + else + { + $labeltoshow = $obj->labelshort; + } + + $label = length_accountg($obj->account_number).' - '.$labeltoshow; + $label = dol_trunc($label, $trunclength); $select_value_in = $obj->rowid; $select_value_out = $obj->rowid; @@ -450,7 +459,7 @@ class FormAccounting extends Form $sql = "SELECT DISTINCT date_format(doc_date, '%Y') as dtyear"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping"; - $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")"; + $sql .= " WHERE entity IN (".getEntity('accountancy').")"; $sql .= " ORDER BY date_format(doc_date, '%Y')"; dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index a73621faa32..c379d1912d1 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -73,7 +73,7 @@ class FormOther // phpcs:enable global $conf, $langs, $user; - $sql = "SELECT rowid, label, fk_user"; + $sql = "SELECT rowid, label, fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; $sql .= " WHERE type = '".$this->db->escape($type)."'"; if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model diff --git a/htdocs/core/class/html.formticket.class.php b/htdocs/core/class/html.formticket.class.php index d99a6c091cc..ecf137adb04 100644 --- a/htdocs/core/class/html.formticket.class.php +++ b/htdocs/core/class/html.formticket.class.php @@ -919,7 +919,7 @@ class FormTicket print ''.$langs->trans('Subject').''; $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE; - print ''; + print 'ref.'] '.$langs->trans('TicketNewMessage').'" />'; print ''; // Destinataires @@ -935,13 +935,13 @@ class FormTicket if (is_array($contacts) && count($contacts) > 0) { foreach ($contacts as $key => $info_sendto) { if ($info_sendto['email'] != '') { - $sendto[] = dol_escape_htmltag(trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">")." (".dol_escape_htmltag($info_sendto['libelle']).")"; + $sendto[] = dol_escape_htmltag(trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">").' ('.dol_escape_htmltag($info_sendto['libelle']).")"; } } } if ($ticketstat->origin_email && !in_array($this->dao->origin_email, $sendto)) { - $sendto[] = dol_escape_htmltag($ticketstat->origin_email)." (".$langs->trans("TicketEmailOriginIssuer").")"; + $sendto[] = dol_escape_htmltag($ticketstat->origin_email).' ('.$langs->trans("TicketEmailOriginIssuer").")"; } if ($ticketstat->fk_soc > 0) { @@ -949,12 +949,12 @@ class FormTicket $ticketstat->fetch_thirdparty(); if (is_array($ticketstat->thirdparty->email) && !in_array($ticketstat->thirdparty->email, $sendto)) { - $sendto[] = $ticketstat->thirdparty->email.' ('.$langs->trans('Customer').')'; + $sendto[] = $ticketstat->thirdparty->email.' ('.$langs->trans('Customer').')'; } } if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS) { - $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO.' (generic email)'; + $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO.' (generic email)'; } // Print recipient list diff --git a/htdocs/core/class/smtps.class.php b/htdocs/core/class/smtps.class.php index f80d2f1547a..39c7d3ba778 100644 --- a/htdocs/core/class/smtps.class.php +++ b/htdocs/core/class/smtps.class.php @@ -117,10 +117,10 @@ class SMTPs /** * Message Sensitivity */ - private $_arySensitivity = array ( false, + private $_arySensitivity = array(false, 'Personal', 'Private', - 'Company Confidential' ); + 'Company Confidential'); /** * Message Sensitivity @@ -131,12 +131,12 @@ class SMTPs /** * Message Priority */ - private $_aryPriority = array ( 'Bulk', + private $_aryPriority = array('Bulk', 'Highest', 'High', 'Normal', 'Low', - 'Lowest' ); + 'Lowest'); /** * Content-Transfer-Encoding @@ -147,13 +147,13 @@ class SMTPs /** * Content-Transfer-Encoding */ - private $_smtpsTransEncodeTypes = array( '7bit', // Simple 7-bit ASCII - '8bit', // 8-bit coding with line termination characters - 'base64', // 3 octets encoded into 4 sextets with offset - 'binary', // Arbitrary binary stream - 'mac-binhex40', // Macintosh binary to hex encoding - 'quoted-printable', // Mostly 7-bit, with 8-bit characters encoded as "=HH" - 'uuencode' ); // UUENCODE encoding + private $_smtpsTransEncodeTypes = array('7bit', // Simple 7-bit ASCII + '8bit', // 8-bit coding with line termination characters + 'base64', // 3 octets encoded into 4 sextets with offset + 'binary', // Arbitrary binary stream + 'mac-binhex40', // Macintosh binary to hex encoding + 'quoted-printable', // Mostly 7-bit, with 8-bit characters encoded as "=HH" + 'uuencode'); // UUENCODE encoding /** * Content-Transfer-Encoding @@ -300,7 +300,7 @@ class SMTPs */ public function setErrorsTo($_strErrorsTo) { - if ( $_strErrorsTo ) + if ($_strErrorsTo) $this->_errorsTo = $this->_strip_email($_strErrorsTo); } @@ -314,7 +314,7 @@ class SMTPs { $_retValue = ''; - if ( $_part === true ) + if ($_part === true) $_retValue = $this->_errorsTo; else $_retValue = $this->_errorsTo[$_part]; @@ -359,29 +359,29 @@ class SMTPs // We have to make sure the HOST given is valid // This is done here because '@fsockopen' will not give me this // information if it failes to connect because it can't find the HOST - $host=$this->getHost(); + $host = $this->getHost(); $usetls = preg_match('@tls://@i', $host); - $host=preg_replace('@tcp://@i', '', $host); // Remove prefix - $host=preg_replace('@ssl://@i', '', $host); // Remove prefix - $host=preg_replace('@tls://@i', '', $host); // Remove prefix + $host = preg_replace('@tcp://@i', '', $host); // Remove prefix + $host = preg_replace('@ssl://@i', '', $host); // Remove prefix + $host = preg_replace('@tls://@i', '', $host); // Remove prefix // @CHANGE LDR include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if ( (! is_ip($host)) && ((gethostbyname($host)) == $host)) + if ((!is_ip($host)) && ((gethostbyname($host)) == $host)) { - $this->_setErr(99, $host . ' is either offline or is an invalid host name.'); + $this->_setErr(99, $host.' is either offline or is an invalid host name.'); $_retVal = false; } else { //See if we can connect to the SMTP server if ($this->socket = @fsockopen( - preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain - $this->getPort(), // which Port number to use - $this->errno, // actual system level error - $this->errstr, // and any text that goes with the error + preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain + $this->getPort(), // which Port number to use + $this->errno, // actual system level error + $this->errstr, // and any text that goes with the error $this->_smtpTimeout // timeout for reading/writing data over the socket )) { // Fix from PHP SMTP class by 'Chris Ryan' @@ -391,14 +391,14 @@ class SMTPs if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0); // Check response from Server - if ( $_retVal = $this->server_parse($this->socket, "220") ) + if ($_retVal = $this->server_parse($this->socket, "220")) $_retVal = $this->socket; } // This connection attempt failed. else { // @CHANGE LDR - if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort(); + if (empty($this->errstr)) $this->errstr = 'Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort(); $this->_setErr($this->errno, $this->errstr); $_retVal = false; } @@ -421,18 +421,18 @@ class SMTPs // Send the RFC2554 specified EHLO. // This improvment as provided by 'SirSir' to // accomodate both SMTP AND ESMTP capable servers - $host=$this->getHost(); + $host = $this->getHost(); $usetls = preg_match('@tls://@i', $host); - $host=preg_replace('@tcp://@i', '', $host); // Remove prefix - $host=preg_replace('@ssl://@i', '', $host); // Remove prefix - $host=preg_replace('@tls://@i', '', $host); // Remove prefix + $host = preg_replace('@tcp://@i', '', $host); // Remove prefix + $host = preg_replace('@ssl://@i', '', $host); // Remove prefix + $host = preg_replace('@tls://@i', '', $host); // Remove prefix - if ($usetls) $host='tls://'.$host; + if ($usetls) $host = 'tls://'.$host; $hosth = $host; - if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) + if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) { // If the from to is 'aaa ', we will keep 'ccc.com' $hosth = $this->getFrom('addr'); @@ -441,7 +441,7 @@ class SMTPs $hosth = preg_replace('/.*@/', '', $hosth); } - if ( $_retVal = $this->socket_send_str('EHLO ' . $hosth, '250') ) + if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) { if ($usetls) { @@ -492,7 +492,7 @@ class SMTPs // the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS. if (!$_retVal = $this->socket_send_str('EHLO '.$host, '250')) { - $this->_setErr(126, '"' . $host . '" does not support authenticated connections.'); + $this->_setErr(126, '"'.$host.'" does not support authenticated connections.'); return $_retVal; } } @@ -506,7 +506,7 @@ class SMTPs case 'PLAIN': $this->socket_send_str('AUTH PLAIN', '334'); // The error here just means the ID/password combo doesn't work. - $_retVal = $this->socket_send_str(base64_encode("\0" . $this->_smtpsID . "\0" . $this->_smtpsPW), '235'); + $_retVal = $this->socket_send_str(base64_encode("\0".$this->_smtpsID."\0".$this->_smtpsPW), '235'); break; case 'LOGIN': // most common case default: @@ -518,13 +518,13 @@ class SMTPs $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235'); break; } - if (! $_retVal) { + if (!$_retVal) { $this->_setErr(130, 'Invalid Authentication Credentials.'); } } else { - $this->_setErr(126, '"' . $host . '" does not support authenticated connections.'); + $this->_setErr(126, '"'.$host.'" does not support authenticated connections.'); } return $_retVal; @@ -548,10 +548,10 @@ class SMTPs $_retVal = false; // Connect to Server - if ( $this->socket = $this->_server_connect() ) + if ($this->socket = $this->_server_connect()) { // If a User ID *and* a password is given, assume Authentication is desired - if( !empty($this->_smtpsID) && !empty($this->_smtpsPW) ) + if (!empty($this->_smtpsID) && !empty($this->_smtpsPW)) { // Send the RFC2554 specified EHLO. $_retVal = $this->_server_authenticate(); @@ -561,16 +561,16 @@ class SMTPs else { // Send the RFC821 specified HELO. - $host=$this->getHost(); + $host = $this->getHost(); $usetls = preg_match('@tls://@i', $host); - $host=preg_replace('@tcp://@i', '', $host); // Remove prefix - $host=preg_replace('@ssl://@i', '', $host); // Remove prefix - $host=preg_replace('@tls://@i', '', $host); // Remove prefix + $host = preg_replace('@tcp://@i', '', $host); // Remove prefix + $host = preg_replace('@ssl://@i', '', $host); // Remove prefix + $host = preg_replace('@tls://@i', '', $host); // Remove prefix $hosth = $host; - if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) + if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO)) { // If the from to is 'aaa ', we will keep 'ccc.com' $hosth = $this->getFrom('addr'); @@ -579,17 +579,17 @@ class SMTPs $hosth = preg_replace('/.*@/', '', $hosth); } - $_retVal = $this->socket_send_str('HELO ' . $hosth, '250'); + $_retVal = $this->socket_send_str('HELO '.$hosth, '250'); } // Well, did we get to the server? - if ( $_retVal ) + if ($_retVal) { // From this point onward most server response codes should be 250 // Specify who the mail is from.... // This has to be the raw email address, strip the "name" off - $resultmailfrom = $this->socket_send_str('MAIL FROM: ' . $this->getFrom('addr'), '250'); - if (! $resultmailfrom) { + $resultmailfrom = $this->socket_send_str('MAIL FROM: '.$this->getFrom('addr'), '250'); + if (!$resultmailfrom) { fclose($this->socket); return false; } @@ -613,7 +613,7 @@ class SMTPs * mark the last address as "bad" and start the address loop over again. * If any address fails, the entire message fails. */ - $this->socket_send_str('RCPT TO: <' . $_address . '>', '250'); + $this->socket_send_str('RCPT TO: <'.$_address.'>', '250'); } // Tell the server we are ready to start sending data @@ -623,7 +623,7 @@ class SMTPs // Now we are ready for the message... // Ok, all the ingredients are mixed in let's cook this puppy... - $this->socket_send_str($this->getHeader().$this->getBodyContent() . "\r\n" . '.', '250'); + $this->socket_send_str($this->getHeader().$this->getBodyContent()."\r\n".'.', '250'); // Now tell the server we are done and close the socket... fputs($this->socket, 'QUIT'); @@ -673,13 +673,13 @@ class SMTPs $_retVal = true; // if we have a path... - if ( ! empty($_strConfigPath) ) + if (!empty($_strConfigPath)) { // If the path is not valid, this will NOT generate an error, // it will simply return false. - if ( ! @include $_strConfigPath) + if (!@include $_strConfigPath) { - $this->_setErr(110, '"' . $_strConfigPath . '" is not a valid path.'); + $this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.'); $_retVal = false; } } @@ -689,13 +689,13 @@ class SMTPs { // Set these properties ONLY if they are set in the php.ini file. // Otherwise the default values will be used. - if ( $_host = ini_get('SMTPs') ) + if ($_host = ini_get('SMTPs')) $this->setHost($_host); - if ( $_port = ini_get('smtp_port') ) + if ($_port = ini_get('smtp_port')) $this->setPort($_port); - if ( $_from = ini_get('sendmail_from') ) + if ($_from = ini_get('sendmail_from')) $this->setFrom($_from); } @@ -757,7 +757,7 @@ class SMTPs */ public function setHost($_strHost) { - if ( $_strHost ) + if ($_strHost) $this->_smtpsHost = $_strHost; } @@ -782,8 +782,8 @@ class SMTPs */ public function setPort($_intPort) { - if ( ( is_numeric($_intPort) ) && - ( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) ) + if ((is_numeric($_intPort)) && + (($_intPort >= 1) && ($_intPort <= 65536))) $this->_smtpsPort = $_intPort; } @@ -849,7 +849,7 @@ class SMTPs */ public function setCharSet($_strCharSet) { - if ( $_strCharSet ) + if ($_strCharSet) $this->_smtpsCharSet = $_strCharSet; } @@ -937,7 +937,7 @@ class SMTPs */ public function setFrom($_strFrom) { - if ( $_strFrom ) + if ($_strFrom) $this->_msgFrom = $this->_strip_email($_strFrom); } @@ -951,7 +951,7 @@ class SMTPs { $_retValue = ''; - if ( $_part === true ) + if ($_part === true) $_retValue = $this->_msgFrom; else $_retValue = $this->_msgFrom[$_part]; @@ -967,7 +967,7 @@ class SMTPs */ public function setReplyTo($_strReplyTo) { - if ( $_strReplyTo ) + if ($_strReplyTo) $this->_msgReplyTo = $this->_strip_email($_strReplyTo); } @@ -981,7 +981,7 @@ class SMTPs { $_retValue = ''; - if ( $_part === true ) + if ($_part === true) $_retValue = $this->_msgReplyTo; else $_retValue = $this->_msgReplyTo[$_part]; @@ -1007,13 +1007,13 @@ class SMTPs $aryHost = $this->_msgRecipients; // Only run this if we have something - if ( !empty($_addrList)) + if (!empty($_addrList)) { // $_addrList can be a STRING or an array - if ( is_string($_addrList) ) + if (is_string($_addrList)) { // This could be a COMMA delimited string - if ( strstr($_addrList, ',') ) + if (strstr($_addrList, ',')) // "explode "list" into an array $_addrList = explode(',', $_addrList); @@ -1033,7 +1033,7 @@ class SMTPs $_tmpaddr = explode('<', $_strAddr); // We have a "Real Name" and eMail address - if ( count($_tmpaddr) == 2 ) + if (count($_tmpaddr) == 2) { $_tmpHost = explode('@', $_tmpaddr[1]); $_tmpaddr[0] = trim($_tmpaddr[0], ' ">'); @@ -1090,10 +1090,10 @@ class SMTPs $_tmpAry = explode('<', $_strAddr); // Do we have a "Real name" - if ( count($_tmpAry) == 2 ) + if (count($_tmpAry) == 2) { // We may not really have a "Real Name" - if ( $_tmpAry[0]) + if ($_tmpAry[0]) $_aryEmail['real'] = trim($_tmpAry[0], ' ">'); $_aryEmail['addr'] = $_tmpAry[1]; @@ -1102,10 +1102,10 @@ class SMTPs $_aryEmail['addr'] = $_tmpAry[0]; // Pull User Name and Host.tld apart - list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']); + list($_aryEmail['user'], $_aryEmail['host']) = explode('@', $_aryEmail['addr']); // Put the brackets back around the address - $_aryEmail['addr'] = '<' . $_aryEmail['addr'] . '>'; + $_aryEmail['addr'] = '<'.$_aryEmail['addr'].'>'; return $_aryEmail; } @@ -1124,7 +1124,7 @@ class SMTPs /** * An array of bares addresses for use with 'RCPT TO:' */ - $_RCPT_list=array(); + $_RCPT_list = array(); // walk down Recipients array and pull just email addresses foreach ($this->_msgRecipients as $_host => $_list) @@ -1134,7 +1134,7 @@ class SMTPs foreach ($_subList as $_name => $_addr) { // build RCPT list - $_RCPT_list[] = $_name . '@' . $_host; + $_RCPT_list[] = $_name.'@'.$_host; } } } @@ -1153,27 +1153,27 @@ class SMTPs { // phpcs:enable // We need to know which address segment to pull - if ( $_which ) + if ($_which) { // Make sure we have addresses to process - if ( $this->_msgRecipients ) + if ($this->_msgRecipients) { - $_RCPT_list=array(); + $_RCPT_list = array(); // walk down Recipients array and pull just email addresses foreach ($this->_msgRecipients as $_host => $_list) { - if ( $this->_msgRecipients[$_host][$_which] ) + if ($this->_msgRecipients[$_host][$_which]) { foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName) { - if ( $_realName ) // @CHANGE LDR + if ($_realName) // @CHANGE LDR { - $_realName = '"' . $_realName . '"'; - $_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>'; + $_realName = '"'.$_realName.'"'; + $_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>'; } else { - $_RCPT_list[] = $_addr . '@' . $_host; + $_RCPT_list[] = $_addr.'@'.$_host; } } } @@ -1202,7 +1202,7 @@ class SMTPs */ public function setTO($_addrTo) { - if ( $_addrTo ) + if ($_addrTo) $this->_buildAddrList('to', $_addrTo); } @@ -1224,7 +1224,7 @@ class SMTPs */ public function setCC($_strCC) { - if ( $_strCC ) + if ($_strCC) $this->_buildAddrList('cc', $_strCC); } @@ -1246,7 +1246,7 @@ class SMTPs */ public function setBCC($_strBCC) { - if ( $_strBCC ) + if ($_strBCC) $this->_buildAddrList('bcc', $_strBCC); } @@ -1268,7 +1268,7 @@ class SMTPs */ public function setSubject($_strSubject = '') { - if ( $_strSubject ) + if ($_strSubject) $this->_msgSubject = $_strSubject; } @@ -1291,11 +1291,11 @@ class SMTPs { global $conf; - $_header = 'From: ' . $this->getFrom('org') . "\r\n" - . 'To: ' . $this->getTO() . "\r\n"; + $_header = 'From: '.$this->getFrom('org')."\r\n" + . 'To: '.$this->getTO()."\r\n"; - if ( $this->getCC() ) - $_header .= 'Cc: ' . $this->getCC() . "\r\n"; + if ($this->getCC()) + $_header .= 'Cc: '.$this->getCC()."\r\n"; /* Note: * BCC email addresses must be listed in the RCPT TO command list, @@ -1308,50 +1308,50 @@ class SMTPs $_header .= 'Bcc: ' . $this->getBCC() . "\r\n"; */ - $host=dol_getprefix('email'); + $host = dol_getprefix('email'); //NOTE: Message-ID should probably contain the username of the user who sent the msg - $_header .= 'Subject: ' . $this->getSubject() . "\r\n"; - $_header .= 'Date: ' . date("r") . "\r\n"; + $_header .= 'Subject: '.$this->getSubject()."\r\n"; + $_header .= 'Date: '.date("r")."\r\n"; $trackid = $this->getTrackId(); if ($trackid) { // References is kept in response and Message-ID is returned into In-Reply-To: - $_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n"; - $_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n"; - $_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n"; + $_header .= 'Message-ID: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n"; + $_header .= 'References: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n"; + $_header .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host."\r\n"; } else { - $_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n"; + $_header .= 'Message-ID: <'.time().'.SMTPs@'.$host.">\r\n"; } - if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n"; - if ( $this->getMoreInHeader() ) - $_header .= $this->getMoreInHeader(); // Value must include the "\r\n"; + if (!empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n"; + if ($this->getMoreInHeader()) + $_header .= $this->getMoreInHeader(); // Value must include the "\r\n"; //$_header .= // 'Read-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n" // 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n"; - if ( $this->getSensitivity() ) - $_header .= 'Sensitivity: ' . $this->getSensitivity() . "\r\n"; + if ($this->getSensitivity()) + $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n"; - if ( $this->_msgPriority != 3 ) + if ($this->_msgPriority != 3) $_header .= $this->getPriority(); // @CHANGE LDR - if ( $this->getDeliveryReceipt() ) - $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n"; - if ( $this->getErrorsTo() ) - $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n"; - if ( $this->getReplyTo() ) - $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n"; + if ($this->getDeliveryReceipt()) + $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n"; + if ($this->getErrorsTo()) + $_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n"; + if ($this->getReplyTo()) + $_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n"; - $_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n"; - $_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n"; - $_header .= 'Mime-Version: 1.0' . "\r\n"; + $_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n"; + $_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n"; + $_header .= 'Mime-Version: 1.0'."\r\n"; return $_header; @@ -1368,7 +1368,7 @@ class SMTPs { //if ( $strContent ) //{ - if ( $strType == 'html' ) + if ($strType == 'html') $strMimeType = 'text/html'; else $strMimeType = 'text/plain'; @@ -1387,7 +1387,7 @@ class SMTPs // Make RFC2045 Compliant //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content - $strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content. + $strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content. $this->_msgContent[$strType] = array(); @@ -1395,7 +1395,7 @@ class SMTPs $this->_msgContent[$strType]['data'] = $strContent; $this->_msgContent[$strType]['dataText'] = $strContentAltText; - if ( $this->getMD5flag() ) + if ($this->getMD5flag()) $this->_msgContent[$strType]['md5'] = dol_hash($strContent, 3); //} } @@ -1419,49 +1419,49 @@ class SMTPs $keyCount = count($_types); // If we have ZERO, we have a problem - if( $keyCount === 0 ) + if ($keyCount === 0) die("Sorry, no content"); // If we have ONE, we can use the simple format - elseif( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) + elseif ($keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { $_msgData = $this->_msgContent; $_msgData = $_msgData[$_types[0]]; - $content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n" - . 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n" - . 'Content-Disposition: inline' . "\r\n" - . 'Content-Description: Message' . "\r\n"; + $content = 'Content-Type: '.$_msgData['mimeType'].'; charset="'.$this->getCharSet().'"'."\r\n" + . 'Content-Transfer-Encoding: '.$this->getTransEncodeType()."\r\n" + . 'Content-Disposition: inline'."\r\n" + . 'Content-Description: Message'."\r\n"; - if ( $this->getMD5flag() ) - $content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n"; + if ($this->getMD5flag()) + $content .= 'Content-MD5: '.$_msgData['md5']."\r\n"; $content .= "\r\n" - . $_msgData['data'] . "\r\n"; + . $_msgData['data']."\r\n"; } // If we have more than ONE, we use the multi-part format - elseif( $keyCount >= 1 || ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) + elseif ($keyCount >= 1 || !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Since this is an actual multi-part message // We need to define a content message Boundary // NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this. //$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"' . "\r\n"; - $content = 'Content-Type: multipart/mixed; boundary="' . $this->_getBoundary('mixed') . '"' . "\r\n"; + $content = 'Content-Type: multipart/mixed; boundary="'.$this->_getBoundary('mixed').'"'."\r\n"; // . "\r\n" // . 'This is a multi-part message in MIME format.' . "\r\n"; $content .= "Content-Transfer-Encoding: 8bit\r\n"; $content .= "\r\n"; - $content .= "--" . $this->_getBoundary('mixed') . "\r\n"; + $content .= "--".$this->_getBoundary('mixed')."\r\n"; if (key_exists('image', $this->_msgContent)) // If inline image found { - $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n"; + $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n"; $content .= "\r\n"; - $content .= "--" . $this->_getBoundary('alternative') . "\r\n"; + $content .= "--".$this->_getBoundary('alternative')."\r\n"; } @@ -1471,91 +1471,91 @@ class SMTPs // Loop through message content array foreach ($this->_msgContent as $type => $_content) { - if ( $type == 'attachment' ) + if ($type == 'attachment') { // loop through all attachments foreach ($_content as $_file => $_data) { - $content .= "--" . $this->_getBoundary('mixed') . "\r\n" - . 'Content-Disposition: attachment; filename="' . $_data['fileName'] . '"' . "\r\n" - . 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['fileName'] . '"' . "\r\n" - . 'Content-Transfer-Encoding: base64' . "\r\n" - . 'Content-Description: ' . $_data['fileName'] ."\r\n"; + $content .= "--".$this->_getBoundary('mixed')."\r\n" + . 'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n" + . 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n" + . 'Content-Transfer-Encoding: base64'."\r\n" + . 'Content-Description: '.$_data['fileName']."\r\n"; - if ( $this->getMD5flag() ) - $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n"; + if ($this->getMD5flag()) + $content .= 'Content-MD5: '.$_data['md5']."\r\n"; - $content .= "\r\n" . $_data['data'] . "\r\n\r\n"; + $content .= "\r\n".$_data['data']."\r\n\r\n"; } } // @CHANGE LDR - elseif ( $type == 'image' ) + elseif ($type == 'image') { // loop through all images foreach ($_content as $_image => $_data) { - $content .= "--" . $this->_getBoundary('related') . "\r\n"; // always related for an inline image + $content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image - $content .= 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['imageName'] . '"' . "\r\n" - . 'Content-Transfer-Encoding: base64' . "\r\n" - . 'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n" - . 'Content-ID: <' . $_data['cid'] . '> ' . "\r\n"; + $content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n" + . 'Content-Transfer-Encoding: base64'."\r\n" + . 'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n" + . 'Content-ID: <'.$_data['cid'].'> '."\r\n"; - if ( $this->getMD5flag() ) - $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n"; + if ($this->getMD5flag()) + $content .= 'Content-MD5: '.$_data['md5']."\r\n"; $content .= "\r\n" - . $_data['data'] . "\r\n"; + . $_data['data']."\r\n"; } // always end related and end alternative after inline images - $content.= "--" . $this->_getBoundary('related') . "--" . "\r\n"; - $content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n"; - $content.= "\r\n"; + $content .= "--".$this->_getBoundary('related')."--"."\r\n"; + $content .= "\r\n"."--".$this->_getBoundary('alternative')."--"."\r\n"; + $content .= "\r\n"; } else { if (key_exists('image', $this->_msgContent)) { - $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n"; - $content.= "\r\n" . ($_content['dataText']?$_content['dataText']:strip_tags($_content['data'])) . "\r\n"; // Add plain text message - $content.= "--" . $this->_getBoundary('alternative') . "\r\n"; - $content.= 'Content-Type: multipart/related; boundary="' . $this->_getBoundary('related') . '"' . "\r\n"; - $content.= "\r\n"; - $content.= "--" . $this->_getBoundary('related') . "\r\n"; - } - - if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part - { - $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n"; + $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n"; + $content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message + $content .= "--".$this->_getBoundary('alternative')."\r\n"; + $content .= 'Content-Type: multipart/related; boundary="'.$this->_getBoundary('related').'"'."\r\n"; $content .= "\r\n"; - $content .= "--" . $this->_getBoundary('alternative') . "\r\n"; - - $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n"; - $content.= "\r\n". $_content['dataText'] . "\r\n"; - $content.= "--" . $this->_getBoundary('alternative') . "\r\n"; + $content .= "--".$this->_getBoundary('related')."\r\n"; } - $content .= 'Content-Type: ' . $_content['mimeType'] . '; ' + if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part + { + $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n"; + $content .= "\r\n"; + $content .= "--".$this->_getBoundary('alternative')."\r\n"; + + $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n"; + $content .= "\r\n".$_content['dataText']."\r\n"; + $content .= "--".$this->_getBoundary('alternative')."\r\n"; + } + + $content .= 'Content-Type: '.$_content['mimeType'].'; ' // . 'charset="' . $this->getCharSet() . '"'; - . 'charset=' . $this->getCharSet() . ''; + . 'charset='.$this->getCharSet().''; // $content .= ( $type == 'html') ? '; name="HTML Part"' : ''; - $content .= "\r\n"; + $content .= "\r\n"; // $content .= 'Content-Transfer-Encoding: '; // $content .= ($type == 'html') ? 'quoted-printable' : $this->getTransEncodeType(); // $content .= "\r\n" // . 'Content-Disposition: inline' . "\r\n" // . 'Content-Description: ' . $type . ' message' . "\r\n"; - if ( $this->getMD5flag() ) - $content .= 'Content-MD5: ' . $_content['md5'] . "\r\n"; + if ($this->getMD5flag()) + $content .= 'Content-MD5: '.$_content['md5']."\r\n"; - $content .= "\r\n" . $_content['data'] . "\r\n"; + $content .= "\r\n".$_content['data']."\r\n"; - if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part + if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part { - $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n"; + $content .= "--".$this->_getBoundary('alternative')."--"."\r\n"; } $content .= "\r\n"; @@ -1564,7 +1564,7 @@ class SMTPs // Close message boundries // $content .= "\r\n--" . $this->_getBoundary() . '--' . "\r\n" ; - $content .= "--" . $this->_getBoundary('mixed') . '--' . "\r\n" ; + $content .= "--".$this->_getBoundary('mixed').'--'."\r\n"; } return $content; @@ -1581,15 +1581,15 @@ class SMTPs */ public function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown') { - if ( $strContent ) + if ($strContent) { - $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047 + $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047 $this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType; $this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName; $this->_msgContent['attachment'][$strFileName]['data'] = $strContent; - if ( $this->getMD5flag() ) + if ($this->getMD5flag()) $this->_msgContent['attachment'][$strFileName]['md5'] = dol_hash($strContent, 3); } } @@ -1616,7 +1616,7 @@ class SMTPs $this->_msgContent['image'][$strImageName]['cid'] = $strImageCid; $this->_msgContent['image'][$strImageName]['data'] = $strContent; - if ( $this->getMD5flag() ) + if ($this->getMD5flag()) $this->_msgContent['image'][$strImageName]['md5'] = dol_hash($strContent, 3); } } @@ -1636,8 +1636,8 @@ class SMTPs */ public function setSensitivity($_value = 0) { - if ( ( is_numeric($_value) ) && - ( ( $_value >= 0 ) && ( $_value <= 3 ) ) ) + if ((is_numeric($_value)) && + (($_value >= 0) && ($_value <= 3))) $this->_msgSensitivity = $_value; } @@ -1671,8 +1671,8 @@ class SMTPs */ public function setPriority($_value = 3) { - if ( ( is_numeric($_value) ) && - ( ( $_value >= 0 ) && ( $_value <= 5 ) ) ) + if ((is_numeric($_value)) && + (($_value >= 0) && ($_value <= 5))) $this->_msgPriority = $_value; } @@ -1690,9 +1690,9 @@ class SMTPs */ public function getPriority() { - return 'Importance: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n" - . 'Priority: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n" - . 'X-Priority: ' . $this->_msgPriority . ' (' . $this->_aryPriority[$this->_msgPriority] . ')' . "\r\n"; + return 'Importance: '.$this->_aryPriority[$this->_msgPriority]."\r\n" + . 'Priority: '.$this->_aryPriority[$this->_msgPriority]."\r\n" + . 'X-Priority: '.$this->_msgPriority.' ('.$this->_aryPriority[$this->_msgPriority].')'."\r\n"; } /** @@ -1726,7 +1726,7 @@ class SMTPs */ public function setXheader($strXdata) { - if ( $strXdata ) + if ($strXdata) $this->_msgXheader[] = $strXdata; } @@ -1747,7 +1747,7 @@ class SMTPs */ private function _setBoundary() { - $this->_smtpsBoundary = "multipart_x." . time() . ".x_boundary"; + $this->_smtpsBoundary = "multipart_x.".time().".x_boundary"; $this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); $this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); } @@ -1786,11 +1786,11 @@ class SMTPs $server_response = ''; // avoid infinite loop - $limit=0; + $limit = 0; - while (substr($server_response, 3, 1) != ' ' && $limit<100) + while (substr($server_response, 3, 1) != ' ' && $limit < 100) { - if (! ($server_response = fgets($socket, 256))) + if (!($server_response = fgets($socket, 256))) { $this->_setErr(121, "Couldn't get mail server response codes"); $_retVal = false; @@ -1800,7 +1800,7 @@ class SMTPs $limit++; } - if (! (substr($server_response, 0, 3) == $response)) + if (!(substr($server_response, 0, 3) == $response)) { $this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response"); $_retVal = false; @@ -1821,11 +1821,11 @@ class SMTPs public function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n") { // phpcs:enable - if ($this->_debug) $this->log.=$_strSend; // @CHANGE LDR for log - fputs($this->socket, $_strSend . $CRLF); - if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF; + if ($this->_debug) $this->log .= $_strSend; // @CHANGE LDR for log + fputs($this->socket, $_strSend.$CRLF); + if ($this->_debug) $this->log .= ' ('.$_returnCode.')'.$CRLF; - if ( $_returnCode ) + if ($_returnCode) return $this->server_parse($this->socket, $_returnCode); } @@ -1860,7 +1860,7 @@ class SMTPs { foreach ($this->_smtpsErrors as $_err => $_info) { - $_errMsg[] = 'Error [' . $_info['num'] .']: '. $_info['msg']; + $_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg']; } } diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 0ce761d12b8..fb9e292ba83 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -29,17 +29,17 @@ */ class Translate { - public $dir; // Directories that contains /langs subdirectory + public $dir; // Directories that contains /langs subdirectory - public $defaultlang; // Current language for current user - public $charset_output='UTF-8'; // Codage used by "trans" method outputs + public $defaultlang; // Current language for current user + public $charset_output = 'UTF-8'; // Codage used by "trans" method outputs - public $tab_translate=array(); // Array of all translations key=>value - private $_tab_loaded=array(); // Array to store result after loading each language file + public $tab_translate = array(); // Array of all translations key=>value + private $_tab_loaded = array(); // Array to store result after loading each language file - public $cache_labels=array(); // Cache for labels return by getLabelFromKey method - public $cache_currencies=array(); // Cache to store currency symbols - private $cache_currencies_all_loaded=false; + public $cache_labels = array(); // Cache for labels return by getLabelFromKey method + public $cache_currencies = array(); // Cache to store currency symbols + private $cache_currencies_all_loaded = false; /** @@ -50,9 +50,9 @@ class Translate */ public function __construct($dir, $conf) { - if (! empty($conf->file->character_set_client)) $this->charset_output=$conf->file->character_set_client; // If charset output is forced - if ($dir) $this->dir=array($dir); - else $this->dir=$conf->file->dol_document_root; + if (!empty($conf->file->character_set_client)) $this->charset_output = $conf->file->character_set_client; // If charset output is forced + if ($dir) $this->dir = array($dir); + else $this->dir = $conf->file->dol_document_root; } @@ -69,59 +69,59 @@ class Translate //dol_syslog(get_class($this)."::setDefaultLang srclang=".$srclang,LOG_DEBUG); // If a module ask to force a priority on langs directories (to use its own lang files) - if (! empty($conf->global->MAIN_FORCELANGDIR)) + if (!empty($conf->global->MAIN_FORCELANGDIR)) { - $more=array(); - $i=0; - foreach($conf->file->dol_document_root as $dir) + $more = array(); + $i = 0; + foreach ($conf->file->dol_document_root as $dir) { - $newdir=$dir.$conf->global->MAIN_FORCELANGDIR; // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX' - if (! in_array($newdir, $this->dir)) + $newdir = $dir.$conf->global->MAIN_FORCELANGDIR; // For example $conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX' + if (!in_array($newdir, $this->dir)) { - $more['module_'.$i]=$newdir; $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir. + $more['module_'.$i] = $newdir; $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir. } } - $this->dir=array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir) + $this->dir = array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir) } - $this->origlang=$srclang; + $this->origlang = $srclang; if (empty($srclang) || $srclang == 'auto') { // $_SERVER['HTTP_ACCEPT_LANGUAGE'] can be 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6' but can contains also malicious content - $langpref=empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])?'':$_SERVER['HTTP_ACCEPT_LANGUAGE']; - $langpref=preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part - $langpref=str_replace("-", "_", $langpref); - $langlist=preg_split("/[;,]/", $langpref); - $codetouse=preg_replace('/[^_a-zA-Z]/', '', $langlist[0]); + $langpref = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? '' : $_SERVER['HTTP_ACCEPT_LANGUAGE']; + $langpref = preg_replace("/;([^,]*)/i", "", $langpref); // Remove the 'q=x.y,' part + $langpref = str_replace("-", "_", $langpref); + $langlist = preg_split("/[;,]/", $langpref); + $codetouse = preg_replace('/[^_a-zA-Z]/', '', $langlist[0]); } - else $codetouse=$srclang; + else $codetouse = $srclang; // We redefine $srclang - $langpart=explode("_", $codetouse); + $langpart = explode("_", $codetouse); //print "Short code before _ : ".$langpart[0].' / Short code after _ : '.$langpart[1].'
'; - if (! empty($langpart[1])) // If it's for a codetouse that is a long code xx_YY + if (!empty($langpart[1])) // If it's for a codetouse that is a long code xx_YY { // Array force long code from first part, even if long code is defined - $longforshort=array('ar'=>'ar_SA'); - $longforshortexcep=array('ar_EG'); - if (isset($longforshort[strtolower($langpart[0])]) && ! in_array($codetouse, $longforshortexcep)) $srclang=$longforshort[strtolower($langpart[0])]; - elseif (! is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser - $srclang=strtolower($langpart[0])."_".strtoupper($langpart[1]); - $longforlong=array('no_nb'=>'nb_NO'); - if (isset($longforlong[strtolower($srclang)])) $srclang=$longforlong[strtolower($srclang)]; + $longforshort = array('ar'=>'ar_SA'); + $longforshortexcep = array('ar_EG'); + if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep)) $srclang = $longforshort[strtolower($langpart[0])]; + elseif (!is_numeric($langpart[1])) { // Second part YY may be a numeric with some Chrome browser + $srclang = strtolower($langpart[0])."_".strtoupper($langpart[1]); + $longforlong = array('no_nb'=>'nb_NO'); + if (isset($longforlong[strtolower($srclang)])) $srclang = $longforlong[strtolower($srclang)]; } - else $srclang=strtolower($langpart[0])."_".strtoupper($langpart[0]); + else $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]); } else { // If it's for a codetouse that is a short code xx // Array to convert short lang code into long code. - $longforshort=array('ar'=>'ar_SA', 'el'=>'el_GR', 'ca'=>'ca_ES', 'en'=>'en_US', 'nb'=>'nb_NO', 'no'=>'nb_NO'); - if (isset($longforshort[strtolower($langpart[0])])) $srclang=$longforshort[strtolower($langpart[0])]; - elseif (! empty($langpart[0])) $srclang=strtolower($langpart[0])."_".strtoupper($langpart[0]); - else $srclang='en_US'; + $longforshort = array('ar'=>'ar_SA', 'el'=>'el_GR', 'ca'=>'ca_ES', 'en'=>'en_US', 'nb'=>'nb_NO', 'no'=>'nb_NO'); + if (isset($longforshort[strtolower($langpart[0])])) $srclang = $longforshort[strtolower($langpart[0])]; + elseif (!empty($langpart[0])) $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]); + else $srclang = 'en_US'; } - $this->defaultlang=$srclang; + $this->defaultlang = $srclang; //print 'this->defaultlang='.$this->defaultlang; } @@ -148,7 +148,7 @@ class Translate */ public function loadLangs($domains) { - foreach($domains as $domain) + foreach ($domains as $domain) { $this->load($domain); } @@ -176,7 +176,7 @@ class Translate */ public function load($domain, $alt = 0, $stopafterdirection = 0, $forcelangdir = '', $loadfromfileonly = 0) { - global $conf,$db; + global $conf, $db; //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang); @@ -186,18 +186,18 @@ class Translate dol_print_error('', get_class($this)."::Load ErrorWrongParameters"); return -1; } - if ($this->defaultlang == 'none_NONE') return 0; // Special language code to not translate keys + if ($this->defaultlang == 'none_NONE') return 0; // Special language code to not translate keys // Load $this->tab_translate[] from database - if (empty($loadfromfileonly) && count($this->tab_translate) == 0) $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database. + if (empty($loadfromfileonly) && count($this->tab_translate) == 0) $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database. $newdomain = $domain; $modulename = ''; // Search if a module directory name is provided into lang file name - $regs=array(); + $regs = array(); if (preg_match('/^([^@]+)@([^@]+)$/i', $domain, $regs)) { $newdomain = $regs[1]; @@ -205,19 +205,19 @@ class Translate } // Check cache - if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain + if (!empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain { //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); return 0; } - $fileread=0; - $langofdir=(empty($forcelangdir)?$this->defaultlang:$forcelangdir); + $fileread = 0; + $langofdir = (empty($forcelangdir) ? $this->defaultlang : $forcelangdir); // Redefine alt - $langarray=explode('_', $langofdir); - if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) $alt=1; - if ($alt < 2 && strtolower($langofdir) == 'en_us') $alt=2; + $langarray = explode('_', $langofdir); + if ($alt < 1 && isset($langarray[1]) && (strtolower($langarray[0]) == strtolower($langarray[1]) || in_array(strtolower($langofdir), array('el_gr')))) $alt = 1; + if ($alt < 2 && strtolower($langofdir) == 'en_us') $alt = 2; if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir { @@ -225,13 +225,13 @@ class Translate return -1; } - foreach($this->dir as $searchdir) + foreach ($this->dir as $searchdir) { // Directory of translation files - $file_lang = $searchdir.($modulename?'/'.$modulename:'')."/langs/".$langofdir."/".$newdomain.".lang"; - $file_lang_osencoded=dol_osencode($file_lang); + $file_lang = $searchdir.($modulename ? '/'.$modulename : '')."/langs/".$langofdir."/".$newdomain.".lang"; + $file_lang_osencoded = dol_osencode($file_lang); - $filelangexists=is_file($file_lang_osencoded); + $filelangexists = is_file($file_lang_osencoded); //dol_syslog(get_class($this).'::Load Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' file_lang='.$file_lang." => filelangexists=".$filelangexists); //print 'Try to read for alt='.$alt.' langofdir='.$langofdir.' domain='.$domain.' newdomain='.$newdomain.' modulename='.$modulename.' this->_tab_loaded[newdomain]='.$this->_tab_loaded[$newdomain].' file_lang='.$file_lang." => filelangexists=".$filelangexists."\n"; @@ -239,19 +239,19 @@ class Translate if ($filelangexists) { // TODO Move cache read out of loop on dirs or at least filelangexists - $found=false; + $found = false; // Enable caching of lang file in memory (not by default) - $usecachekey=''; + $usecachekey = ''; // Using a memcached server - if (! empty($conf->memcached->enabled) && ! empty($conf->global->MEMCACHED_SERVER)) + if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) { - $usecachekey=$newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars + $usecachekey = $newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars } // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file) elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) { - $usecachekey=$newdomain; + $usecachekey = $newdomain; } if ($usecachekey) @@ -259,23 +259,23 @@ class Translate //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey); //global $aaa; $aaa+=1; //print $aaa." ".$usecachekey."\n"; - require_once DOL_DOCUMENT_ROOT .'/core/lib/memory.lib.php'; - $tmparray=dol_getcache($usecachekey); + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $tmparray = dol_getcache($usecachekey); if (is_array($tmparray) && count($tmparray)) { - $this->tab_translate+=$tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added. + $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added. //print $newdomain."\n"; //var_dump($this->tab_translate); - if ($alt == 2) $fileread=1; - $found=true; // Found in dolibarr PHP cache + if ($alt == 2) $fileread = 1; + $found = true; // Found in dolibarr PHP cache } } - if (! $found) + if (!$found) { if ($fp = @fopen($file_lang, "rt")) { - if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache + if ($usecachekey) $tabtranslatedomain = array(); // To save lang content in cache /** * Read each lines until a '=' (with any combination of spaces around it) @@ -316,21 +316,21 @@ class Translate } } fclose($fp); - $fileread=1; + $fileread = 1; // TODO Move cache write out of loop on dirs // To save lang content for usecachekey into cache if ($usecachekey && count($tabtranslatedomain)) { - $ressetcache=dol_setcache($usecachekey, $tabtranslatedomain); + $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain); if ($ressetcache < 0) { - $error='Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache; + $error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache; dol_syslog($error, LOG_ERR); } } - if (empty($conf->global->MAIN_FORCELANGDIR)) break; // Break loop on each root dir. If a module has forced dir, we do not stop loop. + if (empty($conf->global->MAIN_FORCELANGDIR)) break; // Break loop on each root dir. If a module has forced dir, we do not stop loop. } } } @@ -341,10 +341,10 @@ class Translate { // This function MUST NOT contains call to syslog //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG); - $langofdir=strtolower($langarray[0]).'_'.strtoupper($langarray[0]); - if ($langofdir == 'el_EL') $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR' - if ($langofdir == 'ar_AR') $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA' - $this->load($domain, $alt+1, $stopafterdirection, $langofdir); + $langofdir = strtolower($langarray[0]).'_'.strtoupper($langarray[0]); + if ($langofdir == 'el_EL') $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR' + if ($langofdir == 'ar_AR') $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA' + $this->load($domain, $alt + 1, $stopafterdirection, $langofdir); } // Now we complete with reference file (en_US) @@ -352,38 +352,38 @@ class Translate { // This function MUST NOT contains call to syslog //dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG); - $langofdir='en_US'; - $this->load($domain, $alt+1, $stopafterdirection, $langofdir); + $langofdir = 'en_US'; + $this->load($domain, $alt + 1, $stopafterdirection, $langofdir); } // We are in the pass of the reference file. No more files to scan to complete. if ($alt == 2) { - if ($fileread) $this->_tab_loaded[$newdomain]=1; // Set domain file as found so loaded + if ($fileread) $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded - if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain]=2; // Set this file as not found + if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain] = 2; // Set this file as not found } // This part is deprecated and replaced with table llx_overwrite_trans // Kept for backward compatibility. if (empty($loadfromfileonly)) { - $overwritekey='MAIN_OVERWRITE_TRANS_'.$this->defaultlang; - if (! empty($conf->global->$overwritekey)) // Overwrite translation with key1:newstring1,key2:newstring2 + $overwritekey = 'MAIN_OVERWRITE_TRANS_'.$this->defaultlang; + if (!empty($conf->global->$overwritekey)) // Overwrite translation with key1:newstring1,key2:newstring2 { // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX - $tmparray=explode(',', $conf->global->$overwritekey); - foreach($tmparray as $tmp) + $tmparray = explode(',', $conf->global->$overwritekey); + foreach ($tmparray as $tmp) { - $tmparray2=explode(':', $tmp); - if (! empty($tmparray2[1])) $this->tab_translate[$tmparray2[0]]=$tmparray2[1]; + $tmparray2 = explode(':', $tmp); + if (!empty($tmparray2[1])) $this->tab_translate[$tmparray2[0]] = $tmparray2[1]; } } } // Check to be sure that SeparatorDecimal differs from SeparatorThousand - if (! empty($this->tab_translate["SeparatorDecimal"]) && ! empty($this->tab_translate["SeparatorThousand"]) - && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"]=''; + if (!empty($this->tab_translate["SeparatorDecimal"]) && !empty($this->tab_translate["SeparatorThousand"]) + && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"] = ''; return 1; } @@ -404,26 +404,26 @@ class Translate { global $conf; - $domain='database'; + $domain = 'database'; // Check parameters - if (empty($db)) return 0; // Database handler can't be used + if (empty($db)) return 0; // Database handler can't be used //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang); $newdomain = $domain; // Check cache - if (! empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain 'database' + if (!empty($this->_tab_loaded[$newdomain])) // File already loaded for this domain 'database' { //dol_syslog("Translate::Load already loaded for newdomain=".$newdomain); return 0; } - $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only for domain 'database' + $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only for domain 'database' - $fileread=0; - $langofdir=$this->defaultlang; + $fileread = 0; + $langofdir = $this->defaultlang; if (empty($langofdir)) // This may occurs when load is called without setting the language and without providing a value for forcelangdir { @@ -432,19 +432,19 @@ class Translate } // TODO Move cache read out of loop on dirs or at least filelangexists - $found=false; + $found = false; // Enable caching of lang file in memory (not by default) - $usecachekey=''; + $usecachekey = ''; // Using a memcached server - if (! empty($conf->memcached->enabled) && ! empty($conf->global->MEMCACHED_SERVER)) + if (!empty($conf->memcached->enabled) && !empty($conf->global->MEMCACHED_SERVER)) { - $usecachekey=$newdomain.'_'.$langofdir; // Should not contains special chars + $usecachekey = $newdomain.'_'.$langofdir; // Should not contains special chars } // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file) elseif (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) { - $usecachekey=$newdomain; + $usecachekey = $newdomain; } if ($usecachekey) @@ -452,40 +452,40 @@ class Translate //dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey); //global $aaa; $aaa+=1; //print $aaa." ".$usecachekey."\n"; - require_once DOL_DOCUMENT_ROOT .'/core/lib/memory.lib.php'; - $tmparray=dol_getcache($usecachekey); + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $tmparray = dol_getcache($usecachekey); if (is_array($tmparray) && count($tmparray)) { - $this->tab_translate+=$tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a valuer already exists into tab_translate, value into tmparaay is not added. + $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a valuer already exists into tab_translate, value into tmparaay is not added. //print $newdomain."\n"; //var_dump($this->tab_translate); - $fileread=1; - $found=true; // Found in dolibarr PHP cache + $fileread = 1; + $found = true; // Found in dolibarr PHP cache } } - if (! $found && ! empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + if (!$found && !empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Overwrite translation with database read - $sql ="SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."' OR lang IS NULL"; - $sql.=" AND entity IN (0, ".getEntity('overwrite_trans').")"; - $sql.=$db->order("lang", "DESC"); - $resql=$db->query($sql); + $sql = "SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."' OR lang IS NULL"; + $sql .= " AND entity IN (0, ".getEntity('overwrite_trans').")"; + $sql .= $db->order("lang", "DESC"); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); if ($num) { - if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache + if ($usecachekey) $tabtranslatedomain = array(); // To save lang content in cache $i = 0; while ($i < $num) // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents { - $obj=$db->fetch_object($resql); + $obj = $db->fetch_object($resql); - $key=$obj->transkey; - $value=$obj->transvalue; + $key = $obj->transkey; + $value = $obj->transvalue; //print "Domain=$domain, found a string for $tab[0] with value $tab[1]
"; if (empty($this->tab_translate[$key])) // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries) @@ -493,22 +493,22 @@ class Translate // Convert some strings: Parse and render carriage returns. Also, change '\\s' int '\s' because transifex sync pull the string '\s' into string '\\s' $this->tab_translate[$key] = str_replace(array('\\n', '\\\\s'), array("\n", '\s'), $value); - if ($usecachekey) $tabtranslatedomain[$key]=$value; // To save lang content in cache + if ($usecachekey) $tabtranslatedomain[$key] = $value; // To save lang content in cache } $i++; } - $fileread=1; + $fileread = 1; // TODO Move cache write out of loop on dirs // To save lang content for usecachekey into cache if ($usecachekey && count($tabtranslatedomain)) { - $ressetcache=dol_setcache($usecachekey, $tabtranslatedomain); + $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain); if ($ressetcache < 0) { - $error='Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache; + $error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache; dol_syslog($error, LOG_ERR); } } @@ -520,9 +520,9 @@ class Translate } } - if ($fileread) $this->_tab_loaded[$newdomain]=1; // Set domain file as loaded + if ($fileread) $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded - if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain]=2; // Marque ce cas comme non trouve (no lines found for language) + if (empty($this->_tab_loaded[$newdomain])) $this->_tab_loaded[$newdomain] = 2; // Marque ce cas comme non trouve (no lines found for language) return 1; } @@ -544,28 +544,28 @@ class Translate { global $conf, $db; - if (! is_string($key)) return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly. + if (!is_string($key)) return 'ErrorBadValueForParamNotAString'; // Avoid multiple errors with code not using function correctly. - $newstr=$key; + $newstr = $key; if (preg_match('/^Civility([0-9A-Z]+)$/i', $key, $reg)) { - $newstr=$this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label'); + $newstr = $this->getLabelFromKey($db, $reg[1], 'c_civility', 'code', 'label'); } elseif (preg_match('/^Currency([A-Z][A-Z][A-Z])$/i', $key, $reg)) { - $newstr=$this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label'); + $newstr = $this->getLabelFromKey($db, $reg[1], 'c_currencies', 'code_iso', 'label'); } elseif (preg_match('/^SendingMethod([0-9A-Z]+)$/i', $key, $reg)) { - $newstr=$this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle'); + $newstr = $this->getLabelFromKey($db, $reg[1], 'c_shipment_mode', 'code', 'libelle'); } elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i', $key, $reg)) { - $newstr=$this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1); + $newstr = $this->getLabelFromKey($db, $reg[1], 'c_paiement', 'code', 'libelle', '', 1); } elseif (preg_match('/^OppStatus([0-9A-Z]+)$/i', $key, $reg)) { - $newstr=$this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label'); + $newstr = $this->getLabelFromKey($db, $reg[1], 'c_lead_status', 'code', 'label'); } elseif (preg_match('/^OrderSource([0-9A-Z]+)$/i', $key, $reg)) { @@ -601,37 +601,37 @@ class Translate { global $conf; - if (! empty($this->tab_translate[$key])) // Translation is available + if (!empty($this->tab_translate[$key])) // Translation is available { - $str=$this->tab_translate[$key]; + $str = $this->tab_translate[$key]; // Make some string replacement after translation - $replacekey='MAIN_REPLACE_TRANS_'.$this->defaultlang; - if (! empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2 + $replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang; + if (!empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2 { - $tmparray=explode(';', $conf->global->$replacekey); - foreach($tmparray as $tmp) + $tmparray = explode(';', $conf->global->$replacekey); + foreach ($tmparray as $tmp) { - $tmparray2=explode(':', $tmp); - $str=preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str); + $tmparray2 = explode(':', $tmp); + $str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str); } } if (strpos($key, 'Format') !== 0) { - $str=sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings. + $str = sprintf($str, $param1, $param2, $param3, $param4); // Replace %s and %d except for FormatXXX strings. } - if ($maxsize) $str=dol_trunc($str, $maxsize); + if ($maxsize) $str = dol_trunc($str, $maxsize); // We replace some HTML tags by __xx__ to avoid having them encoded by htmlentities - $str=str_replace(array('<','>','"',), array('__lt__','__gt__','__quot__'), $str); + $str = str_replace(array('<', '>', '"',), array('__lt__', '__gt__', '__quot__'), $str); // Crypt string into HTML - $str=htmlentities($str, ENT_COMPAT, $this->charset_output); // Do not convert simple quotes in translation (strings in html are enmbraced by "). Use dol_escape_htmltag around text in HTML content + $str = htmlentities($str, ENT_COMPAT, $this->charset_output); // Do not convert simple quotes in translation (strings in html are enmbraced by "). Use dol_escape_htmltag around text in HTML content // Restore HTML tags - $str=str_replace(array('__lt__','__gt__','__quot__'), array('<','>','"',), $str); + $str = str_replace(array('__lt__', '__gt__', '__quot__'), array('<', '>', '"',), $str); return $str; } @@ -682,26 +682,26 @@ class Translate { global $conf; - if (! empty($this->tab_translate[$key])) // Translation is available + if (!empty($this->tab_translate[$key])) // Translation is available { - $str=$this->tab_translate[$key]; + $str = $this->tab_translate[$key]; // Make some string replacement after translation - $replacekey='MAIN_REPLACE_TRANS_'.$this->defaultlang; - if (! empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2 + $replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang; + if (!empty($conf->global->$replacekey)) // Replacement translation variable with string1:newstring1;string2:newstring2 { - $tmparray=explode(';', $conf->global->$replacekey); - foreach($tmparray as $tmp) + $tmparray = explode(';', $conf->global->$replacekey); + foreach ($tmparray as $tmp) { - $tmparray2=explode(':', $tmp); - $str=preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str); + $tmparray2 = explode(':', $tmp); + $str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str); } } - if (! preg_match('/^Format/', $key)) + if (!preg_match('/^Format/', $key)) { //print $str; - $str=sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings. + $str = sprintf($str, $param1, $param2, $param3, $param4, $param5); // Replace %s and %d except for FormatXXX strings. } return $str; @@ -751,8 +751,8 @@ class Translate */ public function convToOutputCharset($str, $pagecodefrom = 'UTF-8') { - if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') $str=utf8_encode($str); - if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') $str=utf8_decode(str_replace('€', chr(128), $str)); + if ($pagecodefrom == 'ISO-8859-1' && $this->charset_output == 'UTF-8') $str = utf8_encode($str); + if ($pagecodefrom == 'UTF-8' && $this->charset_output == 'ISO-8859-1') $str = utf8_decode(str_replace('€', chr(128), $str)); return $str; } @@ -772,21 +772,21 @@ class Translate global $conf; // We scan directory langs to detect available languages - $handle=opendir($langdir."/langs"); - $langs_available=array(); + $handle = opendir($langdir."/langs"); + $langs_available = array(); while ($dir = trim(readdir($handle))) { if (preg_match('/^[a-z]+_[A-Z]+/i', $dir)) { $this->load("languages"); - if (! empty($conf->global->MAIN_LANGUAGES_ALLOWED) && ! in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED)) ) continue; + if (!empty($conf->global->MAIN_LANGUAGES_ALLOWED) && !in_array($dir, explode(',', $conf->global->MAIN_LANGUAGES_ALLOWED))) continue; if ($usecode == 2) { $langs_available[$dir] = $dir; } - if ($usecode == 1 || ! empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) + if ($usecode == 1 || !empty($conf->global->MAIN_SHOW_LANGUAGE_CODE)) { $langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir), $maxlength); } @@ -812,7 +812,7 @@ class Translate { // phpcs:enable // Test si fichier dans repertoire de la langue - foreach($this->dir as $searchdir) + foreach ($this->dir as $searchdir) { if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename))) return true; @@ -844,22 +844,22 @@ class Translate { global $conf; - $newnumber=$number; + $newnumber = $number; - $dirsubstitutions=array_merge(array(), $conf->modules_parts['substitutions']); - foreach($dirsubstitutions as $reldir) + $dirsubstitutions = array_merge(array(), $conf->modules_parts['substitutions']); + foreach ($dirsubstitutions as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); // Check if directory exists - if (! is_dir($newdir)) continue; // We must not use dol_is_dir here, function may not be loaded + if (!is_dir($newdir)) continue; // We must not use dol_is_dir here, function may not be loaded - $fonc='numberwords'; + $fonc = 'numberwords'; if (file_exists($newdir.'/functions_'.$fonc.'.lib.php')) { include_once $newdir.'/functions_'.$fonc.'.lib.php'; - $newnumber=numberwords_getLabelFromNumber($this, $number, $isamount); + $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount); break; } } @@ -891,36 +891,36 @@ class Translate //print 'param: '.$key.'-'.$keydatabase.'-'.$this->trans($key); exit; // Check if a translation is available (this can call getTradFromKey) - $tmp=$this->transnoentitiesnoconv($key); + $tmp = $this->transnoentitiesnoconv($key); if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') { - return $tmp; // Found in language array + return $tmp; // Found in language array } // Check in cache if (isset($this->cache_labels[$tablename][$key])) // Can be defined to 0 or '' { - return $this->cache_labels[$tablename][$key]; // Found in cache + return $this->cache_labels[$tablename][$key]; // Found in cache } $sql = "SELECT ".$fieldlabel." as label"; - $sql.= " FROM ".MAIN_DB_PREFIX.$tablename; - $sql.= " WHERE ".$fieldkey." = '".$db->escape($keyforselect?$keyforselect:$key)."'"; - if ($filteronentity) $sql.= " AND entity IN (" . getEntity($tablename). ')'; + $sql .= " FROM ".MAIN_DB_PREFIX.$tablename; + $sql .= " WHERE ".$fieldkey." = '".$db->escape($keyforselect ? $keyforselect : $key)."'"; + if ($filteronentity) $sql .= " AND entity IN (".getEntity($tablename).')'; dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $this->cache_labels[$tablename][$key]=$obj->label; - else $this->cache_labels[$tablename][$key]=$key; + if ($obj) $this->cache_labels[$tablename][$key] = $obj->label; + else $this->cache_labels[$tablename][$key] = $key; $db->free($resql); return $this->cache_labels[$tablename][$key]; } else { - $this->error=$db->lasterror(); + $this->error = $db->lasterror(); return -1; } } @@ -937,7 +937,7 @@ class Translate */ public function getCurrencyAmount($currency_code, $amount) { - $symbol=$this->getCurrencySymbol($currency_code); + $symbol = $this->getCurrencySymbol($currency_code); if (in_array($currency_code, array('USD'))) return $symbol.$amount; else return $amount.$symbol; @@ -953,22 +953,22 @@ class Translate */ public function getCurrencySymbol($currency_code, $forceloadall = 0) { - $currency_sign = ''; // By default return iso code + $currency_sign = ''; // By default return iso code if (function_exists("mb_convert_encoding")) { - $this->loadCacheCurrencies($forceloadall?'':$currency_code); + $this->loadCacheCurrencies($forceloadall ? '' : $currency_code); - if (isset($this->cache_currencies[$currency_code]) && ! empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) + if (isset($this->cache_currencies[$currency_code]) && !empty($this->cache_currencies[$currency_code]['unicode']) && is_array($this->cache_currencies[$currency_code]['unicode'])) { - foreach($this->cache_currencies[$currency_code]['unicode'] as $unicode) + foreach ($this->cache_currencies[$currency_code]['unicode'] as $unicode) { $currency_sign .= mb_convert_encoding("&#{$unicode};", "UTF-8", 'HTML-ENTITIES'); } } } - return ($currency_sign?$currency_sign:$currency_code); + return ($currency_sign ? $currency_sign : $currency_code); } /** @@ -981,13 +981,13 @@ class Translate { global $db; - if ($this->cache_currencies_all_loaded) return 0; // Cache already loaded for all - if (! empty($currency_code) && isset($this->cache_currencies[$currency_code])) return 0; // Cache already loaded for the currency + if ($this->cache_currencies_all_loaded) return 0; // Cache already loaded for all + if (!empty($currency_code) && isset($this->cache_currencies[$currency_code])) return 0; // Cache already loaded for the currency $sql = "SELECT code_iso, label, unicode"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_currencies"; - $sql.= " WHERE active = 1"; - if (! empty($currency_code)) $sql.=" AND code_iso = '".$db->escape($currency_code)."'"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies"; + $sql .= " WHERE active = 1"; + if (!empty($currency_code)) $sql .= " AND code_iso = '".$db->escape($currency_code)."'"; //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later dol_syslog(get_class($this).'::loadCacheCurrencies', LOG_DEBUG); @@ -995,8 +995,8 @@ class Translate if ($resql) { $this->load("dict"); - $label=array(); - if (! empty($currency_code)) foreach($this->cache_currencies as $key => $val) $label[$key]=$val['label']; // Label in already loaded cache + $label = array(); + if (!empty($currency_code)) foreach ($this->cache_currencies as $key => $val) $label[$key] = $val['label']; // Label in already loaded cache $num = $db->num_rows($resql); $i = 0; @@ -1005,12 +1005,12 @@ class Translate $obj = $db->fetch_object($resql); // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $this->cache_currencies[$obj->code_iso]['label'] = ($obj->code_iso && $this->trans("Currency".$obj->code_iso)!="Currency".$obj->code_iso?$this->trans("Currency".$obj->code_iso):($obj->label!='-'?$obj->label:'')); + $this->cache_currencies[$obj->code_iso]['label'] = ($obj->code_iso && $this->trans("Currency".$obj->code_iso) != "Currency".$obj->code_iso ? $this->trans("Currency".$obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode($obj->unicode, true); $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label']; $i++; } - if (empty($currency_code)) $this->cache_currencies_all_loaded=true; + if (empty($currency_code)) $this->cache_currencies_all_loaded = true; //print count($label).' '.count($this->cache_currencies); // Resort cache @@ -1037,7 +1037,7 @@ class Translate // phpcs:enable $substitutionarray = array(); - foreach($this->tab_translate as $code => $label) { + foreach ($this->tab_translate as $code => $label) { $substitutionarray['lang_'.$code] = $label; $substitutionarray['__('.$code.')__'] = $label; } diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php index 2ac64565e9c..7904d27d17a 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -493,7 +493,7 @@ class Utils } // Clean old files - if (! $errormsg && $keeplastnfiles > 0) + if (!$errormsg && $keeplastnfiles > 0) { $tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC); $i = 0; diff --git a/htdocs/core/customreports.php b/htdocs/core/customreports.php new file mode 100644 index 00000000000..80d88f72203 --- /dev/null +++ b/htdocs/core/customreports.php @@ -0,0 +1,513 @@ + + * + * 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/customreports.php + * \ingroup sellyoursaas + * \brief Page to make custom reports + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php"; +require_once DOL_DOCUMENT_ROOT."/core/class/dolgraph.class.php"; +require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php"; + +// Load traductions files requiredby by page +$langs->loadLangs(array("companies", "bills", "other", "exports")); + +// Get parameters +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) + +$mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : 'graph'; +$objecttype = GETPOST('objecttype', 'aZ09'); +$tabfamily = GETPOST('tabfamily', 'aZ09'); + +if (empty($objecttype)) $objecttype = 'thirdparty'; + +$search_filters = GETPOST('search_filters', 'array'); +$search_measures = GETPOST('search_measures', 'array'); +$search_xaxis = GETPOST('search_xaxis', 'array'); +$search_yaxis = GETPOST('search_yaxis', 'array'); +$search_graph = GETPOST('search_graph', 'none'); + +// Load variable for pagination +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOST('page', 'int'); +if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Protection if external user +if ($user->societe_id > 0) +{ + //accessforbidden(); +} + +$extrafields = new ExtraFields($db); + +$diroutputmassaction = $conf->user->dir_temp.'/'.$user->id.'/customreport'; +$hookmanager->initHooks(array('customreport')); // Note that conf->hooks_modules contains array + +$title = ''; +$picto = ''; +$head = array(); +$object = null; +$ObjectClassName = ''; +$arrayoftype = array( + 'thirdparty' => array('label' => 'ThirdParties', 'ObjectClassName' => 'Societe', 'enabled' => $conf->societe->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"), + 'contact' => array('label' => 'Contacts', 'ObjectClassName' => 'Contact', 'enabled' => $conf->societe->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/contact/class/contact.class.php"), + 'contract' => array('label' => 'Contracts', 'ObjectClassName' => 'Contrat', 'enabled' => $conf->contrat->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php", 'langs'=>'contract'), + 'invoice' => array('label' => 'Invoices', 'ObjectClassName' => 'Facture', 'enabled' => $conf->facture->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"), + 'invoice_template'=>array('label' => 'PredefinedInvoices', 'ObjectClassName' => 'FactureRec', 'enabled' => $conf->facture->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/compta/class/facturerec.class.php"), + 'bom' => array('label' => 'BOM', 'ObjectClassName' => 'Bom', 'enabled' => $conf->bom->enabled), + 'mo' => array('label' => 'MO', 'ObjectClassName' => 'Mo', 'enabled' => $conf->mo->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/mrp/class/mo.class.php"), + 'ticket' => array('label' => 'Ticket', 'ObjectClassName' => 'Ticket', 'enabled' => $conf->ticket->enabled), + 'member' => array('label' => 'Adherent', 'ObjectClassName' => 'Adherent', 'enabled' => $conf->adherent->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php", 'langs'=>'members'), + 'cotisation' => array('label' => 'Subscriptions', 'ObjectClassName' => 'Subscription', 'enabled' => $conf->adherent->enabled, 'ClassPath' => DOL_DOCUMENT_ROOT."/adherents/class/subscription.class.php", 'langs'=>'members'), +); + +// Complete $arrayoftype +$parameters = array('objecttype'=>$objecttype, 'tabfamily'=>$tabfamily); +$reshook = $hookmanager->executeHooks('loadDataForCustomReports', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +elseif (is_array($hookmanager->resArray)) { + if (! empty($hookmanager->resArray['title'])) { // Add entries for tabs + $title = $hookmanager->resArray['title']; + } + if (! empty($hookmanager->resArray['picto'])) { // Add entries for tabs + $picto = $hookmanager->resArray['picto']; + } + if (! empty($hookmanager->resArray['head'])) { // Add entries for tabs + $head = array_merge($head, $hookmanager->resArray['head']); + } + if (! empty($hookmanager->resArray['arrayoftype'])) { // Add entries from hook + foreach($hookmanager->resArray['arrayoftype'] as $key => $val) { + $arrayoftype[$key] = $val; + } + } +} + +if ($objecttype) { + try { + if ($arrayoftype[$objecttype]['langs']) { + $langs->load($arrayoftype[$objecttype]['langs']); + } + if ($arrayoftype[$objecttype]['ClassPath']) { + include_once $arrayoftype[$objecttype]['ClassPath']; + } else { + include_once DOL_DOCUMENT_ROOT."/".$objecttype."/class/".$objecttype.".class.php"; + } + $ObjectClassName = $arrayoftype[$objecttype]['ObjectClassName']; + $object = new $ObjectClassName($db); + } + catch(Exception $e) { + print 'Failed to load class for type '.$objecttype; + } +} + +// Security check +$socid = 0; +if ($user->socid > 0) // Protection if external user +{ + //$socid = $user->socid; + accessforbidden(); +} +$result = restrictedArea($user, $object->element, 0, ''); + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +$search_component_params=array(''); + + +/* + * Actions + */ + + + + + +/* + * View + */ + +$form=new Form($db); + +llxHeader('', $langs->transnoentitiesnoconv('CustomReports'), ''); + +//print_fiche_titre($langs->trans("DoliCloudArea")); + + + +//$head = commande_prepare_head(null); +dol_fiche_head($head, 'customreports', $title, -1, $picto); + + +$tmparray=dol_getdate(dol_now()); +$endyear=$tmparray['year']; +$endmonth=$tmparray['mon']; +$datelastday=dol_get_last_day($endyear, $endmonth, 1); +$startyear=$endyear-2; + +$param = ''; + +$arrayofmesures = array('t.count'=>'Count'); +$arrayofxaxis = array(); +$arrayofyaxis = array(); + +print ''; +print ''; +print ''; + +print '
'; + +// Select object +print '
'; +print '
'.$langs->trans("StatisticsOn").'
'; +print $form->selectarray('objecttype', $arrayoftype, $objecttype, 0, 0, 0, '', 1, 0, 0, '', '', 1); +if (empty($conf->use_javascript_ajax)) print ''; +else { + print ''; +} +print '
'; + + +// Add Filter +print '
'; +print $form->searchComponent(array($object->element => $object->fields), $search_component_params); +print '
'; + +// Measures +print '
'; +foreach($object->fields as $key => $val) { + if ($val['isameasure']) { + $arrayofmesures['t.'.$key.'-sum'] = $langs->trans($val['label']).' ('.$langs->trans("Sum").')'; + $arrayofmesures['t.'.$key.'-average'] = $langs->trans($val['label']).' ('.$langs->trans("Average").')'; + $arrayofmesures['t.'.$key.'-min'] = $langs->trans($val['label']).' ('.$langs->trans("Minimum").')'; + $arrayofmesures['t.'.$key.'-max'] = $langs->trans($val['label']).' ('.$langs->trans("Maximum").')'; + } +} +// Add measure from extrafields +if ($object->isextrafieldmanaged) { + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + if (! empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) { + $arrayofmesures['te.'.$key.'-sum'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' ('.$langs->trans("Sum").')'; + $arrayofmesures['te.'.$key.'-average'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' ('.$langs->trans("Average").')'; + $arrayofmesures['te.'.$key.'-min'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' ('.$langs->trans("Minimum").')'; + $arrayofmesures['te.'.$key.'-max'] = $langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' ('.$langs->trans("Maximum").')'; + } + } +} +print '
'.$langs->trans("Measures").'
'; +print $form->multiselectarray('search_measures', $arrayofmesures, $search_measures, 0, 0, 'minwidth500', 1); +print '
'; + +// XAxis +print '
'; +foreach($object->fields as $key => $val) { + if (! $val['measure']) { + if (in_array($key, array( + 'id', 'ref_int', 'ref_ext', 'rowid', 'entity', 'last_main_doc', 'logo', 'logo_squarred', 'extraparams', + 'parent', 'photo', 'socialnetworks', 'webservices_url', 'webservices_key'))) continue; + if (isset($val['enabled']) && ! dol_eval($val['enabled'], 1)) continue; + if (isset($val['visible']) && ! dol_eval($val['visible'], 1)) continue; + if (preg_match('/^fk_/', $key) && ! preg_match('/^fk_statu/', $key)) continue; + if (preg_match('/^pass/', $key)) continue; + if (in_array($val['type'], array('html', 'text'))) continue; + if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) { + $arrayofxaxis['t.'.$key.'-year'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Year").')', 'position' => $val['position']); + $arrayofxaxis['t.'.$key.'-month'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Month").')', 'position' => $val['position']); + $arrayofxaxis['t.'.$key.'-day'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Day").')', 'position' => $val['position']); + } else { + $arrayofxaxis['t.'.$key] = array('label' => $val['label'], 'position' => (int) $val['position']); + } + } + // Add measure from extrafields + if ($object->isextrafieldmanaged) { + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + if (! empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) { + $arrayofxaxis['te.'.$key] = array('label' => $extrafields->attributes[$object->table_element]['label'][$key], 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key]); + } + } + } +} +$arrayofxaxis = dol_sort_array($arrayofxaxis, 'position'); +$arrayofxaxislabel = array(); +foreach($arrayofxaxis as $key => $val) { + $arrayofxaxislabel[$key] = $val['label']; +} +print '
'.$langs->trans("XAxis").'
'; +print $form->multiselectarray('search_xaxis', $arrayofxaxislabel, $search_xaxis, 0, 0, 'minwidth500', 1); +print '
'; + +// YAxis +if ($mode == 'grid') { + print '
'; + foreach($object->fields as $key => $val) { + if (! $val['measure']) { + if (in_array($key, array('id', 'rowid', 'entity', 'last_main_doc', 'extraparams'))) continue; + if (preg_match('/^fk_/', $key)) continue; + if (in_array($val['type'], array('html', 'text'))) continue; + if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) { + $arrayofyaxis['t.'.$key.'-year'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Year").')', 'position' => $val['position']); + $arrayofyaxis['t.'.$key.'-month'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Month").')', 'position' => $val['position']); + $arrayofyaxis['t.'.$key.'-day'] = array('label' => $langs->trans($val['label']).' ('.$langs->trans("Day").')', 'position' => $val['position']); + } else { + $arrayofyaxis['t.'.$key] = array('label' => $val['label'], 'position' => (int) $val['position']); + } + } + // Add measure from extrafields + if ($object->isextrafieldmanaged) { + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + if (! empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) { + $arrayofyaxis['te.'.$key] = array('label' => $extrafields->attributes[$object->table_element]['label'][$key], 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key]); + } + } + } + } + $arrayofyaxis = dol_sort_array($arrayofyaxis, 'position'); + $arrayofyaxislabel = array(); + foreach($arrayofyaxis as $key => $val) { + $arrayofyaxislabel[$key] = $val['label']; + } + print '
'.$langs->trans("YAxis").'
'; + print $form->multiselectarray('search_yaxis', $arrayofyaxislabel, $search_yaxis, 0, 0, 'minwidth100', 1); + print '
'; +} + +if ($mode == 'graph') { + print '
'; + $arrayofgraphs = array('bars', 'line'); // also 'pies' + print '
'.$langs->trans("Graph").'
'; + print $form->selectarray('search_graph', $arrayofgraphs, $search_graph, 0, 0, 'minwidth100', 1); + print '
'; +} +print '
'; +print ''; +print '
'; +print '
'; +print ''; + + +// Generate the SQL request +$sql = ''; +if (! empty($search_measures) && ! empty($search_xaxis)) +{ + $fieldid = 'rowid'; + + $sql = 'SELECT '; + foreach($search_xaxis as $key => $val) { + if (preg_match('/\-year$/', $val)) { + $tmpval = preg_replace('/\-year$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y') as x_".$key.', '; + } elseif (preg_match('/\-month$/', $val)) { + $tmpval = preg_replace('/\-month$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m') as x_".$key.', '; + } elseif (preg_match('/\-day$/', $val)) { + $tmpval = preg_replace('/\-day$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d') as x_".$key.', '; + } + else $sql .= $val.' as x_'.$key.', '; + } + foreach($search_measures as $key => $val) { + if ($val == 't.count') $sql .= 'COUNT(t.'.$fieldid.') as y_'.$key.', '; + elseif (preg_match('/\-sum$/', $val)) { + $tmpval = preg_replace('/\-sum$/', '', $val); + $sql .= 'SUM('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; + } + elseif (preg_match('/\-average$/', $val)) { + $tmpval = preg_replace('/\-average$/', '', $val); + $sql .= 'AVG('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; + } + elseif (preg_match('/\-min$/', $val)) { + $tmpval = preg_replace('/\-min$/', '', $val); + $sql .= 'MIN('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; + } + elseif (preg_match('/\-max$/', $val)) { + $tmpval = preg_replace('/\-max$/', '', $val); + $sql .= 'MAX('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; + } + } + $sql = preg_replace('/,\s*$/', '', $sql); + $sql .= ' FROM '.MAIN_DB_PREFIX.$object->table_element.' as t'; + // Add measure from extrafields + if ($object->isextrafieldmanaged) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.$object->table_element.'_extrafields as te ON te.fk_object = t.'.$fieldid; + } + if ($object->ismultientitymanaged) { + if ($object->ismultientitymanaged == 1) { + // Nothing here + } else { + $tmparray = explode('@', $object->ismultientitymanaged); + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON t.'.$tmparray[0].' = parenttable.rowid'; + $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')'; + } + } + $sql .= ' WHERE 1 = 1'; + if ($object->ismultientitymanaged == 1) { + $sql .= ' AND entity IN ('.getEntity($object->element).')'; + } + foreach($search_filters as $key => $val) { + // TODO + } + $sql .= ' GROUP BY '; + foreach($search_xaxis as $key => $val) { + if (preg_match('/\-year$/', $val)) { + $tmpval = preg_replace('/\-year$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), "; + } elseif (preg_match('/\-month$/', $val)) { + $tmpval = preg_replace('/\-month$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), "; + } elseif (preg_match('/\-day$/', $val)) { + $tmpval = preg_replace('/\-day$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), "; + } + else $sql .= $val.', '; + } + $sql = preg_replace('/,\s*$/', '', $sql); + $sql .= ' ORDER BY '; + foreach($search_xaxis as $key => $val) { + if (preg_match('/\-year$/', $val)) { + $tmpval = preg_replace('/\-year$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y'), "; + } elseif (preg_match('/\-month$/', $val)) { + $tmpval = preg_replace('/\-month$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m'), "; + } elseif (preg_match('/\-day$/', $val)) { + $tmpval = preg_replace('/\-day$/', '', $val); + $sql .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d'), "; + } + else $sql .= $val.', '; + } + $sql = preg_replace('/,\s*$/', '', $sql); +} + + +$legend=array(); +foreach($search_measures as $key => $val) { + $legend[] = $langs->trans($arrayofmesures[$val]); +} + +// Execute the SQL request +$totalnbofrecord = 0; +$data = array(); +if ($sql) { + $resql = $db->query($sql); + if (! $resql) { + dol_print_error($db); + } + + while($obj = $db->fetch_object($resql)) { + // $this->data = array(array(0=>'labelxA',1=>yA1,...,n=>yAn), array('labelxB',yB1,...yBn)); // or when there is n series to show for each x + foreach($search_xaxis as $xkey => $xval) { + $fieldforxkey = 'x_'.$xkey; + $xlabel = $obj->$fieldforxkey; + $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval); + if (! empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) { + $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey]; + } + $xarray = array(0 => (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : $langs->trans("NotDefined"))); + foreach($search_measures as $key => $val) { + $fieldfory = 'y_'.$key; + $xarray[] = $obj->$fieldfory; + } + $data[] = $xarray; + } + } + + $totalnbofrecord = count($data); +} + + +print '
'; + + +if ($mode == 'grid') { + // TODO +} + +if ($mode == 'graph') { + $WIDTH = '80%'; + $HEIGHT = 200; + + // Show graph + $px1 = new DolGraph(); + $mesg = $px1->isGraphKo(); + if (! $mesg) + { + $px1->SetData($data); + unset($data); + + $arrayoftypes = array(); + foreach($search_measures as $key => $val) { + $arrayoftypes[] = $search_graph; + } + + $px1->SetLegend($legend); + $px1->SetMinValue($px1->GetFloorMinValue()); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetWidth($WIDTH); + $px1->SetHeight($HEIGHT); + $px1->SetYLabel($langs->trans("Y")); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + $px1->SetType($arrayoftypes); + $px1->mode='depth'; + $px1->SetTitle(''); + + $dir=$conf->user->dir_temp; + dol_mkdir($dir); + $filenamenb = $dir.'/customreport_'.$object->element.'.png'; + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=user&file=customreport_'.$object->element.'.png'; + + $px1->draw($filenamenb, $fileurlnb); + + print $px1->show($totalnbofrecord ? 0 : $langs->trans("SelectYourGraphOptionsFirst")); + } +} + +if ($sql) { + // Show admin info + print '
'.info_admin($langs->trans("SQLUsedForExport").':
'.$sql); +} + +print '
'; + +dol_fiche_end(); + + +// End of page +llxFooter(); + +$db->close(); diff --git a/htdocs/core/db/mssql.class.php b/htdocs/core/db/mssql.class.php index 2c489b25181..79d26949394 100644 --- a/htdocs/core/db/mssql.class.php +++ b/htdocs/core/db/mssql.class.php @@ -41,7 +41,7 @@ class DoliDBMssql extends DoliDB public $forcecollate='latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value //! Version min database const VERSIONMIN='2000'; - /** @var resource Resultset of last query */ + /** @var boolean|resource Resultset of last query */ private $_results; /** @@ -336,6 +336,8 @@ class DoliDBMssql extends DoliDB $query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/", "$1[$2]$3", $query); + $original_query=''; + if ($type=="auto" || $type='dml') { $query=preg_replace('/AUTO_INCREMENT/i', 'IDENTITY', $query); @@ -345,7 +347,6 @@ class DoliDBMssql extends DoliDB $query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i', "$1VARCHAR(MAX)$3", $query); $matches=array(); - $original_query=''; if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query, $matches)) { $original_query=$query; @@ -356,10 +357,12 @@ class DoliDBMssql extends DoliDB $fields_clear=array_map('trim', $fields); $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear); $query_comp=array(); - foreach($infos as $fld) { - if ($fld->IS_NULLABLE == 'YES') { - $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL"; - } + if (is_array($infos)) { + foreach($infos as $fld) { + if ($fld->IS_NULLABLE == 'YES') { + $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL"; + } + } } if (! empty($query_comp)) $query.=" WHERE ".implode(" AND ", $query_comp); @@ -784,7 +787,8 @@ class DoliDBMssql extends DoliDB public function DDLListTables($database, $table = '') { // phpcs:enable - $this->_results = mssql_list_tables($database, $this->db); + $v = mssql_query("Select name from sysobjects where type like 'u'", $this->db); + $this->_results = mssql_fetch_array($v); return $this->_results; } @@ -825,6 +829,10 @@ class DoliDBMssql extends DoliDB // phpcs:enable // FIXME: $fulltext_keys parameter is unused + $sqlfields = array(); + $sqluq = array(); + $sqlk = array(); + // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment'); $sql = "create table ".$table."("; diff --git a/htdocs/core/extrafieldsinexport.inc.php b/htdocs/core/extrafieldsinexport.inc.php index e9d10138d1e..4f85610e657 100644 --- a/htdocs/core/extrafieldsinexport.inc.php +++ b/htdocs/core/extrafieldsinexport.inc.php @@ -8,67 +8,67 @@ if (empty($keyforselect) || empty($keyforelement) || empty($keyforaliasextra)) } // Add extra fields -$sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.') ORDER BY pos ASC'; +$sql = "SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.') ORDER BY pos ASC'; //print $sql; -$resql=$this->db->query($sql); +$resql = $this->db->query($sql); if ($resql) // This can fail when class is used on old database (during migration for example) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $fieldname=$keyforaliasextra.'.'.$obj->name; - $fieldlabel=ucfirst($obj->label); - $typeFilter="Text"; - $typefield=preg_replace('/\(.*$/', '', $obj->type); // double(24,8) -> double + $fieldname = $keyforaliasextra.'.'.$obj->name; + $fieldlabel = ucfirst($obj->label); + $typeFilter = "Text"; + $typefield = preg_replace('/\(.*$/', '', $obj->type); // double(24,8) -> double switch ($typefield) { case 'int': case 'integer': case 'double': case 'price': - $typeFilter="Numeric"; + $typeFilter = "Numeric"; break; case 'date': case 'datetime': case 'timestamp': - $typeFilter="Date"; + $typeFilter = "Date"; break; case 'boolean': - $typeFilter="Boolean"; + $typeFilter = "Boolean"; break; case 'select': - if (! empty($conf->global->EXPORT_LABEL_FOR_SELECT)) + if (!empty($conf->global->EXPORT_LABEL_FOR_SELECT)) { - $tmpparam=unserialize($obj->param); // $tmpparam may be array with 'options' = array(key1=>val1, key2=>val2 ...) + $tmpparam = unserialize($obj->param); // $tmpparam may be array with 'options' = array(key1=>val1, key2=>val2 ...) if ($tmpparam['options'] && is_array($tmpparam['options'])) { - $typeFilter="Select:".$obj->param; + $typeFilter = "Select:".$obj->param; } } break; case 'sellist': - $tmp=''; - $tmpparam=unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null + $tmp = ''; + $tmpparam = unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null if ($tmpparam['options'] && is_array($tmpparam['options'])) { - $tmpkeys=array_keys($tmpparam['options']); - $tmp=array_shift($tmpkeys); + $tmpkeys = array_keys($tmpparam['options']); + $tmp = array_shift($tmpkeys); } - if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp; + if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter = "List:".$tmp; break; } - if ($obj->type!='separate') + if ($obj->type != 'separate') { // If not a computed field if (empty($obj->fieldcomputed)) { - $this->export_fields_array[$r][$fieldname]=$fieldlabel; - $this->export_TypeFields_array[$r][$fieldname]=$typeFilter; - $this->export_entities_array[$r][$fieldname]=$keyforelement; + $this->export_fields_array[$r][$fieldname] = $fieldlabel; + $this->export_TypeFields_array[$r][$fieldname] = $typeFilter; + $this->export_entities_array[$r][$fieldname] = $keyforelement; } // If this is a computed field else { - $this->export_fields_array[$r][$fieldname]=$fieldlabel; - $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute'; - $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed; - $this->export_entities_array[$r][$fieldname]=$keyforelement; + $this->export_fields_array[$r][$fieldname] = $fieldlabel; + $this->export_TypeFields_array[$r][$fieldname] = $typeFilter.'Compute'; + $this->export_special_array[$r][$fieldname] = $obj->fieldcomputed; + $this->export_entities_array[$r][$fieldname] = $keyforelement; } } } diff --git a/htdocs/core/lib/date.lib.php b/htdocs/core/lib/date.lib.php index 8fb32bb2f37..e7043a1798a 100644 --- a/htdocs/core/lib/date.lib.php +++ b/htdocs/core/lib/date.lib.php @@ -961,3 +961,69 @@ function monthArray($outputlangs, $short = 0) return $montharray; } +/** + * Return array of week numbers. + + * + * @param int $month Month number + * @param int $year Year number + * @return array Week numbers + */ +function getWeekNumbersOfMonth($month, $year) +{ + $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year); + $TWeek = array(); + for($day = 1; $day < $nb_days; $day++) { + $week_number = getWeekNumber($day, $month, $year); + $TWeek[$week_number] = $week_number; + } + return $TWeek; +} +/** + * Return array of first day of weeks. + + * + * @param array $TWeek array of week numbers + * @param int $year Year number + * @return array First day of week + */ +function getFirstDayOfEachWeek($TWeek, $year) +{ + $TFirstDayOfWeek = array(); + foreach($TWeek as $weekNb) { + if(in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') $year++;//Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année + $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb)); + } + return $TFirstDayOfWeek; +} +/** + * Return array of last day of weeks. + + * + * @param array $TWeek array of week numbers + * @param int $year Year number + * @return array Last day of week + */ +function getLastDayOfEachWeek($TWeek, $year) +{ + $TLastDayOfWeek = array(); + foreach($TWeek as $weekNb) { + $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days')); + } + return $TLastDayOfWeek; +} +/** + * Return week number. + + * + * @param int $day Day number + * @param int $month Month number + * @param int $year Year number + * @return int Week number + */ +function getWeekNumber($day, $month, $year) +{ + $date = new DateTime($year.'-'.$month.'-'.$day); + $week = $date->format("W"); + return $week; +} diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index 0051d28caf3..38264ac9029 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -195,7 +195,7 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl closedir($dir); // Obtain a list of columns - if (! empty($sortcriteria) && $sortorder) + if (!empty($sortcriteria) && $sortorder) { $file_list = dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ? 'asc' : 'desc')); } @@ -1435,21 +1435,21 @@ function dol_meta_create($object) if (is_dir($dir)) { $nblines = count($object->lines); - $client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town; - $meta = "REFERENCE=\"" . $object->ref . "\" - DATE=\"" . dol_print_date($object->date, '') . "\" - NB_ITEMS=\"" . $nblines . "\" - CLIENT=\"" . $client . "\" - AMOUNT_EXCL_TAX=\"" . $object->total_ht . "\" - AMOUNT=\"" . $object->total_ttc . "\"\n"; + $client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town; + $meta = "REFERENCE=\"".$object->ref."\" + DATE=\"" . dol_print_date($object->date, '')."\" + NB_ITEMS=\"" . $nblines."\" + CLIENT=\"" . $client."\" + AMOUNT_EXCL_TAX=\"" . $object->total_ht."\" + AMOUNT=\"" . $object->total_ttc."\"\n"; - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { //Pour les articles - $meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\" - ITEM_" . $i . "_AMOUNT_WO_TAX=\"" . $object->lines[$i]->total_ht . "\" - ITEM_" . $i . "_VAT=\"" .$object->lines[$i]->tva_tx . "\" - ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n", "", nl2br($object->lines[$i]->desc)) . "\" + $meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\" + ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\" + ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\" + ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\" "; } } @@ -1543,21 +1543,21 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess for ($i = 0; $i < $nbfile; $i++) { // Define $destfull (path to file including filename) and $destfile (only filename) - $destfull=$upload_dir . "/" . $TFile['name'][$i]; - $destfile=$TFile['name'][$i]; + $destfull = $upload_dir."/".$TFile['name'][$i]; + $destfile = $TFile['name'][$i]; if ($savingdocmask) { - $destfull=$upload_dir . "/" . preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask); - $destfile=preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask); + $destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask); + $destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask); } // dol_sanitizeFileName the file name and lowercase extension $info = pathinfo($destfull); - $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension']!='' ? ('.'.strtolower($info['extension'])) : '')); + $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : '')); $info = pathinfo($destfile); - $destfile = dol_sanitizeFileName($info['filename'].($info['extension']!='' ? ('.'.strtolower($info['extension'])) : '')); + $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : '')); // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because // this function is also applied when we make try to download file (by the GETPOST(filename, 'alphanohtml') call). @@ -1845,15 +1845,15 @@ function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '' $ret = $image->setImageFormat($ext); if ($ret) { - if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext; + if (empty($fileoutput)) $fileoutput = $fileinput.".".$ext; $count = $image->getNumberImages(); - if (! dol_is_file($fileoutput) || is_writeable($fileoutput)) + if (!dol_is_file($fileoutput) || is_writeable($fileoutput)) { try { $ret = $image->writeImages($fileoutput, true); } - catch(Exception $e) + catch (Exception $e) { dol_syslog($e->getMessage(), LOG_WARNING); } @@ -1896,20 +1896,20 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring { global $conf; - $foundhandler=0; + $foundhandler = 0; try { dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile); $data = implode("", file(dol_osencode($inputfile))); - if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); } - elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); } + if ($mode == 'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); } + elseif ($mode == 'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); } elseif ($mode == 'zip') { - if (class_exists('ZipArchive') && ! empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) + if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) { - $foundhandler=1; + $foundhandler = 1; $rootPath = realpath($inputfile); @@ -1917,7 +1917,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring $zip = new ZipArchive; if ($zip->open($outputfile, ZipArchive::CREATE) !== true) { - $errorstring="dol_compress_file failure - Failed to open file ".$outputfile."\n"; + $errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n"; dol_syslog($errorstring, LOG_ERR); global $errormsg; @@ -1956,7 +1956,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring if (defined('ODTPHP_PATHTOPCLZIP')) { - $foundhandler=1; + $foundhandler = 1; include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; $archive = new PclZip($outputfile); @@ -1965,7 +1965,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring if ($result === 0) { global $errormsg; - $errormsg=$archive->errorInfo(true); + $errormsg = $archive->errorInfo(true); if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) { @@ -2007,7 +2007,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring { global $langs, $errormsg; $langs->load("errors"); - $errormsg=$langs->trans("ErrorFailedToWriteInDir"); + $errormsg = $langs->trans("ErrorFailedToWriteInDir"); $errorstring = "Failed to open file ".$outputfile; dol_syslog($errorstring, LOG_ERR); @@ -2087,22 +2087,22 @@ function dol_uncompress($inputfile, $outputdir) */ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '') { - $foundhandler=0; + $foundhandler = 0; dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode); - if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile))) + if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) { global $langs, $errormsg; $langs->load("errors"); - $errormsg=$langs->trans("ErrorFailedToWriteInDir", $outputfile); + $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile); return -3; } try { - if ($mode == 'gz') { $foundhandler=0; } - elseif ($mode == 'bz') { $foundhandler=0; } + if ($mode == 'gz') { $foundhandler = 0; } + elseif ($mode == 'bz') { $foundhandler = 0; } elseif ($mode == 'zip') { /*if (defined('ODTPHP_PATHTOPCLZIP')) @@ -2124,11 +2124,11 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = // Initialize archive object $zip = new ZipArchive(); $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE); - if (! $result) + if (!$result) { global $langs, $errormsg; $langs->load("errors"); - $errormsg=$langs->trans("ErrorFailedToWriteInFile", $outputfile); + $errormsg = $langs->trans("ErrorFailedToWriteInFile", $outputfile); return -4; } @@ -2148,7 +2148,7 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = $filePath = $file->getRealPath(); $relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr($filePath, strlen($inputdir) + 1); - if (empty($excludefiles) || ! preg_match($excludefiles, $filePath)) + if (empty($excludefiles) || !preg_match($excludefiles, $filePath)) { // Add current file to archive $zip->addFile($filePath, $relativePath); @@ -2219,267 +2219,267 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, global $conf, $db, $user; global $dolibarr_main_data_root, $dolibarr_main_document_root_alt; - if (! is_object($fuser)) $fuser=$user; + if (!is_object($fuser)) $fuser = $user; if (empty($modulepart)) return 'ErrorBadParameter'; if (empty($entity)) { - if (empty($conf->multicompany->enabled)) $entity=1; - else $entity=0; + if (empty($conf->multicompany->enabled)) $entity = 1; + else $entity = 0; } // Fix modulepart - if ($modulepart == 'users') $modulepart='user'; + if ($modulepart == 'users') $modulepart = 'user'; dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity); // We define $accessallowed and $sqlprotectagainstexternals - $accessallowed=0; - $sqlprotectagainstexternals=''; - $ret=array(); + $accessallowed = 0; + $sqlprotectagainstexternals = ''; + $ret = array(); // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10' - if (empty($refname)) $refname=basename(dirname($original_file)."/"); + if (empty($refname)) $refname = basename(dirname($original_file)."/"); // Define possible keys to use for permission check - $lire='lire'; $read='read'; $download='download'; + $lire = 'lire'; $read = 'read'; $download = 'download'; if ($mode == 'write') { - $lire='creer'; $read='write'; $download='upload'; + $lire = 'creer'; $read = 'write'; $download = 'upload'; } // Wrapping for miscellaneous medias files if ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) { if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); - $accessallowed=1; - $original_file=$conf->medias->multidir_output[$entity].'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->medias->multidir_output[$entity].'/'.$original_file; } // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) { - $accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file))); - $original_file=$dolibarr_main_data_root.'/'.$original_file; + $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file))); + $original_file = $dolibarr_main_data_root.'/'.$original_file; } // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) { - $accessallowed=($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file))); - $original_file=$dolibarr_main_data_root.'/doctemplates/websites/'.$original_file; + $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file))); + $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file; } // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) { // Dir for custom dirs - $tmp=explode(',', $dolibarr_main_document_root_alt); + $tmp = explode(',', $dolibarr_main_document_root_alt); $dirins = $tmp[0]; - $accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file))); - $original_file=$dirins.'/'.$original_file; + $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file))); + $original_file = $dirins.'/'.$original_file; } // Wrapping for some images elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) { - $accessallowed=1; - $original_file=$conf->mycompany->dir_output.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->mycompany->dir_output.'/'.$original_file; } // Wrapping for users photos elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) { - $accessallowed=1; - $original_file=$conf->user->dir_output.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->user->dir_output.'/'.$original_file; } // Wrapping for members photos elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output)) { - $accessallowed=1; - $original_file=$conf->adherent->dir_output.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->adherent->dir_output.'/'.$original_file; } // Wrapping pour les apercu factures elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity])) { - if ($fuser->rights->facture->{$lire}) $accessallowed=1; - $original_file=$conf->facture->multidir_output[$entity].'/'.$original_file; + if ($fuser->rights->facture->{$lire}) $accessallowed = 1; + $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file; } // Wrapping pour les apercu propal elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) { - if ($fuser->rights->propale->{$lire}) $accessallowed=1; - $original_file=$conf->propal->multidir_output[$entity].'/'.$original_file; + if ($fuser->rights->propale->{$lire}) $accessallowed = 1; + $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file; } // Wrapping pour les apercu commande elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity])) { - if ($fuser->rights->commande->{$lire}) $accessallowed=1; - $original_file=$conf->commande->multidir_output[$entity].'/'.$original_file; + if ($fuser->rights->commande->{$lire}) $accessallowed = 1; + $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file; } // Wrapping pour les apercu intervention elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) { - if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1; - $original_file=$conf->ficheinter->dir_output.'/'.$original_file; + if ($fuser->rights->ficheinter->{$lire}) $accessallowed = 1; + $original_file = $conf->ficheinter->dir_output.'/'.$original_file; } // Wrapping pour les apercu conat elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output)) { - if ($fuser->rights->contrat->{$lire}) $accessallowed=1; - $original_file=$conf->contrat->dir_output.'/'.$original_file; + if ($fuser->rights->contrat->{$lire}) $accessallowed = 1; + $original_file = $conf->contrat->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier proposal elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) { - if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1; - $original_file=$conf->supplier_proposal->dir_output.'/'.$original_file; + if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed = 1; + $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier order elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) { - if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file; + if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1; + $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) { - if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file; + if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1; + $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) { - if ($fuser->rights->expensereport->{$lire}) $accessallowed=1; - $original_file=$conf->expensereport->dir_output.'/'.$original_file; + if ($fuser->rights->expensereport->{$lire}) $accessallowed = 1; + $original_file = $conf->expensereport->dir_output.'/'.$original_file; } // Wrapping pour les images des stats propales elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) { - if ($fuser->rights->propale->{$lire}) $accessallowed=1; - $original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file; + if ($fuser->rights->propale->{$lire}) $accessallowed = 1; + $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file; } // Wrapping pour les images des stats commandes elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp)) { - if ($fuser->rights->commande->{$lire}) $accessallowed=1; - $original_file=$conf->commande->dir_temp.'/'.$original_file; + if ($fuser->rights->commande->{$lire}) $accessallowed = 1; + $original_file = $conf->commande->dir_temp.'/'.$original_file; } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) { - if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file; + if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1; + $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats factures elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp)) { - if ($fuser->rights->facture->{$lire}) $accessallowed=1; - $original_file=$conf->facture->dir_temp.'/'.$original_file; + if ($fuser->rights->facture->{$lire}) $accessallowed = 1; + $original_file = $conf->facture->dir_temp.'/'.$original_file; } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) { - if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file; + if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1; + $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats expeditions elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) { - if ($fuser->rights->expedition->{$lire}) $accessallowed=1; - $original_file=$conf->expedition->dir_temp.'/'.$original_file; + if ($fuser->rights->expedition->{$lire}) $accessallowed = 1; + $original_file = $conf->expedition->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats expeditions elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) { - if ($fuser->rights->deplacement->{$lire}) $accessallowed=1; - $original_file=$conf->deplacement->dir_temp.'/'.$original_file; + if ($fuser->rights->deplacement->{$lire}) $accessallowed = 1; + $original_file = $conf->deplacement->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats expeditions elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp)) { - if ($fuser->rights->adherent->{$lire}) $accessallowed=1; - $original_file=$conf->adherent->dir_temp.'/'.$original_file; + if ($fuser->rights->adherent->{$lire}) $accessallowed = 1; + $original_file = $conf->adherent->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats produits elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) { - if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1; - $original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file; + if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed = 1; + $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file; } // Wrapping for taxes elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output)) { - if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1; - $original_file=$conf->tax->dir_output.'/'.$original_file; + if ($fuser->rights->tax->charges->{$lire}) $accessallowed = 1; + $original_file = $conf->tax->dir_output.'/'.$original_file; } // Wrapping for events elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) { - if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1; - $original_file=$conf->agenda->dir_output.'/'.$original_file; + if ($fuser->rights->agenda->myactions->{$read}) $accessallowed = 1; + $original_file = $conf->agenda->dir_output.'/'.$original_file; } // Wrapping for categories elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output)) { if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided'); - if ($fuser->rights->categorie->{$lire}) $accessallowed=1; - $original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file; + if ($fuser->rights->categorie->{$lire}) $accessallowed = 1; + $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file; } // Wrapping pour les prelevements elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) { - if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed=1; - $original_file=$conf->prelevement->dir_output.'/'.$original_file; + if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed = 1; + $original_file = $conf->prelevement->dir_output.'/'.$original_file; } // Wrapping pour les graph energie elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) { - $accessallowed=1; - $original_file=$conf->stock->dir_temp.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->stock->dir_temp.'/'.$original_file; } // Wrapping pour les graph fournisseurs elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) { - $accessallowed=1; - $original_file=$conf->fournisseur->dir_temp.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->fournisseur->dir_temp.'/'.$original_file; } // Wrapping pour les graph des produits elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) { - $accessallowed=1; - $original_file=$conf->product->multidir_temp[$entity].'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file; } // Wrapping pour les code barre elseif ($modulepart == 'barcode') { - $accessallowed=1; + $accessallowed = 1; // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk. //$original_file=$conf->barcode->dir_temp.'/'.$original_file; - $original_file=''; + $original_file = ''; } // Wrapping pour les icones de background des mailings elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) { - $accessallowed=1; - $original_file=$conf->mailing->dir_temp.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->mailing->dir_temp.'/'.$original_file; } // Wrapping pour le scanner elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) { - $accessallowed=1; - $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; } // Wrapping pour les images fckeditor elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) { - $accessallowed=1; - $original_file=$conf->fckeditor->dir_output.'/'.$original_file; + $accessallowed = 1; + $original_file = $conf->fckeditor->dir_output.'/'.$original_file; } // Wrapping for users elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) { - $canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire}); - if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card + $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire}); + if ($fuser->id == (int) $refname) { $canreaduser = 1; } // A user can always read its own card if ($canreaduser || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->user->dir_output.'/'.$original_file; + $original_file = $conf->user->dir_output.'/'.$original_file; } // Wrapping for third parties @@ -2510,9 +2510,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->facture->multidir_output[$entity].'/'.$original_file; + $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } // Wrapping for mass actions @@ -2520,81 +2520,81 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_orders') { if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_sendings') { if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_invoices') { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_expensereport') { if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_interventions') { if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) { if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_supplier_order') { if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_supplier_invoice') { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) { if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + $original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } // Wrapping for interventions @@ -2634,9 +2634,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->commande->multidir_output[$entity].'/'.$original_file; + $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } @@ -2676,9 +2676,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, { if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) { - $accessallowed=1; + $accessallowed = 1; } - $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file; + $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file; $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity; } // Wrapping pour les rapport de paiements @@ -2912,6 +2912,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, if ($fuser->admin) $accessallowed = 1; // If user is admin // Define $accessallowed + $reg = array(); if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) { if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index b05cc41ea5d..38b5a2d2a2d 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -885,7 +885,7 @@ function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1) function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1) { $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°'); - return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); + return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars); } /** @@ -2114,7 +2114,7 @@ function dol_now($mode = 'gmt') $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time $ret = (int) (dol_now('gmt') + ($tzsecond * 3600)); } - /*else if ($mode == 'tzref') // Time for now with parent company timezone is added + /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added { require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time @@ -3165,7 +3165,6 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ } elseif ($pictowithouttext == 'bank') { $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext]; - $facolor = '#444'; } elseif ($pictowithouttext == 'stats') { $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext]; @@ -4202,7 +4201,8 @@ function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pict if ($picto == 'setup') $picto = 'generic'; $return .= "\n"; - $return .= ''; // maring bottom must be same than into print_barre_list + $return .= '
'; // maring bottom must be same than into print_barre_list + $return .= ''; if ($picto) $return .= ''; $return .= ''; $texte .= ''; $texte .= ''; + print ''; } if (!empty($arrayfields['l.ref']['checked'])) { @@ -403,7 +428,16 @@ if ($resql) if (!empty($arrayfields['l.date_delivery']['checked'])) { // Date received - print ''; + print ''; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index cbca46576a1..79e418206a5 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -389,7 +389,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link); // Rebuild pdf @@ -509,7 +509,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $dateRefusEx = explode(" ", $object->date_refuse); $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link); @@ -635,7 +635,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); // Rebuilt pdf @@ -755,7 +755,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link); // Rebuilt pdf @@ -885,7 +885,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link); // Rebuilt pdf @@ -1111,7 +1111,7 @@ if (empty($reshook)) // CONTENT $link = $urlwithroot.'/expensereport/card.php?id='.$object->id; - $link = '' . $link . ''; + $link = ''.$link.''; $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link); // Generate pdf before attachment diff --git a/htdocs/expensereport/class/expensereportstats.class.php b/htdocs/expensereport/class/expensereportstats.class.php index 9c614e4953c..f400d5e4277 100644 --- a/htdocs/expensereport/class/expensereportstats.class.php +++ b/htdocs/expensereport/class/expensereportstats.class.php @@ -22,8 +22,8 @@ * \ingroup expensereport * \brief Fichier de la classe de gestion des stats des expensereport et notes de frais */ -require_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; -require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; /** * Classe permettant la gestion des stats des expensereports et notes de frais @@ -61,29 +61,29 @@ class ExpenseReportStats extends Stats $this->socid = $socid; $this->userid = $userid; - $object=new ExpenseReport($this->db); + $object = new ExpenseReport($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as e"; - $this->field='total_ht'; + $this->field = 'total_ht'; //$this->where = " e.fk_statut > 0"; //$this->where.= " AND e.date_valid > '2000-01-01'"; // To filter only correct "valid date". If date is invalid, the group by on it will fails. Launch a repair.php if you have. - $this->where.= ' e.entity IN ('.getEntity('expensereport').')'; + $this->where .= ' e.entity IN ('.getEntity('expensereport').')'; //$this->where.= " AND entity = ".$conf->entity; if ($this->socid) { - $this->where.=" AND e.fk_soc = ".$this->socid; + $this->where .= " AND e.fk_soc = ".$this->socid; } // Only me and subordinates if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { $childids = $user->getAllChildIds(); - $childids[]=$user->id; - $this->where.=" AND e.fk_user_author IN (".(join(',', $childids)).")"; + $childids[] = $user->id; + $this->where .= " AND e.fk_user_author IN (".(join(',', $childids)).")"; } - if ($this->userid > 0) $this->where.=' AND e.fk_user_author = '.$this->userid; + if ($this->userid > 0) $this->where .= ' AND e.fk_user_author = '.$this->userid; } @@ -95,9 +95,9 @@ class ExpenseReportStats extends Stats public function getNbByYear() { $sql = "SELECT YEAR(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)"; - $sql.= " FROM ".$this->from; - $sql.= " GROUP BY dm DESC"; - $sql.= " WHERE ".$this->where; + $sql .= " FROM ".$this->from; + $sql .= " GROUP BY dm DESC"; + $sql .= " WHERE ".$this->where; return $this->_getNbByYear($sql); } @@ -113,13 +113,13 @@ class ExpenseReportStats extends Stats public function getNbByMonth($year, $format = 0) { $sql = "SELECT MONTH(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)"; - $sql.= " FROM ".$this->from; - $sql.= " WHERE YEAR(e.".$this->datetouse.") = ".$year; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + $sql .= " WHERE YEAR(e.".$this->datetouse.") = ".$year; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getNbByMonth($year, $sql, $format); + $res = $this->_getNbByMonth($year, $sql, $format); //var_dump($res);print '
'; return $res; } @@ -135,13 +135,13 @@ class ExpenseReportStats extends Stats public function getAmountByMonth($year, $format = 0) { $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.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $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 .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getAmountByMonth($year, $sql, $format); + $res = $this->_getAmountByMonth($year, $sql, $format); //var_dump($res);print '
'; return $res; } @@ -155,11 +155,11 @@ class ExpenseReportStats extends Stats public function getAverageByMonth($year) { $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.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $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 .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getAverageByMonth($year, $sql); } @@ -172,10 +172,10 @@ class ExpenseReportStats extends Stats public function getAllByYear() { $sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg"; - $sql.= " FROM ".$this->from; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY year"; - $sql.= $this->db->order('year', 'DESC'); + $sql .= " FROM ".$this->from; + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY year"; + $sql .= $this->db->order('year', 'DESC'); return $this->_getAllByYear($sql); } diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php index b43fddad60d..78d8ea09166 100644 --- a/htdocs/exports/class/export.class.php +++ b/htdocs/exports/class/export.class.php @@ -35,27 +35,27 @@ class Export */ public $db; - public $array_export_code=array(); // Tableau de "idmodule_numlot" - public $array_export_module=array(); // Tableau de "nom de modules" - public $array_export_label=array(); // Tableau de "libelle de lots" - public $array_export_sql_start=array(); // Tableau des "requetes sql" - public $array_export_sql_end=array(); // Tableau des "requetes sql" - public $array_export_sql_order=array(); // Tableau des "requetes sql" + public $array_export_code = array(); // Tableau de "idmodule_numlot" + public $array_export_module = array(); // Tableau de "nom de modules" + public $array_export_label = array(); // Tableau de "libelle de lots" + public $array_export_sql_start = array(); // Tableau des "requetes sql" + public $array_export_sql_end = array(); // Tableau des "requetes sql" + public $array_export_sql_order = array(); // Tableau des "requetes sql" - public $array_export_fields=array(); // Tableau des listes de champ+libelle a exporter - public $array_export_TypeFields=array(); // Tableau des listes de champ+Type de filtre - public $array_export_FilterValue=array(); // Tableau des listes de champ+Valeur a filtrer - public $array_export_entities=array(); // Tableau des listes de champ+alias a exporter - public $array_export_dependencies=array(); // array of list of entities that must take care of the DISTINCT if a field is added into export - public $array_export_special=array(); // array of special operations to do on field - public $array_export_examplevalues=array(); // array with examples for fields - public $array_export_help=array(); // array with tooltip help for fields + public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter + public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre + public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer + public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter + public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export + public $array_export_special = array(); // array of special operations to do on field + public $array_export_examplevalues = array(); // array with examples for fields + public $array_export_help = array(); // array with tooltip help for fields // To store export modules - public $hexa; // List of fields in the export profile - public $hexafiltervalue; // List of search criteria in the export profile + public $hexa; // List of fields in the export profile + public $hexafiltervalue; // List of search criteria in the export profile public $datatoexport; - public $model_name; // Name of export profile + public $model_name; // Name of export profile public $sqlusedforexport; @@ -67,7 +67,7 @@ class Export */ public function __construct($db) { - $this->db=$db; + $this->db = $db; } @@ -82,35 +82,35 @@ class Export public function load_arrays($user, $filter = '') { // phpcs:enable - global $langs,$conf,$mysoc; + global $langs, $conf, $mysoc; dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter); - $i=0; + $i = 0; // Define list of modules directories into modulesdir require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $modulesdir = dolGetModulesDirs(); - foreach($modulesdir as $dir) + foreach ($modulesdir as $dir) { // Search available exports - $handle=@opendir(dol_osencode($dir)); + $handle = @opendir(dol_osencode($dir)); if (is_resource($handle)) { // Search module files - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { - $modulename=$reg[1]; + $modulename = $reg[1]; // Defined if module is enabled - $enabled=true; - $part=strtolower(preg_replace('/^mod/i', '', $modulename)); - if ($part == 'propale') $part='propal'; - if (empty($conf->$part->enabled)) $enabled=false; + $enabled = true; + $part = strtolower(preg_replace('/^mod/i', '', $modulename)); + if ($part == 'propale') $part = 'propal'; + if (empty($conf->$part->enabled)) $enabled = false; if ($enabled) { @@ -122,32 +122,32 @@ class Export if (isset($module->export_code) && is_array($module->export_code)) { - foreach($module->export_code as $r => $value) + foreach ($module->export_code as $r => $value) { //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'
'; if ($filter && ($filter != $module->export_code[$r])) continue; // Test if condition to show are ok - if (! empty($module->export_enabled[$r]) && ! verifCond($module->export_enabled[$r])) continue; + if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue; // Test if permissions are ok - $bool=true; + $bool = true; if (isset($module->export_permission)) { - foreach($module->export_permission[$r] as $val) + foreach ($module->export_permission[$r] as $val) { - $perm=$val; + $perm = $val; //print_r("$perm[0]-$perm[1]-$perm[2]
"); - if (! empty($perm[2])) + if (!empty($perm[2])) { - $bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}; + $bool = $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}; } else { - $bool=$user->rights->{$perm[0]}->{$perm[1]}; + $bool = $user->rights->{$perm[0]}->{$perm[1]}; } - if ($perm[0]=='user' && $user->admin) $bool=true; - if (! $bool) break; + if ($perm[0] == 'user' && $user->admin) $bool = true; + if (!$bool) break; } } //print $bool." $perm[0]"."
"; @@ -156,47 +156,47 @@ class Export // if ($bool) // { // Charge fichier lang en rapport - $langtoload=$module->getLangFilesArray(); + $langtoload = $module->getLangFilesArray(); if (is_array($langtoload)) { - foreach($langtoload as $key) + foreach ($langtoload as $key) { $langs->load($key); } } // Module - $this->array_export_module[$i]=$module; + $this->array_export_module[$i] = $module; // Permission - $this->array_export_perms[$i]=$bool; + $this->array_export_perms[$i] = $bool; // Icon - $this->array_export_icon[$i]=(isset($module->export_icon[$r])?$module->export_icon[$r]:$module->picto); + $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto); // Code du dataset export - $this->array_export_code[$i]=$module->export_code[$r]; + $this->array_export_code[$i] = $module->export_code[$r]; // Libelle du dataset export - $this->array_export_label[$i]=$module->getExportDatasetLabel($r); + $this->array_export_label[$i] = $module->getExportDatasetLabel($r); // Tableau des champ a exporter (cle=champ, valeur=libelle) - $this->array_export_fields[$i]=$module->export_fields_array[$r]; + $this->array_export_fields[$i] = $module->export_fields_array[$r]; // Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres - $this->array_export_TypeFields[$i]=(isset($module->export_TypeFields_array[$r])?$module->export_TypeFields_array[$r]:''); + $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : ''); // Tableau des entites a exporter (cle=champ, valeur=entite) - $this->array_export_entities[$i]=$module->export_entities_array[$r]; + $this->array_export_entities[$i] = $module->export_entities_array[$r]; // Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records) - $this->array_export_dependencies[$i]=(! empty($module->export_dependencies_array[$r])?$module->export_dependencies_array[$r]:''); + $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : ''); // Tableau des operations speciales sur champ - $this->array_export_special[$i]=(! empty($module->export_special_array[$r])?$module->export_special_array[$r]:''); + $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : ''); // Array of examples - $this->array_export_examplevalues[$i]=$module->export_examplevalues_array[$r]; + $this->array_export_examplevalues[$i] = $module->export_examplevalues_array[$r]; // Array of help tooltips - $this->array_export_help[$i]=(! empty($module->export_help_array[$r])?$module->export_help_array[$r]:''); + $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : ''); // Requete sql du dataset - $this->array_export_sql_start[$i]=$module->export_sql_start[$r]; - $this->array_export_sql_end[$i]=$module->export_sql_end[$r]; - $this->array_export_sql_order[$i]=$module->export_sql_order[$r]; + $this->array_export_sql_start[$i] = $module->export_sql_start[$r]; + $this->array_export_sql_end[$i] = $module->export_sql_end[$r]; + $this->array_export_sql_order[$i] = $module->export_sql_order[$r]; //$this->array_export_sql[$i]=$module->export_sql[$r]; - dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(! empty($module->export_fields_code[$r])?count($module->export_fields_code[$r]):'')); + dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(!empty($module->export_fields_code[$r]) ?count($module->export_fields_code[$r]) : '')); $i++; // } } @@ -226,42 +226,42 @@ class Export { // phpcs:enable // Build the sql request - $sql=$this->array_export_sql_start[$indice]; - $i=0; + $sql = $this->array_export_sql_start[$indice]; + $i = 0; //print_r($array_selected); foreach ($this->array_export_fields[$indice] as $key => $value) { - if (! array_key_exists($key, $array_selected)) continue; // Field not selected - if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL - if ($i > 0) $sql.=', '; + if (!array_key_exists($key, $array_selected)) continue; // Field not selected + if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL + if ($i > 0) $sql .= ', '; else $i++; - if (strpos($key, ' as ')===false) { - $newfield=$key.' as '.str_replace(array('.', '-','(',')'), '_', $key); + if (strpos($key, ' as ') === false) { + $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key); } else { - $newfield=$key; + $newfield = $key; } - $sql.=$newfield; + $sql .= $newfield; } - $sql.=$this->array_export_sql_end[$indice]; + $sql .= $this->array_export_sql_end[$indice]; // Add the WHERE part. Filtering into sql if a filtering array is provided if (is_array($array_filterValue) && !empty($array_filterValue)) { - $sqlWhere=''; + $sqlWhere = ''; // Loop on each condition to add foreach ($array_filterValue as $key => $value) { if (preg_match('/GROUP_CONCAT/i', $key)) continue; - if ($value != '') $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + if ($value != '') $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); } - $sql.=$sqlWhere; + $sql .= $sqlWhere; } // Add the order - $sql.=$this->array_export_sql_order[$indice]; + $sql .= $this->array_export_sql_order[$indice]; // Add the HAVING part. if (is_array($array_filterValue) && !empty($array_filterValue)) @@ -269,7 +269,7 @@ class Export // Loop on each condition to add foreach ($array_filterValue as $key => $value) { - if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); } } @@ -293,25 +293,25 @@ class Export // build the input field on depend of the type of file switch ($InfoFieldList[0]) { case 'Text': - if (! (strpos($ValueField, '%') === false)) - $szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'"; + if (!(strpos($ValueField, '%') === false)) + $szFilterQuery .= " ".$NameField." LIKE '".$ValueField."'"; else - $szFilterQuery.=" ".$NameField." = '".$ValueField."'"; + $szFilterQuery .= " ".$NameField." = '".$ValueField."'"; break; case 'Date': if (strpos($ValueField, "+") > 0) { // mode plage $ValueArray = explode("+", $ValueField); - $szFilterQuery ="(".$this->conditionDate($NameField, trim($ValueArray[0]), ">="); - $szFilterQuery.=" AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")"; + $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">="); + $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")"; } else { if (is_numeric(substr($ValueField, 0, 1))) - $szFilterQuery=$this->conditionDate($NameField, trim($ValueField), "="); + $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "="); else - $szFilterQuery=$this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); + $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); } break; case 'Duree': @@ -322,29 +322,29 @@ class Export { // mode plage $ValueArray = explode("+", $ValueField); - $szFilterQuery ="(".$NameField.">=".$ValueArray[0]; - $szFilterQuery.=" AND ".$NameField."<=".$ValueArray[1].")"; + $szFilterQuery = "(".$NameField.">=".$ValueArray[0]; + $szFilterQuery .= " AND ".$NameField."<=".$ValueArray[1].")"; } else { if (is_numeric(substr($ValueField, 0, 1))) - $szFilterQuery=" ".$NameField."=".$ValueField; + $szFilterQuery = " ".$NameField."=".$ValueField; else - $szFilterQuery=" ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); + $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); } break; case 'Boolean': - $szFilterQuery=" ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField =='yes' ? 1: 0) ); + $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0)); break; case 'Status': case 'List': if (is_numeric($ValueField)) - $szFilterQuery=" ".$NameField."=".$ValueField; + $szFilterQuery = " ".$NameField."=".$ValueField; else { - if (! (strpos($ValueField, '%') === false)) - $szFilterQuery=" ".$NameField." LIKE '".$ValueField."'"; + if (!(strpos($ValueField, '%') === false)) + $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'"; else - $szFilterQuery=" ".$NameField." = '".$ValueField."'"; + $szFilterQuery = " ".$NameField." = '".$ValueField."'"; } break; default: @@ -365,9 +365,9 @@ class Export public function conditionDate($Field, $Value, $Sens) { // TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN - if (strlen($Value)==4) $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; - elseif (strlen($Value)==6) $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; - else $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; + if (strlen($Value) == 4) $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; + elseif (strlen($Value) == 6) $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; + else $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; return $Condition; } @@ -383,9 +383,9 @@ class Export public function build_filterField($TypeField, $NameField, $ValueField) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; - $szFilterField=''; + $szFilterField = ''; $InfoFieldList = explode(":", $TypeField); // build the input field on depend of the type of file @@ -393,31 +393,31 @@ class Export { case 'Text': case 'Date': - $szFilterField=''; + $szFilterField = ''; break; case 'Duree': case 'Numeric': case 'Number': // Must be a string text to allow to use comparison strings like "<= 999" - $szFilterField=''; + $szFilterField = ''; break; case 'Status': - $szFilterField=''; + $szFilterField = ''; break; case 'Boolean': - $szFilterField='"; + $szFilterField .= ''; $num = $this->db->num_rows($resql); $i = 0; @@ -458,30 +458,30 @@ class Export continue; } //var_dump($InfoFieldList[1]); - $labeltoshow=dol_trunc($obj->label, 18); + $labeltoshow = dol_trunc($obj->label, 18); if ($InfoFieldList[1] == 'c_stcomm') { $langs->load("companies"); - $labeltoshow=(($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id)?$langs->trans("StatusProspect".$obj->id):$obj->label); + $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label); } if ($InfoFieldList[1] == 'c_country') { //var_dump($sql); $langs->load("dict"); - $labeltoshow=(($langs->trans("Country".$obj->code) != "Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label); + $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label); } if (!empty($ValueField) && $ValueField == $obj->rowid) { - $szFilterField.=''; + $szFilterField .= ''; } else { - $szFilterField.=''; + $szFilterField .= ''; } $i++; } } - $szFilterField.=""; + $szFilterField .= ""; $this->db->free($resql); } @@ -502,12 +502,12 @@ class Export { global $langs; - $szMsg=''; + $szMsg = ''; $InfoFieldList = explode(":", $TypeField); // build the input field on depend of the type of file switch ($InfoFieldList[0]) { case 'Text': - $szMsg= $langs->trans('ExportStringFilter'); + $szMsg = $langs->trans('ExportStringFilter'); break; case 'Date': $szMsg = $langs->trans('ExportDateFilter'); @@ -542,37 +542,37 @@ class Export public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '') { // phpcs:enable - global $conf,$langs,$mysoc; + global $conf, $langs, $mysoc; - $indice=0; + $indice = 0; asort($array_selected); dol_syslog(get_class($this)."::".__FUNCTION__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected)); // Check parameters or context properties - if (empty($this->array_export_fields) || ! is_array($this->array_export_fields)) + if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) { - $this->error="ErrorBadParameter"; + $this->error = "ErrorBadParameter"; return -1; } // Creation of class to export using model ExportXXX - $dir = DOL_DOCUMENT_ROOT . "/core/modules/export/"; + $dir = DOL_DOCUMENT_ROOT."/core/modules/export/"; $file = "export_".$model.".modules.php"; $classname = "Export".$model; require_once $dir.$file; $objmodel = new $classname($this->db); - if (! empty($sqlquery)) $sql = $sqlquery; + if (!empty($sqlquery)) $sql = $sqlquery; else { // Define value for indice from $datatoexport - $foundindice=0; - foreach($this->array_export_code as $key => $dataset) + $foundindice = 0; + foreach ($this->array_export_code as $key => $dataset) { if ($datatoexport == $dataset) { - $indice=$key; + $indice = $key; $foundindice++; //print "Found indice = ".$indice." for dataset=".$datatoexport."\n"; break; @@ -580,31 +580,31 @@ class Export } if (empty($foundindice)) { - $this->error="ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code"; + $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code"; return -1; } - $sql=$this->build_sql($indice, $array_selected, $array_filterValue); + $sql = $this->build_sql($indice, $array_selected, $array_filterValue); } // Run the sql - $this->sqlusedforexport=$sql; + $this->sqlusedforexport = $sql; dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { //$this->array_export_label[$indice] if ($conf->global->EXPORT_PREFIX_SPEC) - $filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport; + $filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport; else - $filename="export_".$datatoexport; - $filename.='.'.$objmodel->getDriverExtension(); - $dirname=$conf->export->dir_temp.'/'.$user->id; + $filename = "export_".$datatoexport; + $filename .= '.'.$objmodel->getDriverExtension(); + $dirname = $conf->export->dir_temp.'/'.$user->id; $outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value // Open file dol_mkdir($dirname); - $result=$objmodel->open_file($dirname."/".$filename, $outputlangs); + $result = $objmodel->open_file($dirname."/".$filename, $outputlangs); if ($result >= 0) { @@ -617,62 +617,62 @@ class Export while ($obj = $this->db->fetch_object($resql)) { // Process special operations - if (! empty($this->array_export_special[$indice])) + if (!empty($this->array_export_special[$indice])) { foreach ($this->array_export_special[$indice] as $key => $value) { - if (! array_key_exists($key, $array_selected)) continue; // Field not selected + if (!array_key_exists($key, $array_selected)) continue; // Field not selected // Operation NULLIFNEG - if ($this->array_export_special[$indice][$key]=='NULLIFNEG') + if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') { //$alias=$this->array_export_alias[$indice][$key]; - $alias=str_replace(array('.', '-','(',')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias=''; + $alias = str_replace(array('.', '-', '(', ')'), '_', $key); + if ($obj->$alias < 0) $obj->$alias = ''; } // Operation ZEROIFNEG - elseif ($this->array_export_special[$indice][$key]=='ZEROIFNEG') + elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') { //$alias=$this->array_export_alias[$indice][$key]; - $alias=str_replace(array('.', '-','(',')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias='0'; + $alias = str_replace(array('.', '-', '(', ')'), '_', $key); + if ($obj->$alias < 0) $obj->$alias = '0'; } // Operation GETNUMOPENDAYS (for Holiday module) - elseif ($this->array_export_special[$indice][$key]=='getNumOpenDays') + elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; //$alias=$this->array_export_alias[$indice][$key]; - $alias=str_replace(array('.', '-','(',')'), '_', $key); - $obj->$alias=num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code); + $alias = str_replace(array('.', '-', '(', ')'), '_', $key); + $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code); } // Operation INVOICEREMAINTOPAY - elseif ($this->array_export_special[$indice][$key]=='getRemainToPay') + elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') { //$alias=$this->array_export_alias[$indice][$key]; - $alias=str_replace(array('.', '-','(',')'), '_', $key); - $remaintopay=''; + $alias = str_replace(array('.', '-', '(', ')'), '_', $key); + $remaintopay = ''; if ($obj->f_rowid > 0) { global $tmpobjforcomputecall; - if (! is_object($tmpobjforcomputecall)) + if (!is_object($tmpobjforcomputecall)) { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $tmpobjforcomputecall=new Facture($this->db); + $tmpobjforcomputecall = new Facture($this->db); } $tmpobjforcomputecall->id = $obj->f_rowid; $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc; $tmpobjforcomputecall->close_code = $obj->f_close_code; - $remaintopay=$tmpobjforcomputecall->getRemainToPay(); + $remaintopay = $tmpobjforcomputecall->getRemainToPay(); } - $obj->$alias=$remaintopay; + $obj->$alias = $remaintopay; } else { // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field - $computestring=$this->array_export_special[$indice][$key]; - $tmp=dol_eval($computestring, 1, 0); - $obj->$alias=$tmp; + $computestring = $this->array_export_special[$indice][$key]; + $tmp = dol_eval($computestring, 1, 0); + $obj->$alias = $tmp; - $this->error="ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field."; + $this->error = "ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field."; return -1; } } @@ -691,14 +691,14 @@ class Export } else { - $this->error=$objmodel->error; + $this->error = $objmodel->error; dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR); return -1; } } else { - $this->error=$this->db->error()." - sql=".$sql; + $this->error = $this->db->error()." - sql=".$sql; return -1; } } @@ -717,24 +717,24 @@ class Export $this->db->begin(); - $filter=''; + $filter = ''; $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model ('; - $sql.= 'label,'; - $sql.= 'type,'; - $sql.= 'field,'; - $sql.= 'fk_user,'; - $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.= ")"; + $sql .= 'label,'; + $sql .= 'type,'; + $sql .= 'field,'; + $sql .= 'fk_user,'; + $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 .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -742,8 +742,8 @@ class Export } else { - $this->error=$this->db->lasterror(); - $this->errno=$this->db->lasterrno(); + $this->error = $this->db->lasterror(); + $this->errno = $this->db->lasterrno(); $this->db->rollback(); return -1; } @@ -758,8 +758,8 @@ class Export public function fetch($id) { $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 .= ' FROM '.MAIN_DB_PREFIX.'export_model as em'; + $sql .= ' WHERE em.rowid = '.$id; dol_syslog("Export::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -779,7 +779,7 @@ class Export } else { - $this->error="ModelNotFound"; + $this->error = "ModelNotFound"; return -2; } } @@ -801,20 +801,20 @@ class Export public function delete($user, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model"; - $sql.= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action call a trigger. @@ -831,13 +831,13 @@ class Export // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -859,8 +859,8 @@ class Export global $conf, $langs; $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter"; - $sql.= " FROM ".MAIN_DB_PREFIX."export_model as em"; - $sql.= " ORDER BY rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em"; + $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); if ($result) @@ -878,12 +878,12 @@ class Export print $this->array_export_module[$keyModel]->getName().' - '; // recuperation du nom de l'export - $string=$langs->trans($this->array_export_label[$keyModel]); - print ($string!=$this->array_export_label[$keyModel]?$string:$this->array_export_label[$keyModel]); + $string = $langs->trans($this->array_export_label[$keyModel]); + print ($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]); print ''; //print ''; print ''; - if (! empty($obj->filter)) { + if (!empty($obj->filter)) { $filter = json_decode($obj->filter, true); print ''; print ''; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index 525a5b17c9e..f910001a5e0 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -379,7 +379,7 @@ if ($step == 2 && $action == 'select_model') { $fieldsarray = preg_split("/,(?! [^(]*\))/", $objexport->hexa); $i = 1; - foreach($fieldsarray as $val) + foreach ($fieldsarray as $val) { $array_selected[$val] = $i; $i++; diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php index 5c854d0ecb1..18e2992930c 100644 --- a/htdocs/filefunc.inc.php +++ b/htdocs/filefunc.inc.php @@ -31,7 +31,7 @@ */ if (! defined('DOL_APPLICATION_TITLE')) define('DOL_APPLICATION_TITLE', 'Dolibarr'); -if (! defined('DOL_VERSION')) define('DOL_VERSION', '11.0.0'); // a.b.c-alpha, a.b.c-beta, a.b.c-rcX or a.b.c +if (! defined('DOL_VERSION')) define('DOL_VERSION', '12.0.0-alpha'); // a.b.c-alpha, a.b.c-beta, a.b.c-rcX or a.b.c if (! defined('EURO')) define('EURO', chr(128)); diff --git a/htdocs/fourn/ajax/getSupplierPrices.php b/htdocs/fourn/ajax/getSupplierPrices.php index 2d18c6ea86e..0c0d8f42c9e 100644 --- a/htdocs/fourn/ajax/getSupplierPrices.php +++ b/htdocs/fourn/ajax/getSupplierPrices.php @@ -22,20 +22,20 @@ * \brief File to return an Ajax response to get list of possible prices for margin calculation */ -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; -$idprod=GETPOST('idprod', 'int'); +$idprod = GETPOST('idprod', 'int'); $prices = array(); // Load translation files required by the page -$langs->loadLangs(array("stocks","margins")); +$langs->loadLangs(array("stocks", "margins")); /* @@ -48,14 +48,14 @@ top_httphead(); if ($idprod > 0) { - $producttmp=new ProductFournisseur($db); + $producttmp = new ProductFournisseur($db); $producttmp->fetch($idprod); $sorttouse = 's.nom, pfp.quantity, pfp.price'; if (GETPOST('bestpricefirst')) $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price'; - $productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse); // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list. - if ( is_array($productSupplierArray)) + $productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse); // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list. + if (is_array($productSupplierArray)) { foreach ($productSupplierArray as $productSupplier) { @@ -66,35 +66,35 @@ if ($idprod > 0) if ($productSupplier->fourn_qty == 1) { - $title.= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/"; + $title .= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/"; } - $title.= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units")); + $title .= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units")); if ($productSupplier->fourn_qty > 1) { - $title.=" - "; - $title.= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); + $title .= " - "; + $title .= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); $price = $unitprice; } $label = price($price, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); - if ($productSupplier->fourn_ref) $label.=' ('.$productSupplier->fourn_ref.')'; + if ($productSupplier->fourn_ref) $label .= ' ('.$productSupplier->fourn_ref.')'; - $prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title); // For price field, we must use price2num(), for label or title, price() + $prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title); // For price field, we must use price2num(), for label or title, price() } } // After best supplier prices and before costprice - if(!empty($conf->stock->enabled)) + if (!empty($conf->stock->enabled)) { // Add price for pmp - $price=$producttmp->pmp; - $prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() + $price = $producttmp->pmp; + $prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() } // Add price for costprice (at end) - $price=$producttmp->cost_price; - $prices[] = array("id" => 'costprice', "price" => price2num($price), "label" => $langs->trans("CostPrice").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() + $price = $producttmp->cost_price; + $prices[] = array("id" => 'costprice', "price" => price2num($price), "label" => $langs->trans("CostPrice").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() } echo json_encode($prices); diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 9056d1217ca..23031d09d90 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -36,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by page $langs->loadLangs(array( @@ -312,7 +313,7 @@ if ($object->id > 0) $langs->load("categories"); print ''; print '"; } diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 3b2833fee76..bd74d52a4d5 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -65,7 +65,7 @@ class CommandeFournisseur extends CommonOrder /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto='order'; + public $picto = 'order'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -442,7 +442,7 @@ class CommandeFournisseur extends CommonOrder $line->fk_product = $objp->fk_product; - $line->libelle = $objp->product_label; // deprecated + $line->libelle = $objp->product_label; // deprecated $line->product_label = $objp->product_label; $line->product_desc = $objp->product_desc; @@ -1414,38 +1414,38 @@ class CommandeFournisseur extends CommonOrder */ public function createFromClone(User $user, $socid = 0) { - global $conf, $user,$hookmanager; + global $conf, $user, $hookmanager; - $error=0; + $error = 0; $this->db->begin(); // get lines so they will be clone - foreach($this->lines as $line) + foreach ($this->lines as $line) $line->fetch_optionals(); // Load source object $objFrom = clone $this; // Change socid if needed - if (! empty($socid) && $socid != $this->socid) + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid)>0) + if ($objsoc->fetch($socid) > 0) { - $this->socid = $objsoc->id; - $this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $this->fk_project = 0; - $this->fk_delivery_address = 0; + $this->socid = $objsoc->id; + $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $this->fk_project = 0; + $this->fk_delivery_address = 0; } // 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; @@ -2400,7 +2400,7 @@ class CommandeFournisseur extends CommonOrder $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 .= " 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."');"; @@ -2623,7 +2623,7 @@ class CommandeFournisseur extends CommonOrder 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) { + foreach ($array_options as $key => $value) { $this->line->array_options[$key] = $array_options[$key]; } } @@ -2795,26 +2795,26 @@ class CommandeFournisseur extends CommonOrder // phpcs:enable global $conf, $user; - $this->nb=array(); + $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"; + $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; + $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 .= " ".$clause." co.entity = ".$conf->entity; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $this->nb["supplier_orders"]=$obj->nb; + $this->nb["supplier_orders"] = $obj->nb; } $this->db->free($resql); return 1; @@ -2843,41 +2843,41 @@ class CommandeFournisseur extends CommonOrder $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"; + $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; + $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; + $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.")"; + else { + $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; } - if ($user->socid) $sql.=" AND c.fk_soc = ".$user->socid; + if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; - $resql=$this->db->query($sql); + $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->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)) + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; @@ -2953,17 +2953,17 @@ class CommandeFournisseur extends CommonOrder $langs->load("suppliers"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'muscadet'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) { + } elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) { $modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF; } } - $modelpath = "core/modules/supplier_order/pdf/"; + $modelpath = "core/modules/supplier_order/doc/"; return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } @@ -3642,20 +3642,20 @@ class CommandeFournisseurLigne extends CommonOrderLine { global $user; - $error=0; + $error = 0; $this->db->begin(); $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if (!$notrigger) { // Call trigger - $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); + $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); if ($result < 0) $error++; // End call triggers } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index b64bd1277c0..231a5e9e910 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -46,27 +46,27 @@ class FactureFournisseur extends CommonInvoice /** * @var string ID to identify managed object */ - public $element='invoice_supplier'; + public $element = 'invoice_supplier'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='facture_fourn'; + public $table_element = 'facture_fourn'; /** * @var int Name of subtable line */ - public $table_element_line='facture_fourn_det'; + 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'; + 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='bill'; + public $picto = 'bill'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -96,7 +96,7 @@ class FactureFournisseur extends CommonInvoice public $ref; public $label; - public $libelle; // @deprecated + public $libelle; // @deprecated public $product_ref; public $ref_supplier; @@ -196,9 +196,9 @@ class FactureFournisseur extends CommonInvoice public $fk_incoterms; public $location_incoterms; - public $label_incoterms; //Used into tooltip + public $label_incoterms; //Used into tooltip - public $extraparams=array(); + public $extraparams = array(); // Multicurrency /** @@ -317,86 +317,86 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - if (! $remise) $remise = 0 ; + if (!$remise) $remise = 0; $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn ("; - $sql.= "ref"; - $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_incoterms, location_incoterms"; - $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->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.= ", ".(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.= ", ".(isset($this->fk_facture_source)?$this->fk_facture_source:"NULL"); - $sql.= ")"; + $sql .= "ref"; + $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_incoterms, location_incoterms"; + $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->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 .= ", ".(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 .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL"); + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $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.')'; + $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++; + $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 + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { - foreach($this->linked_objects as $origin => $tmp_origin_id) + 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) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { dol_print_error($this->db); $error++; @@ -501,28 +501,28 @@ class FactureFournisseur extends CommonInvoice } // Update total price - $result=$this->update_price(); + $result = $this->update_price(); if ($result > 0) { // Actions on extra fields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found + $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found if ($result < 0) { $error++; } } - if (! $error) + if (!$error) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_CREATE', $user); + $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -569,75 +569,75 @@ class FactureFournisseur extends CommonInvoice global $langs; $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.= ' 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').")"; + $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 .= ' 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').")"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $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->ref_supplier = $obj->ref_supplier; $this->entity = $obj->entity; - $this->type = empty($obj->type)? self::TYPE_STANDARD:$obj->type; + $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->tms = $this->db->jdate($obj->tms); + $this->libelle = $obj->label; // deprecated $this->label = $obj->label; $this->paye = $obj->paye; $this->paid = $obj->paye; @@ -645,7 +645,7 @@ class FactureFournisseur extends CommonInvoice $this->remise = $obj->remise; $this->close_code = $obj->close_code; $this->close_note = $obj->close_note; - $this->tva = $obj->tva; + $this->tva = $obj->tva; $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; $this->total_ht = $obj->total_ht; @@ -758,44 +758,44 @@ class FactureFournisseur extends CommonInvoice $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->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->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->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->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->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->info_bits = $obj->info_bits; $line->fk_parent_line = $obj->fk_parent_line; $line->special_code = $obj->special_code; - $line->rang = $obj->rang; + $line->rang = $obj->rang; $line->fk_unit = $obj->fk_unit; // Multicurrency @@ -832,40 +832,40 @@ class FactureFournisseur extends CommonInvoice public function update($user = null, $notrigger = 0) { global $conf, $langs; - $error=0; + $error = 0; // Clean parameters - if (empty($this->type)) $this->type= self::TYPE_STANDARD; - if (isset($this->ref)) $this->ref=trim($this->ref); - if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier); - if (isset($this->entity)) $this->entity=trim($this->entity); - if (isset($this->type)) $this->type=trim($this->type); - if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc); - if (isset($this->label)) $this->label=trim($this->label); - if (isset($this->libelle)) $this->libelle=trim($this->libelle); // deprecated - if (isset($this->paye)) $this->paye=trim($this->paye); - if (isset($this->amount)) $this->amount=trim($this->amount); - if (isset($this->remise)) $this->remise=trim($this->remise); - if (isset($this->close_code)) $this->close_code=trim($this->close_code); - if (isset($this->close_note)) $this->close_note=trim($this->close_note); - if (isset($this->tva)) $this->tva=trim($this->tva); - if (isset($this->localtax1)) $this->localtax1=trim($this->localtax1); - if (isset($this->localtax2)) $this->localtax2=trim($this->localtax2); - if (empty($this->total_ht)) $this->total_ht=0; - if (empty($this->total_tva)) $this->total_tva=0; + if (empty($this->type)) $this->type = self::TYPE_STANDARD; + if (isset($this->ref)) $this->ref = trim($this->ref); + if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); + if (isset($this->entity)) $this->entity = trim($this->entity); + if (isset($this->type)) $this->type = trim($this->type); + if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc); + if (isset($this->label)) $this->label = trim($this->label); + if (isset($this->libelle)) $this->libelle = trim($this->libelle); // deprecated + if (isset($this->paye)) $this->paye = trim($this->paye); + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->remise)) $this->remise = trim($this->remise); + if (isset($this->close_code)) $this->close_code = trim($this->close_code); + if (isset($this->close_note)) $this->close_note = trim($this->close_note); + if (isset($this->tva)) $this->tva = trim($this->tva); + if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1); + if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2); + if (empty($this->total_ht)) $this->total_ht = 0; + if (empty($this->total_tva)) $this->total_tva = 0; // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1); // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2); - if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc); - if (isset($this->statut)) $this->statut=(int) $this->statut; - if (isset($this->author)) $this->author=trim($this->author); - if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid); - if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source); - if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project); - if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id); - if (isset($this->note_private)) $this->note=trim($this->note_private); - if (isset($this->note_public)) $this->note_public=trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key=trim($this->import_key); + if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc); + if (isset($this->statut)) $this->statut = (int) $this->statut; + if (isset($this->author)) $this->author = trim($this->author); + if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid); + if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source); + if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project); + if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id); + if (isset($this->note_private)) $this->note = trim($this->note_private); + if (isset($this->note_public)) $this->note_public = trim($this->note_public); + if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); + if (isset($this->import_key)) $this->import_key = trim($this->import_key); // Check parameters @@ -873,38 +873,38 @@ class FactureFournisseur extends CommonInvoice // 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=".(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; $this->db->begin(); @@ -1313,13 +1313,13 @@ class FactureFournisseur extends CommonInvoice */ public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0) { - global $conf,$langs; + global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $now=dol_now(); + $now = dol_now(); - $error=0; + $error = 0; dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse); // Force to have object complete for checks @@ -1385,10 +1385,10 @@ class FactureFournisseur extends CommonInvoice $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)); + $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); } @@ -1412,17 +1412,17 @@ class FactureFournisseur extends CommonInvoice 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; + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref; $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref; - if (! $error && file_exists($dirsource)) + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); @@ -1521,16 +1521,16 @@ class FactureFournisseur extends CommonInvoice $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increase stock for product - if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); - else $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); } } } // Triggers call - if (! $error && empty($notrigger)) + if (!$error && empty($notrigger)) { // Call trigger - $result=$this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); + $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); if ($result < 0) $error++; // End call triggers } @@ -1595,27 +1595,27 @@ class FactureFournisseur extends CommonInvoice if ($this->statut == self::STATUS_DRAFT) { // Clean parameters - if (empty($remise_percent)) $remise_percent=0; - if (empty($qty)) $qty=0; - if (empty($info_bits)) $info_bits=0; - if (empty($rang)) $rang=0; - if (empty($ventil)) $ventil=0; - if (empty($txtva)) $txtva=0; - if (empty($txlocaltax1)) $txlocaltax1=0; - if (empty($txlocaltax2)) $txlocaltax2=0; + if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) $qty = 0; + if (empty($info_bits)) $info_bits = 0; + if (empty($rang)) $rang = 0; + if (empty($ventil)) $ventil = 0; + if (empty($txtva)) $txtva = 0; + if (empty($txlocaltax1)) $txlocaltax1 = 0; + if (empty($txlocaltax2)) $txlocaltax2 = 0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu=price2num($pu); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu = price2num($pu); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' + $txtva = price2num($txtva); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1' } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); - $this->error=$langs->trans('ErrorStartDateGreaterEnd'); + $this->error = $langs->trans('ErrorStartDateGreaterEnd'); return -1; } @@ -1952,7 +1952,7 @@ class FactureFournisseur extends CommonInvoice 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) { + foreach ($array_options as $key => $value) { $this->line->array_options[$key] = $array_options[$key]; } } @@ -2201,31 +2201,31 @@ class FactureFournisseur extends CommonInvoice 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 .= ' 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); + $resql = $this->db->query($sql); if ($resql) { $langs->load("bills"); - $now=dol_now(); + $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->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"); + $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)) + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; @@ -2276,58 +2276,58 @@ class FactureFournisseur extends CommonInvoice 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'; + $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 + $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("ShowSupplierInvoice") . ''; - 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 ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; - elseif ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref; - elseif ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref; - if ($moretitle) $label.=' - '.$moretitle; + $label = ''.$langs->trans("ShowSupplierInvoice").''; + 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 ($this->type == self::TYPE_REPLACEMENT) $label = $langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; + elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = $langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref; + elseif ($this->type == self::TYPE_DEPOSIT) $label = $langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref; + if ($moretitle) $label .= ' - '.$moretitle; - $ref=$this->ref; - if (empty($ref)) $ref=$this->id; + $ref = $this->ref; + if (empty($ref)) $ref = $this->id; - $linkclose=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowSupplierInvoice"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowSupplierInvoice"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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); + 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) @@ -2395,7 +2395,7 @@ class FactureFournisseur extends CommonInvoice } else { - $this->error=$obj->error; + $this->error = $obj->error; //dol_print_error($db,get_class($this)."::getNextNumRef ".$obj->error); return false; } @@ -2520,27 +2520,27 @@ class FactureFournisseur extends CommonInvoice // phpcs:enable global $conf, $user; - $this->nb=array(); + $this->nb = array(); $clause = "WHERE"; $sql = "SELECT count(f.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$user->socid) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; + $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." f.entity = ".$conf->entity; + $sql .= " ".$clause." f.entity = ".$conf->entity; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $this->nb["supplier_invoices"]=$obj->nb; + $this->nb["supplier_invoices"] = $obj->nb; } $this->db->free($resql); return 1; @@ -2565,16 +2565,16 @@ class FactureFournisseur extends CommonInvoice { 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; + $object->id = 0; + $object->statut = self::STATUS_DRAFT; // Clear fields $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier); @@ -2664,7 +2664,7 @@ class FactureFournisseur extends CommonInvoice } else { - $modelpath = "core/modules/supplier_invoice/pdf/"; + $modelpath = "core/modules/supplier_invoice/doc/"; return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } @@ -2729,9 +2729,9 @@ class FactureFournisseur extends CommonInvoice $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)){ + if (!empty($resql)) { $obj = $db->fetch_object($resql); - if(!empty($obj->fk_invoice_supplier))$isUsed=true; + if (!empty($obj->fk_invoice_supplier))$isUsed = true; } return $isUsed; @@ -2983,14 +2983,14 @@ class SupplierInvoiceLine extends CommonObjectLine public function fetch($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.tva_tx'; - $sql.= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 '; - $sql.= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_facture_fourn, 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 product_label, p.description as product_desc'; - $sql.= ', f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, 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 f.rowid = '.$rowid; - $sql.= ' ORDER BY f.rang, f.rowid'; + $sql .= ', f.localtax1_type, f.localtax2_type, f.localtax1_tx, f.localtax2_tx, f.total_localtax1, f.total_localtax2 '; + $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_facture_fourn, 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 product_label, p.description as product_desc'; + $sql .= ', f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, 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 f.rowid = '.$rowid; + $sql .= ' ORDER BY f.rang, f.rowid'; $query = $this->db->query($sql); @@ -3025,21 +3025,21 @@ class SupplierInvoiceLine extends CommonObjectLine $this->localtax1_type = $obj->localtax1_type; $this->localtax2_type = $obj->localtax2_type; $this->qty = $obj->qty; - $this->remise_percent = $obj->remise_percent; - $this->tva = $obj->total_tva; // deprecated - $this->total_ht = $obj->total_ht; + $this->remise_percent = $obj->remise_percent; + $this->tva = $obj->total_tva; // deprecated + $this->total_ht = $obj->total_ht; $this->total_tva = $obj->total_tva; $this->total_localtax1 = $obj->total_localtax1; $this->total_localtax2 = $obj->total_localtax2; $this->total_ttc = $obj->total_ttc; $this->fk_product = $obj->fk_product; - $this->product_type = $obj->product_type; + $this->product_type = $obj->product_type; $this->product_label = $obj->product_label; $this->info_bits = $obj->info_bits; - $this->tva_npr = ($obj->info_bits & 1 == 1) ? 1 : 0; + $this->tva_npr = ($obj->info_bits & 1 == 1) ? 1 : 0; $this->fk_parent_line = $obj->fk_parent_line; - $this->special_code = $obj->special_code; - $this->rang = $obj->rang; + $this->special_code = $obj->special_code; + $this->rang = $obj->rang; $this->fk_unit = $obj->fk_unit; $this->multicurrency_subprice = $obj->multicurrency_subprice; @@ -3224,50 +3224,50 @@ class SupplierInvoiceLine extends CommonObjectLine */ public function insert($notrigger = 0) { - global $user,$conf; + global $user, $conf; - $error=0; + $error = 0; 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; + $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'; + $this->error = 'ErrorProductTypeMustBe0orMore'; return -1; } - if (! empty($this->fk_product)) + if (!empty($this->fk_product)) { // Check product exists - $result=Product::isExistingObject('product', $this->fk_product); + $result = Product::isExistingObject('product', $this->fk_product); if ($result <= 0) { - $this->error='ErrorProductIdDoesNotExists'; + $this->error = 'ErrorProductIdDoesNotExists'; return -1; } } diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index 2ada245ff8b..eb9093888af 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -8,6 +8,7 @@ * Copyright (C) 2016 Florian Henry * Copyright (C) 2017 Ferran Marcet * Copyright (C) 2018 Frédéric France + * Copyright (C) 2019 Christophe Battarel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -51,6 +52,8 @@ $id = GETPOST("id", 'int'); $ref = GETPOST('ref'); $lineid = GETPOST('lineid', 'int'); $action = GETPOST('action', 'aZ09'); +$fk_default_warehouse = GETPOST('fk_default_warehouse', 'int'); + if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); @@ -236,6 +239,7 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) $prod = "product_".$reg[1].'_'.$reg[2]; $qty = "qty_".$reg[1].'_'.$reg[2]; $ent = "entrepot_".$reg[1].'_'.$reg[2]; + if (empty(GETPOST($ent))) $ent = $fk_default_warehouse; $pu = "pu_".$reg[1].'_'.$reg[2]; // This is unit price including discount $fk_commandefourndet = "fk_commandefourndet_".$reg[1].'_'.$reg[2]; @@ -484,9 +488,11 @@ if ($id > 0 || !empty($ref)) { if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY - || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) { - $entrepot = new Entrepot($db); - $listwarehouses = $entrepot->list_array(1); + || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $formproduct->loadWarehouses(); if (empty($conf->reception->enabled))print ''; else print ''; @@ -561,6 +567,9 @@ if ($id > 0 || !empty($ref)) { $i = 0; if ($num) { + $entrepot = new Entrepot($db); + $listwarehouses=$entrepot->list_array(1); + print ''; print ''; @@ -590,7 +599,19 @@ if ($id > 0 || !empty($ref)) { } } - print ''; + print ''; // Enable hooks to append additional columns $parameters = array(); @@ -897,6 +918,15 @@ if ($id > 0 || !empty($ref)) { dol_fiche_end(); + // traitement entrepot par défaut + print ''; // List of lines already dispatched $sql = "SELECT p.ref, p.label,"; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index e9198ebcc91..e0a679d1321 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -370,7 +370,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $dateinvoice = ($datefacture == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datefacture); $sql = 'SELECT s.nom as name, s.rowid as socid,'; - $sql .= ' f.rowid, f.ref, f.ref_supplier, f.amount, f.total_ttc as total, f.fk_mode_reglement, f.fk_account'; + $sql .= ' f.rowid, f.ref, f.ref_supplier, f.total_ttc as total, f.fk_mode_reglement, f.fk_account'; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f'; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -821,7 +821,7 @@ if (empty($action) || $action == 'list') $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(f.amount)'; + $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'; @@ -1013,9 +1013,9 @@ if (empty($action) || $action == 'list') // Amount print ''; - if (!$i) $totalarray['nbfield']++; - $totalarray['pos'][7] = 'amount'; + $totalarray['pos'][$totalarray['nbfield']] = 'amount'; $totalarray['val']['amount'] += $objp->pamount; + if (!$i) $totalarray['nbfield']++; // Ref invoice /*$invoicesupplierstatic->ref=$objp->ref_supplier; diff --git a/htdocs/fourn/recap-fourn.php b/htdocs/fourn/recap-fourn.php index 1fda453ffe4..2cd52bfeb77 100644 --- a/htdocs/fourn/recap-fourn.php +++ b/htdocs/fourn/recap-fourn.php @@ -72,7 +72,7 @@ if ($socid > 0) print '
'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).''; $return .= '
'.$titre.'
'; @@ -4267,8 +4267,9 @@ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', print ''; // maring bottom must be same than into load_fiche_tire // Left + + if ($picto && $titre) print ''; print ''; @@ -6140,6 +6141,8 @@ function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : ''); $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : ''); $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : ''); + $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : ''); + $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : ''); $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : ''); $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : ''); $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : ''); @@ -6163,6 +6166,8 @@ function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : ''); $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : ''); $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : ''); + $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : ''); + $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : ''); $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : ''); $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : ''); $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : ''); @@ -6906,6 +6911,24 @@ function utf8_check($str) return true; } +/** + * Check if a string is in ASCII + * + * @param string $str String to check + * @return boolean True if string is ASCII, False if not (byte value > 0x7F) + */ +function ascii_check($str) +{ + if (function_exists('mb_check_encoding')) { + //if (mb_detect_encoding($str, 'ASCII', true) return false; + if (! mb_check_encoding($str, 'ASCII')) return false; + } else { + if (preg_match('/[^\x00-\x7f]/', $str)) return false; // Contains a byte > 7f + } + + return true; +} + /** * Return a string encoded into OS filesystem encoding. This function is used to define diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index d4b4016a564..98d636e97dd 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -573,7 +573,7 @@ function isValidVATID($company) elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers else $vatprefix = preg_quote($vatprefix, '/');*/ $vatprefix = '[a-zA-Z][a-zA-Z]'; - if (! preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) + if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) { return 0; } @@ -732,17 +732,17 @@ function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = ' */ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null) { - global $conf,$user; + global $conf, $user; - if (! is_object($objsoc)) $valueforccc=$objsoc; - elseif ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=dol_string_unaccent($objsoc->code_fournisseur); - else $valueforccc=dol_string_unaccent($objsoc->code_client); + if (!is_object($objsoc)) $valueforccc = $objsoc; + elseif ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = dol_string_unaccent($objsoc->code_fournisseur); + else $valueforccc = dol_string_unaccent($objsoc->code_client); $sharetable = $table; if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function // Clean parameters - if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers + if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers // but we should use local year and month of user // For debugging @@ -811,73 +811,73 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; if (is_object($objuser)) $lastname = $objuser->lastname; - $maskuser=$regType[1]; - $maskuser_value=substr($lastname, 0, dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask) - $maskuser_value=str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask + $maskuser = $regType[1]; + $maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask) + $maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask } else { - $maskuser=''; - $maskuser_value=''; + $maskuser = ''; + $maskuser_value = ''; } // Personalized field {XXX-1} à {XXX-9} - $maskperso=array(); - $maskpersonew=array(); - $tmpmask=$mask; + $maskperso = array(); + $maskpersonew = array(); + $tmpmask = $mask; while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) { - $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}'; - $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT); - $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask); + $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}'; + $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT); + $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask); } if (strstr($mask, 'user_extra_')) { $start = "{user_extra_"; $end = "\}"; - $extra= get_string_between($mask, "user_extra_", "}"); + $extra = get_string_between($mask, "user_extra_", "}"); if (!empty($user->array_options['options_'.$extra])) { - $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask); + $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask); } } - $maskwithonlyymcode=$mask; - $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode); - foreach($maskperso as $key => $val) + $maskwithonlyymcode = $mask; + $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode); + foreach ($maskperso as $key => $val) { - $maskwithonlyymcode=preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode); } - $maskwithnocode=$maskwithonlyymcode; - $maskwithnocode=preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode); - $maskwithnocode=preg_replace('/\{yy\}/i', 'yy', $maskwithnocode); - $maskwithnocode=preg_replace('/\{y\}/i', 'y', $maskwithnocode); - $maskwithnocode=preg_replace('/\{mm\}/i', 'mm', $maskwithnocode); + $maskwithnocode = $maskwithonlyymcode; + $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode); + $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode); + $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode); + $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode); // Now maskwithnocode = 0000ddmmyyyyccc for example // and maskcounter = 0000 for example //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n
"; //var_dump($reg); // If an offset is asked - if (! empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset=preg_replace('/^\+/', '', $reg[2]); - if (! empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset=preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); // Define $sqlwhere - $sqlwhere=''; - $yearoffset=0; // Use year of current $date by default - $yearoffsettype=false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x + $sqlwhere = ''; + $yearoffset = 0; // Use year of current $date by default + $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x // If a restore to zero after a month is asked we check if there is already a value for this year. - if (! empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]); - if (! empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]); + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]); //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype; if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) - $maskraz=$yearoffsettype; // For backward compatibility - elseif ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) + $maskraz = $yearoffsettype; // For backward compatibility + elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START; //print "maskraz=".$maskraz; // -1=no reset @@ -1161,24 +1161,24 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ if ($maskrefclient) { //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n
";exit; - $maskrefclient_maskbefore='{'.$maskrefclient.'}'; - $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT); + $maskrefclient_maskbefore = '{'.$maskrefclient.'}'; + $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT); $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal); } // Now we replace the type if ($masktype) { - $masktype_maskbefore='{'.$masktype.'}'; - $masktype_maskafter=$masktype_value; + $masktype_maskbefore = '{'.$masktype.'}'; + $masktype_maskafter = $masktype_value; $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal); } // Now we replace the user if ($maskuser) { - $maskuser_maskbefore='{'.$maskuser.'}'; - $maskuser_maskafter=$maskuser_value; + $maskuser_maskbefore = '{'.$maskuser.'}'; + $maskuser_maskafter = $maskuser_value; $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal); } } @@ -1214,69 +1214,69 @@ function get_string_between($string, $start, $end) */ function check_value($mask, $value) { - $result=0; + $result = 0; - $hasglobalcounter=false; + $hasglobalcounter = false; // Extract value for mask counter, mask raz and mask offset if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) { - $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:''); - $maskcounter=$reg[1]; - $hasglobalcounter=true; + $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : ''); + $maskcounter = $reg[1]; + $hasglobalcounter = true; } else { // setting some defaults so the rest of the code won't fail if there is a third party counter - $masktri='00000'; - $maskcounter='00000'; + $masktri = '00000'; + $maskcounter = '00000'; } - $maskraz=-1; - $maskoffset=0; + $maskraz = -1; + $maskoffset = 0; if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; // Extract value for third party mask counter if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { - $maskrefclient=$regClientRef[1].$regClientRef[2]; - $maskrefclient_maskclientcode=$regClientRef[1]; - $maskrefclient_maskcounter=$regClientRef[2]; - $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset - $maskrefclient_clientcode=substr('', 0, dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode - $maskrefclient_clientcode=str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode - $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like + $maskrefclient = $regClientRef[1].$regClientRef[2]; + $maskrefclient_maskclientcode = $regClientRef[1]; + $maskrefclient_maskcounter = $regClientRef[2]; + $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset + $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode + $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode + $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; } - else $maskrefclient=''; + else $maskrefclient = ''; // fail if there is neither a global nor a third party counter - if (! $hasglobalcounter && ($maskrefclient_maskcounter == '')) + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } - $maskwithonlyymcode=$mask; - $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode); - $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); - $maskwithnocode=$maskwithonlyymcode; - $maskwithnocode=preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode); - $maskwithnocode=preg_replace('/\{yy\}/i', 'yy', $maskwithnocode); - $maskwithnocode=preg_replace('/\{y\}/i', 'y', $maskwithnocode); - $maskwithnocode=preg_replace('/\{mm\}/i', 'mm', $maskwithnocode); + $maskwithonlyymcode = $mask; + $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode); + $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); + $maskwithnocode = $maskwithonlyymcode; + $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode); + $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode); + $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode); + $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode); // Now maskwithnocode = 0000ddmmyyyyccc for example // and maskcounter = 0000 for example //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n
"; // If an offset is asked - if (! empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset=preg_replace('/^\+/', '', $reg[2]); - if (! empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset=preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); // Define $sqlwhere // If a restore to zero after a month is asked we check if there is already a value for this year. - if (! empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz=preg_replace('/^@/', '', $reg[2]); - if (! empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz=preg_replace('/^@/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz = preg_replace('/^@/', '', $reg[2]); + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz = preg_replace('/^@/', '', $reg[3]); if ($maskraz >= 0) { if ($maskraz == 99) { @@ -1286,8 +1286,8 @@ function check_value($mask, $value) if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth'; // Define reg - if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; - if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask'; + if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask'; //print "x".$maskwithonlyymcode." ".$maskraz; } //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."
\n"; @@ -1616,16 +1616,16 @@ function version_webserver() */ function getListOfModels($db, $type, $maxfilenamelength = 0) { - global $conf,$langs; - $liste=array(); - $found=0; - $dirtoscan=''; + global $conf, $langs; + $liste = array(); + $found = 0; + $dirtoscan = ''; $sql = "SELECT nom as id, nom as doc_template_name, libelle as label, description as description"; - $sql.= " FROM ".MAIN_DB_PREFIX."document_model"; - $sql.= " WHERE type = '".$type."'"; - $sql.= " AND entity IN (0,".$conf->entity.")"; - $sql.= " ORDER BY description DESC"; + $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; + $sql .= " WHERE type = '".$type."'"; + $sql .= " AND entity IN (0,".$conf->entity.")"; + $sql .= " ORDER BY description DESC"; dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG); $resql = $db->query($sql); @@ -1635,48 +1635,48 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) $i = 0; while ($i < $num) { - $found=1; + $found = 1; $obj = $db->fetch_object($resql); // If this generation module needs to scan a directory, then description field is filled // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...). - if (! empty($obj->description)) // A list of directories to scan is defined + if (!empty($obj->description)) // A list of directories to scan is defined { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $const=$obj->description; + $const = $obj->description; //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const)); - $dirtoscan= preg_replace('/[\r\n]+/', ',', trim($conf->global->$const)); + $dirtoscan = preg_replace('/[\r\n]+/', ',', trim($conf->global->$const)); - $listoffiles=array(); + $listoffiles = array(); // Now we add models found in directories scanned - $listofdir=explode(',', $dirtoscan); - foreach($listofdir as $key=>$tmpdir) + $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; } + $tmpdir = trim($tmpdir); + $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); + if (!$tmpdir) { unset($listofdir[$key]); continue; } if (is_dir($tmpdir)) { // all type of template is allowed - $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles=array_merge($listoffiles, $tmpfiles); + $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0); + if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); } } if (count($listoffiles)) { - foreach($listoffiles as $record) + foreach ($listoffiles as $record) { - $max=($maxfilenamelength?$maxfilenamelength:28); - $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'], $max, 'middle'); + $max = ($maxfilenamelength ? $maxfilenamelength : 28); + $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle'); } } else { - $liste[0]=$obj->label.': '.$langs->trans("None"); + $liste[0] = $obj->label.': '.$langs->trans("None"); } } else @@ -1685,14 +1685,14 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) { global $_Avery_Labels; include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php'; - foreach($_Avery_Labels as $key => $val) + foreach ($_Avery_Labels as $key => $val) { - $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->doc_template_name).' '.$val['name']; + $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name']; } } else // Common usage { - $liste[$obj->id]=$obj->label?$obj->label:$obj->doc_template_name; + $liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name; } } $i++; @@ -1762,7 +1762,7 @@ function getSoapParams() $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT); $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER); $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS); - $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout + $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout //print extension_loaded('soap'); if ($proxyuse) @@ -1829,18 +1829,18 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') // Special cases, to work with non standard path if ($objecttype == 'facture' || $objecttype == 'invoice') { $classpath = 'compta/facture/class'; - $module='facture'; - $myobject='facture'; + $module = 'facture'; + $myobject = 'facture'; } elseif ($objecttype == 'commande' || $objecttype == 'order') { $classpath = 'commande/class'; - $module='commande'; - $myobject='commande'; + $module = 'commande'; + $myobject = 'commande'; } - elseif ($objecttype == 'propal') { + elseif ($objecttype == 'propal') { $classpath = 'comm/propal/class'; } - elseif ($objecttype == 'supplier_proposal') { + elseif ($objecttype == 'supplier_proposal') { $classpath = 'supplier_proposal/class'; } elseif ($objecttype == 'shipping') { @@ -1855,43 +1855,43 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') } elseif ($objecttype == 'contract') { $classpath = 'contrat/class'; - $module='contrat'; - $myobject='contrat'; + $module = 'contrat'; + $myobject = 'contrat'; } elseif ($objecttype == 'member') { $classpath = 'adherents/class'; - $module='adherent'; - $myobject='adherent'; + $module = 'adherent'; + $myobject = 'adherent'; } elseif ($objecttype == 'cabinetmed_cons') { $classpath = 'cabinetmed/class'; - $module='cabinetmed'; - $myobject='cabinetmedcons'; + $module = 'cabinetmed'; + $myobject = 'cabinetmedcons'; } elseif ($objecttype == 'fichinter') { $classpath = 'fichinter/class'; - $module='ficheinter'; - $myobject='fichinter'; + $module = 'ficheinter'; + $myobject = 'fichinter'; } elseif ($objecttype == 'task') { $classpath = 'projet/class'; - $module='projet'; - $myobject='task'; + $module = 'projet'; + $myobject = 'task'; } elseif ($objecttype == 'stock') { $classpath = 'product/stock/class'; - $module='stock'; - $myobject='stock'; + $module = 'stock'; + $myobject = 'stock'; } elseif ($objecttype == 'inventory') { $classpath = 'product/inventory/class'; - $module='stock'; - $myobject='inventory'; + $module = 'stock'; + $myobject = 'inventory'; } elseif ($objecttype == 'mo') { $classpath = 'mrp/class'; - $module='mrp'; - $myobject='mo'; + $module = 'mrp'; + $myobject = 'mo'; } // Generic case for $classfile and $classname @@ -2257,9 +2257,9 @@ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) */ function colorValidateHex($color, $allow_white = true) { - if(!$allow_white && ($color === '#fff' || $color === '#ffffff') ) return false; + if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) return false; - if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid + if (preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid { return true; } @@ -2277,7 +2277,7 @@ function colorValidateHex($color, $allow_white = true) */ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) { - if (empty($ratio)) $ratio = 0; // To avoid null + if (empty($ratio)) $ratio = 0; // To avoid null // Steps should be between -255 and 255. Negative = darker, positive = lighter $ratio = max(-100, min(100, $ratio)); @@ -2293,7 +2293,7 @@ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) $return = '#'; foreach ($color_parts as $color) { - $color = hexdec($color); // Convert to decimal + $color = hexdec($color); // Convert to decimal if ($ratio > 0) // We increase aggressivity { if ($color > 127) $color += ((255 - $color) * ($ratio / 100)); @@ -2607,10 +2607,10 @@ function convertBackOfficeMediasLinksToPublicLinks($notetoshow) { global $dolibarr_main_url_root; // 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 + $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 - $notetoshow=preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow); + $notetoshow = preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow); return $notetoshow; } @@ -2627,7 +2627,7 @@ function price2fec($amount) global $conf; // Clean parameters - if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = '' + if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = '' $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number) // Output decimal number by default diff --git a/htdocs/core/lib/functionsnumtoword.lib.php b/htdocs/core/lib/functionsnumtoword.lib.php index 5fbb799b7dc..94479fe2c28 100644 --- a/htdocs/core/lib/functionsnumtoword.lib.php +++ b/htdocs/core/lib/functionsnumtoword.lib.php @@ -41,97 +41,110 @@ function dol_convertToWord($num, $langs, $currency = false, $centimes = false) if (! $num) { return false; } + if ($centimes && strlen($num) == 1) { $num = $num*10; } - $TNum = explode('.', $num); - $num = (int) $TNum[0]; - $words = array(); - $list1 = array( - '', - $langs->transnoentitiesnoconv('one'), - $langs->transnoentitiesnoconv('two'), - $langs->transnoentitiesnoconv('three'), - $langs->transnoentitiesnoconv('four'), - $langs->transnoentitiesnoconv('five'), - $langs->transnoentitiesnoconv('six'), - $langs->transnoentitiesnoconv('seven'), - $langs->transnoentitiesnoconv('eight'), - $langs->transnoentitiesnoconv('nine'), - $langs->transnoentitiesnoconv('ten'), - $langs->transnoentitiesnoconv('eleven'), - $langs->transnoentitiesnoconv('twelve'), - $langs->transnoentitiesnoconv('thirteen'), - $langs->transnoentitiesnoconv('fourteen'), - $langs->transnoentitiesnoconv('fifteen'), - $langs->transnoentitiesnoconv('sixteen'), - $langs->transnoentitiesnoconv('seventeen'), - $langs->transnoentitiesnoconv('eighteen'), - $langs->transnoentitiesnoconv('nineteen') - ); - $list2 = array( - '', - $langs->transnoentitiesnoconv('ten'), - $langs->transnoentitiesnoconv('twenty'), - $langs->transnoentitiesnoconv('thirty'), - $langs->transnoentitiesnoconv('forty'), - $langs->transnoentitiesnoconv('fifty'), - $langs->transnoentitiesnoconv('sixty'), - $langs->transnoentitiesnoconv('seventy'), - $langs->transnoentitiesnoconv('eighty'), - $langs->transnoentitiesnoconv('ninety'), - $langs->transnoentitiesnoconv('hundred') - ); - $list3 = array( - '', - $langs->transnoentitiesnoconv('thousand'), - $langs->transnoentitiesnoconv('million'), - $langs->transnoentitiesnoconv('billion'), - $langs->transnoentitiesnoconv('trillion'), - $langs->transnoentitiesnoconv('quadrillion') - ); - $num_length = strlen($num); - $levels = (int) (($num_length + 2) / 3); - $max_length = $levels * 3; - $num = substr('00' . $num, -$max_length); - $num_levels = str_split($num, 3); - $nboflevels = count($num_levels); - for ($i = 0; $i < $nboflevels; $i++) { - $levels--; - $hundreds = (int) ($num_levels[$i] / 100); - $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' '.$langs->transnoentities('hundred') . ( $hundreds == 1 ? '' : 's' ) . ' ': ''); - $tens = (int) ($num_levels[$i] % 100); - $singles = ''; - if ( $tens < 20 ) { - $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' ); - } else { - $tens = (int) ($tens / 10); - $tens = ' ' . $list2[$tens] . ' '; - $singles = (int) ($num_levels[$i] % 10); - $singles = ' ' . $list1[$singles] . ' '; - } - $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' ); - } //end for loop - $commas = count($words); - if ($commas > 1) { - $commas = $commas - 1; - } - $concatWords = implode(' ', $words); - // Delete multi whitespaces - $concatWords = trim(preg_replace('/[ ]+/', ' ', $concatWords)); + if (! empty($conf->global->MAIN_MODULE_NUMBERWORDS)) { + if ($currency) { + $type = 1; + } else { + $type = 0; + } - if(!empty($currency)) { - $concatWords .= ' '.$currency; + $concatWords = $langs->getLabelFromNumber($num, $type); + return $concatWords; + } else { + $TNum = explode('.', $num); + $num = (int) $TNum[0]; + $words = array(); + $list1 = array( + '', + $langs->transnoentitiesnoconv('one'), + $langs->transnoentitiesnoconv('two'), + $langs->transnoentitiesnoconv('three'), + $langs->transnoentitiesnoconv('four'), + $langs->transnoentitiesnoconv('five'), + $langs->transnoentitiesnoconv('six'), + $langs->transnoentitiesnoconv('seven'), + $langs->transnoentitiesnoconv('eight'), + $langs->transnoentitiesnoconv('nine'), + $langs->transnoentitiesnoconv('ten'), + $langs->transnoentitiesnoconv('eleven'), + $langs->transnoentitiesnoconv('twelve'), + $langs->transnoentitiesnoconv('thirteen'), + $langs->transnoentitiesnoconv('fourteen'), + $langs->transnoentitiesnoconv('fifteen'), + $langs->transnoentitiesnoconv('sixteen'), + $langs->transnoentitiesnoconv('seventeen'), + $langs->transnoentitiesnoconv('eighteen'), + $langs->transnoentitiesnoconv('nineteen') + ); + $list2 = array( + '', + $langs->transnoentitiesnoconv('ten'), + $langs->transnoentitiesnoconv('twenty'), + $langs->transnoentitiesnoconv('thirty'), + $langs->transnoentitiesnoconv('forty'), + $langs->transnoentitiesnoconv('fifty'), + $langs->transnoentitiesnoconv('sixty'), + $langs->transnoentitiesnoconv('seventy'), + $langs->transnoentitiesnoconv('eighty'), + $langs->transnoentitiesnoconv('ninety'), + $langs->transnoentitiesnoconv('hundred') + ); + $list3 = array( + '', + $langs->transnoentitiesnoconv('thousand'), + $langs->transnoentitiesnoconv('million'), + $langs->transnoentitiesnoconv('billion'), + $langs->transnoentitiesnoconv('trillion'), + $langs->transnoentitiesnoconv('quadrillion') + ); + + $num_length = strlen($num); + $levels = (int) (($num_length + 2) / 3); + $max_length = $levels * 3; + $num = substr('00' . $num, -$max_length); + $num_levels = str_split($num, 3); + $nboflevels = count($num_levels); + for ($i = 0; $i < $nboflevels; $i++) { + $levels--; + $hundreds = (int) ($num_levels[$i] / 100); + $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' '.$langs->transnoentities('hundred') . ( $hundreds == 1 ? '' : 's' ) . ' ': ''); + $tens = (int) ($num_levels[$i] % 100); + $singles = ''; + if ( $tens < 20 ) { + $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' ); + } else { + $tens = (int) ($tens / 10); + $tens = ' ' . $list2[$tens] . ' '; + $singles = (int) ($num_levels[$i] % 10); + $singles = ' ' . $list1[$singles] . ' '; + } + $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' ); + } //end for loop + $commas = count($words); + if ($commas > 1) { + $commas = $commas - 1; + } + $concatWords = implode(' ', $words); + // Delete multi whitespaces + $concatWords = trim(preg_replace('/[ ]+/', ' ', $concatWords)); + + if(!empty($currency)) { + $concatWords .= ' '.$currency; + } + + // If we need to write cents call again this function for cents + if(!empty($TNum[1])) { + if(!empty($currency)) $concatWords .= ' '.$langs->transnoentities('and'); + $concatWords .= ' '.dol_convertToWord($TNum[1], $langs, $currency, true); + if(!empty($currency)) $concatWords .= ' '.$langs->transnoentities('centimes'); + } + return $concatWords; } - - // If we need to write cents call again this function for cents - if(!empty($TNum[1])) { - if(!empty($currency)) $concatWords .= ' '.$langs->transnoentities('and'); - $concatWords .= ' '.dol_convertToWord($TNum[1], $langs, $currency, true); - if(!empty($currency)) $concatWords .= ' '.$langs->transnoentities('centimes'); - } - return $concatWords; } diff --git a/htdocs/core/lib/invoice.lib.php b/htdocs/core/lib/invoice.lib.php index de1334c37a5..15de60eb791 100644 --- a/htdocs/core/lib/invoice.lib.php +++ b/htdocs/core/lib/invoice.lib.php @@ -137,13 +137,6 @@ function invoice_admin_prepare_head() $head[$h][2] = 'payment'; $h++; - if ($conf->global->INVOICE_USE_SITUATION || $conf->global->MAIN_FEATURES_LEVEL >= 1) { - $head[$h][0] = DOL_URL_ROOT.'/admin/facture_situation.php'; - $head[$h][1] = $langs->trans("InvoiceSituation"); - $head[$h][2] = 'situation'; - $h++; - } - // Show more tabs from modules // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab @@ -170,6 +163,11 @@ function invoice_admin_prepare_head() $head[$h][2] = 'attributeslinesrec'; $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/facture_situation.php'; + $head[$h][1] = $langs->trans("InvoiceSituation"); + $head[$h][2] = 'situation'; + $h++; + complete_head_from_modules($conf, $langs, null, $head, $h, 'invoice_admin', 'remove'); return $head; diff --git a/htdocs/core/lib/multicurrency.lib.php b/htdocs/core/lib/multicurrency.lib.php index 529b9697dc5..f17d79c6207 100644 --- a/htdocs/core/lib/multicurrency.lib.php +++ b/htdocs/core/lib/multicurrency.lib.php @@ -1,6 +1,6 @@ - * Copyright (C) 2015 ATM Consulting +/* Copyright (C) 2015 ATM Consulting + * Copyright (C) 2018 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 @@ -44,3 +44,28 @@ function multicurrencyAdminPrepareHead() return $head; } + +/** + * Prepare array with list of currency tabs + * + * @param array $aCurrencies Currencies array + * @return array Array of tabs + */ +function multicurrencyLimitPrepareHead($aCurrencies) +{ + global $langs; + + $i=0; + $head = array(); + + foreach($aCurrencies as $currency) + { + $head[$i][0] = $_SERVER['PHP_SELF'].'?currencycode='.$currency; + $head[$i][1] = $langs->trans("Currency".$currency).' ('.$langs->getCurrencySymbol($currency).')'; + $head[$i][2] = $currency; + + $i++; + } + + return $head; +} diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index a5ba08bb139..e7538725bc2 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -1388,7 +1388,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - "; } - if (!empty($ref_prodserv) && !empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) { $ref_prodserv = ''.$ref_prodserv.''; } + if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { $ref_prodserv = ''.$ref_prodserv.''; } $libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice; // Add an additional description for the category products @@ -1425,7 +1425,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } //print '>'.$outputlangs->charset_output.','.$period; - if (!empty($conf->global->ADD_HTML_FORMATING_INTO_DESC_DOC)) { + if (!empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { $libelleproduitservice .= ''."__N__ ".$period.''; } else { $libelleproduitservice .= "__N__".$period; @@ -2157,7 +2157,7 @@ function pdf_getLinkedObjects($object, $outputlangs) elseif ($objecttype == 'fichinter') { $outputlangs->load('interventions'); - foreach($objects as $elementobject) + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("InterRef"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index b050b560197..16e78d24414 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -263,6 +263,14 @@ function project_timesheet_prepare_head($mode, $fuser = null) $param .= ($mode ? '&mode='.$mode : ''); if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id; + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) + { + $head[$h][0] = DOL_URL_ROOT."/projet/activity/permonth.php".($param?'?'.$param:''); + $head[$h][1] = $langs->trans("InputPerMonth"); + $head[$h][2] = 'inputpermonth'; + $h++; + } + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : ''); @@ -935,7 +943,7 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Warning print ''."\n"; + print ''."\n"; // User /* @@ -1520,7 +1528,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; - print ''."\n"; + print ''."\n"; // User /* @@ -1704,6 +1712,271 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ return $totalforeachday; } +/** + * Output a task line into a perday intput mode + * + * @param string $inc Line output identificator (start to 0, then increased by recursive call) + * @param int $firstdaytoshow First day to show + * @param User|null $fuser Restrict list to user if defined + * @param string $parent Id of parent task to show (0 to show all) + * @param Task[] $lines Array of lines (list of tasks but we will show only if we have a specific role on task) + * @param int $level Level (start to 0, then increased/decrease by recursive call) + * @param string $projectsrole Array of roles user has on project + * @param string $tasksrole Array of roles user has on task + * @param string $mine Show only task lines I am assigned to + * @param int $restricteditformytask 0=No restriction, 1=Enable add time only if task is a task i am affected to + * @param array $isavailable Array with data that say if user is available for several days for morning and afternoon + * @param int $oldprojectforbreak Old project id of last project break + * @param array $TWeek Array of week numbers + * @return array Array with time spent for $fuser for each day of week on tasks in $lines and substasks + */ +function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, &$isavailable, $oldprojectforbreak = 0, $TWeek = array()) +{ + global $conf, $db, $user, $bc, $langs; + global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic; + + $numlines=count($lines); + + $lastprojectid=0; + $workloadforid=array(); + $totalforeachweek=array(); + $lineswithoutlevel0=array(); + + // Create a smaller array with sublevels only to be used later. This increase dramatically performances. + if ($parent == 0) // Always and only if at first level + { + for ($i = 0 ; $i < $numlines ; $i++) + { + if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; + } + } + + //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); + + if (empty($oldprojectforbreak)) + { + $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1); // 0 = start break, -1 = never break + } + + for ($i = 0 ; $i < $numlines ; $i++) + { + if ($parent == 0) $level = 0; + + if ($lines[$i]->fk_task_parent == $parent) + { + // If we want all or we have a role on task, we show it + if (empty($mine) || ! empty($tasksrole[$lines[$i]->id])) + { + //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); + + // Break on a new project + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) + { + $lastprojectid=$lines[$i]->fk_project; + $projectstatic->id = $lines[$i]->fk_project; + } + + //var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); + //var_dump($projectstatic->weekWorkLoadPerTask); + if (empty($workloadforid[$projectstatic->id])) + { + $projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + $workloadforid[$projectstatic->id]=1; + } + //var_dump($projectstatic->weekWorkLoadPerTask); + //var_dump('--- '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); + + $projectstatic->id=$lines[$i]->fk_project; + $projectstatic->ref=$lines[$i]->projectref; + $projectstatic->title=$lines[$i]->projectlabel; + $projectstatic->public=$lines[$i]->public; + $projectstatic->thirdparty_name=$lines[$i]->thirdparty_name; + + $taskstatic->id=$lines[$i]->id; + $taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id); + $taskstatic->label=$lines[$i]->label; + $taskstatic->date_start=$lines[$i]->date_start; + $taskstatic->date_end=$lines[$i]->date_end; + + $thirdpartystatic->id=$lines[$i]->thirdparty_id; + $thirdpartystatic->name=$lines[$i]->thirdparty_name; + $thirdpartystatic->email=$lines[$i]->thirdparty_email; + + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) + { + print ''."\n"; + print ''; + print ''; + } + + if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + print ''."\n"; + + // User + /* + print ''; + */ + + // Project + /*print '";*/ + + // Thirdparty + /*print '';*/ + + // Ref + print '\n"; + + // Planned Workload + print ''; + + // Progress declared % + print ''; + + // Time spent by everybody + print '\n"; + + // Time spent by user + print '\n"; + + $disabledproject=1;$disabledtask=1; + //print "x".$lines[$i]->fk_project; + //var_dump($lines[$i]); + //var_dump($projectsrole[$lines[$i]->fk_project]); + // If at least one role for project + if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) + { + $disabledproject=0; + $disabledtask=0; + } + // If $restricteditformytask is on and I have no role on task, i disable edit + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) + { + $disabledtask=1; + } + + //var_dump($projectstatic->weekWorkLoadPerTask); + //TODO + // Fields to show current time + $tableCell=''; $modeinput='hours'; + $TFirstDay = getFirstDayOfEachWeek($TWeek, date('Y', $firstdaytoshow)); + $TFirstDay[reset($TWeek)] = 1; + foreach($TFirstDay as &$fday) { + $fday--; + } + foreach ($TWeek as $weekNb) + { + $weekWorkLoad = $projectstatic->monthWorkLoadPerTask[$weekNb][$lines[$i]->id]; + $totalforeachweek[$weekNb]+=$weekWorkLoad; + + $alreadyspent=''; + if ($weekWorkLoad > 0) $alreadyspent=convertSecondToTime($weekWorkLoad, 'allhourmin'); + $alttitle=$langs->trans("AddHereTimeSpentForWeek", $weekNb); + + + $tableCell =''; + print $tableCell; + } + + // Warning + print ''; + + print "\n"; + } + + // Call to show task with a lower level (task under the current task) + $inc++; + $level++; + if ($lines[$i]->id > 0) + { + //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); + //var_dump($totalforeachday); + $ret = projectLinesPerMonth($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $TWeek); + //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); + //var_dump($ret); + foreach($ret as $key => $val) + { + $totalforeachweek[$key]+=$val; + } + //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); + //var_dump($totalforeachday); + } + $level--; + } + else + { + //$level--; + } + } + + return $totalforeachweek; +} + /** * Search in task lines with a particular parent if there is a task for a particular user (in taskrole) diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php index 5a7b8342bd6..c09f43cdedd 100644 --- a/htdocs/core/lib/security.lib.php +++ b/htdocs/core/lib/security.lib.php @@ -168,10 +168,10 @@ function dol_verifyHash($chain, $hash, $type = '0') * If GETPOST('action','aZ09') defined, we also check write and delete permission. * * @param User $user User to check - * @param string $features Features to check (it must be module name. Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...) + * @param string $features Features to check (it must be module $object->element. Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...) * @param int $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional). * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany modume. Param not used if objectid is null (optional). - * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'level1|level2'. + * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'sublevela|sublevelb'. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional) * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional) * @param int $isdraft 1=The object with id=$objectid is a draft @@ -188,6 +188,11 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select; //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."
"; + if ($features == 'facturerec') $features = 'facture'; + if ($features == 'mo') $features = 'mrp'; + if ($features == 'member') $features = 'adherent'; + if ($features == 'subscription') { $features = 'adherent'; $feature2 = 'cotisation'; }; + // Get more permissions checks from hooks $parameters = array('features'=>$features, 'objectid'=>$objectid, 'idtype'=>$dbt_select); $reshook = $hookmanager->executeHooks('restrictedArea', $parameters); diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php index 18d1e9c680a..c943220a5ac 100644 --- a/htdocs/core/lib/security2.lib.php +++ b/htdocs/core/lib/security2.lib.php @@ -34,9 +34,9 @@ */ function dol_getwebuser($mode) { - $t='?'; - if ($mode=='user') $t=getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty - if ($mode=='group') $t=getenv('APACHE_RUN_GROUP'); + $t = '?'; + if ($mode == 'user') $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty + if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP'); return $t; } @@ -52,11 +52,11 @@ function dol_getwebuser($mode) */ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context = '') { - global $conf,$langs; + global $conf, $langs; //global $dolauthmode; // To return authentication finally used // Check parameters - if ($entitytotest == '') $entitytotest=1; + if ($entitytotest == '') $entitytotest = 1; dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode)); $login = ''; @@ -64,42 +64,42 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth // Validation of login/pass/entity with standard modules if (empty($login)) { - $test=true; - foreach($authmode as $mode) + $test = true; + foreach ($authmode as $mode) { - if ($test && $mode && ! $login) + if ($test && $mode && !$login) { // Validation of login/pass/entity for mode $mode - $mode=trim($mode); - $authfile='functions_'.$mode.'.php'; - $fullauthfile=''; + $mode = trim($mode); + $authfile = 'functions_'.$mode.'.php'; + $fullauthfile = ''; - $dirlogin=array_merge(array("/core/login"), (array) $conf->modules_parts['login']); - foreach($dirlogin as $reldir) + $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']); + foreach ($dirlogin as $reldir) { - $dir=dol_buildpath($reldir, 0); - $newdir=dol_osencode($dir); + $dir = dol_buildpath($reldir, 0); + $newdir = dol_osencode($dir); // Check if file found (do not use dol_is_file to avoid loading files.lib.php) - $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir)?'':'/').$authfile; - if (is_file($tmpnewauthfile)) $fullauthfile=$tmpnewauthfile; + $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile; + if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile; } - $result=false; - if ($fullauthfile) $result=include_once $fullauthfile; + $result = false; + if ($fullauthfile) $result = include_once $fullauthfile; if ($fullauthfile && $result) { // Call function to check user/password - $function='check_user_password_'.$mode; - $login=call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); + $function = 'check_user_password_'.$mode; + $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); if ($login) // Login is successfull { - $test=false; // To stop once at first login success - $conf->authmode=$mode; // This properties is defined only when logged to say what mode was successfully used - $dol_tz=GETPOST('tz'); - $dol_dst=GETPOST('dst'); - $dol_screenwidth=GETPOST('screenwidth'); - $dol_screenheight=GETPOST('screenheight'); + $test = false; // To stop once at first login success + $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used + $dol_tz = GETPOST('tz'); + $dol_dst = GETPOST('dst'); + $dol_screenwidth = GETPOST('screenwidth'); + $dol_screenheight = GETPOST('screenheight'); } } else @@ -109,7 +109,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth // Load translation files required by the page $langs->loadLangs(array('other', 'main', 'errors')); - $_SESSION["dol_loginmesg"]=$langs->trans("ErrorFailedToLoadLoginFileForMode", $mode); + $_SESSION["dol_loginmesg"] = $langs->trans("ErrorFailedToLoadLoginFileForMode", $mode); } } } @@ -119,7 +119,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth } -if (! function_exists('dol_loginfunction')) +if (!function_exists('dol_loginfunction')) { /** * Show Dolibarr default login page. @@ -135,22 +135,22 @@ if (! function_exists('dol_loginfunction')) global $dolibarr_main_demo, $db; global $hookmanager; - $langs->loadLangs(array("main","other","help","admin")); + $langs->loadLangs(array("main", "other", "help", "admin")); // Instantiate hooks of thirdparty module only if not already define $hookmanager->initHooks(array('mainloginpage')); - $main_authentication=$conf->file->main_authentication; + $main_authentication = $conf->file->main_authentication; - $session_name=session_name(); // Get current session name + $session_name = session_name(); // Get current session name $dol_url_root = DOL_URL_ROOT; // Title - $appli=constant('DOL_APPLICATION_TITLE'); - $title=$appli.' '.constant('DOL_VERSION'); - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title=$conf->global->MAIN_APPLICATION_TITLE; - $titletruedolibarrversion=constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version + $appli = constant('DOL_APPLICATION_TITLE'); + $title = $appli.' '.constant('DOL_VERSION'); + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $conf->global->MAIN_APPLICATION_TITLE; + $titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version // Note: $conf->css looks like '/theme/eldy/style.css.php' /* @@ -171,13 +171,13 @@ if (! function_exists('dol_loginfunction')) */ // Select templates dir - if (! empty($conf->modules_parts['tpl'])) // Using this feature slow down application + if (!empty($conf->modules_parts['tpl'])) // Using this feature slow down application { - $dirtpls=array_merge($conf->modules_parts['tpl'], array('/core/tpl/')); - foreach($dirtpls as $reldir) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl/')); + foreach ($dirtpls as $reldir) { - $tmp=dol_buildpath($reldir.'login.tpl.php'); - if (file_exists($tmp)) { $template_dir=preg_replace('/login\.tpl\.php$/', '', $tmp); break; } + $tmp = dol_buildpath($reldir.'login.tpl.php'); + if (file_exists($tmp)) { $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; } } } else @@ -186,116 +186,116 @@ if (! function_exists('dol_loginfunction')) } // Set cookie for timeout management - $prefix=dol_getprefix(''); - $sessiontimeout='DOLSESSTIMEOUT_'.$prefix; - if (! empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, false, true); + $prefix = dol_getprefix(''); + $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; + if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, false, true); - if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"]=GETPOST('urlfrom', 'alpha'); + if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); else unset($_SESSION["urlfrom"]); - if (! GETPOST("username", 'alpha')) $focus_element='username'; - else $focus_element='password'; + if (!GETPOST("username", 'alpha')) $focus_element = 'username'; + else $focus_element = 'password'; - $demologin=''; - $demopassword=''; - if (! empty($dolibarr_main_demo)) + $demologin = ''; + $demopassword = ''; + if (!empty($dolibarr_main_demo)) { - $tab=explode(',', $dolibarr_main_demo); - $demologin=$tab[0]; - $demopassword=$tab[1]; + $tab = explode(',', $dolibarr_main_demo); + $demologin = $tab[0]; + $demopassword = $tab[1]; } // Execute hook getLoginPageOptions (for table) - $parameters=array('entity' => GETPOST('entity', 'int')); - $reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters); // Note that $action and $object may have been modified by some hooks. + $parameters = array('entity' => GETPOST('entity', 'int')); + $reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters); // Note that $action and $object may have been modified by some hooks. $morelogincontent = $hookmanager->resPrint; // Execute hook getLoginPageExtraOptions (eg for js) - $parameters=array('entity' => GETPOST('entity', 'int')); - $reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters); // Note that $action and $object may have been modified by some hooks. + $parameters = array('entity' => GETPOST('entity', 'int')); + $reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters); // Note that $action and $object may have been modified by some hooks. $moreloginextracontent = $hookmanager->resPrint; // Login - $login = (! empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin)); + $login = (!empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin)); $password = $demopassword; // Show logo (search in order: small company logo, large company logo, theme logo, common logo) - $width=0; + $width = 0; $urllogo=DOL_URL_ROOT.'/theme/common/login_logo.png'; - if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) + if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_small); + $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_small); } - elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) + elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/'.$mysoc->logo); - $width=128; + $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/'.$mysoc->logo); + $width = 128; } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png')) { - $urllogo=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'; + $urllogo = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'; } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png')) { - $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png'; + $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.png'; } // Security graphical code - $captcha=0; - $captcha_refresh=''; - if (function_exists("imagecreatefrompng") && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) + $captcha = 0; + $captcha_refresh = ''; + if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) { - $captcha=1; - $captcha_refresh=img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"'); + $captcha = 1; + $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"'); } // Extra link - $forgetpasslink=0; - $helpcenterlink=0; + $forgetpasslink = 0; + $helpcenterlink = 0; if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) { - $forgetpasslink=1; + $forgetpasslink = 1; } if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { - $helpcenterlink=1; + $helpcenterlink = 1; } } // Home message - $main_home=''; - if (! empty($conf->global->MAIN_HOME)) + $main_home = ''; + if (!empty($conf->global->MAIN_HOME)) { - $substitutionarray=getCommonSubstitutionArray($langs); + $substitutionarray = getCommonSubstitutionArray($langs); complete_substitutions_array($substitutionarray, $langs); $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs); - $main_home=dol_htmlcleanlastbr($texttoshow); + $main_home = dol_htmlcleanlastbr($texttoshow); } // Google AD - $main_google_ad_client = ((! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))?1:0); + $main_google_ad_client = ((!empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) ? 1 : 0); // Set jquery theme - $dol_loginmesg = (! empty($_SESSION["dol_loginmesg"])?$_SESSION["dol_loginmesg"]:''); + $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : ''); $favicon = DOL_URL_ROOT.'/theme/dolibarr_logo_256x256.png'; - if (! empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); - if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL; + if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); + if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL; $jquerytheme = 'base'; - if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover - $dol_hide_topmenu=GETPOST('dol_hide_topmenu', 'int'); - $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu', 'int'); - $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen', 'int'); - $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover', 'int'); - $dol_use_jmobile=GETPOST('dol_use_jmobile', 'int'); + $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int'); + $dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int'); + $dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int'); + $dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int'); + $dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); // Include login page template include $template_dir.'login.tpl.php'; @@ -316,20 +316,20 @@ if (! function_exists('dol_loginfunction')) function makesalt($type = CRYPT_SALT_LENGTH) { dol_syslog("makesalt type=".$type); - switch($type) + switch ($type) { case 12: // 8 + 4 - $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; + $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise) - $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break; + $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; case 2: // 2 default: // by default, fall back on Standard DES (should work everywhere) - $saltlen=2; $saltprefix=''; $saltsuffix=''; break; + $saltlen = 2; $saltprefix = ''; $saltsuffix = ''; break; } - $salt=''; - while(dol_strlen($salt) < $saltlen) $salt.=chr(mt_rand(64, 126)); + $salt = ''; + while (dol_strlen($salt) < $saltlen) $salt .= chr(mt_rand(64, 126)); - $result=$saltprefix.$salt.$saltsuffix; + $result = $saltprefix.$salt.$saltsuffix; dol_syslog("makesalt return=".$result); return $result; } @@ -344,35 +344,35 @@ function encodedecode_dbpassconf($level = 0) { dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG); $config = ''; - $passwd=''; - $passwd_crypted=''; + $passwd = ''; + $passwd_crypted = ''; if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) { - while(!feof($fp)) + while (!feof($fp)) { $buffer = fgets($fp, 4096); - $lineofpass=0; + $lineofpass = 0; if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) // Old way to save crypted value { - $val = trim($reg[1]); // This also remove CR/LF - $val=preg_replace('/^["\']/', '', $val); - $val=preg_replace('/["\'][\s;]*$/', '', $val); - if (! empty($val)) + $val = trim($reg[1]); // This also remove CR/LF + $val = preg_replace('/^["\']/', '', $val); + $val = preg_replace('/["\'][\s;]*$/', '', $val); + if (!empty($val)) { $passwd_crypted = $val; $val = dol_decode($val); $passwd = $val; - $lineofpass=1; + $lineofpass = 1; } } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { - $val = trim($reg[1]); // This also remove CR/LF - $val=preg_replace('/^["\']/', '', $val); - $val=preg_replace('/["\'][\s;]*$/', '', $val); + $val = trim($reg[1]); // This also remove CR/LF + $val = preg_replace('/^["\']/', '', $val); + $val = preg_replace('/["\'][\s;]*$/', '', $val); if (preg_match('/crypted:/i', $buffer)) { $val = preg_replace('/crypted:/i', '', $val); @@ -386,7 +386,7 @@ function encodedecode_dbpassconf($level = 0) $val = dol_encode($val); $passwd_crypted = $val; } - $lineofpass=1; + $lineofpass = 1; } // Output line @@ -413,7 +413,7 @@ function encodedecode_dbpassconf($level = 0) fclose($fp); // Write new conf file - $file=DOL_DOCUMENT_ROOT.'/conf/conf.php'; + $file = DOL_DOCUMENT_ROOT.'/conf/conf.php'; if ($fp = @fopen($file, 'w')) { fputs($fp, $config); @@ -451,17 +451,17 @@ function encodedecode_dbpassconf($level = 0) */ function getRandomPassword($generic = false, $replaceambiguouschars = null, $length = 32) { - global $db,$conf,$langs,$user; + global $db, $conf, $langs, $user; - $generated_password=''; + $generated_password = ''; if ($generic) { $lowercase = "qwertyuiopasdfghjklzxcvbnm"; $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP"; $numbers = "1234567890"; $randomCode = ""; - $nbofchar = round($length/3); - $nbofcharlast = ($length - 2*$nbofchar); + $nbofchar = round($length / 3); + $nbofcharlast = ($length - 2 * $nbofchar); //var_dump($nbofchar.'-'.$nbofcharlast); if (function_exists('random_int')) // Cryptographic random { @@ -478,7 +478,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $randomCode .= $numbers{random_int(0, $max)}; } - $generated_password=str_shuffle($randomCode); + $generated_password = str_shuffle($randomCode); } else // Old platform, non cryptographic random { @@ -495,17 +495,17 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $randomCode .= $numbers{mt_rand(0, $max)}; } - $generated_password=str_shuffle($randomCode); + $generated_password = str_shuffle($randomCode); } } - elseif (! empty($conf->global->USER_PASSWORD_GENERATED)) + elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) { - $nomclass="modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); - $nomfichier=$nomclass.".class.php"; + $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); + $nomfichier = $nomclass.".class.php"; //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass; require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier; - $genhandler=new $nomclass($db, $conf, $langs, $user); - $generated_password=$genhandler->getNewGeneratedPassword(); + $genhandler = new $nomclass($db, $conf, $langs, $user); + $generated_password = $genhandler->getNewGeneratedPassword(); unset($genhandler); } @@ -516,11 +516,11 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $max = strlen($numbers) - 1; if (function_exists('random_int')) // Cryptographic random { - $generated_password=str_replace($replaceambiguouschars, $numbers{random_int(0, $max)}, $generated_password); + $generated_password = str_replace($replaceambiguouschars, $numbers{random_int(0, $max)}, $generated_password); } else { - $generated_password=str_replace($replaceambiguouschars, $numbers{mt_rand(0, $max)}, $generated_password); + $generated_password = str_replace($replaceambiguouschars, $numbers{mt_rand(0, $max)}, $generated_password); } } diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php index 861017b2844..278e53eef6e 100644 --- a/htdocs/core/modules/DolibarrModules.class.php +++ b/htdocs/core/modules/DolibarrModules.class.php @@ -85,7 +85,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it /** * @var string Module position on 2 digits */ - public $module_position='50'; + public $module_position = '50'; /** * @var string Module name @@ -222,9 +222,9 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it public $export_permission; public $export_fields_array; - public $export_TypeFields_array; // Array of key=>type where type can be 'Numeric', 'Date', 'Text', 'Boolean', 'Status', 'List:xxx:login:rowid' + public $export_TypeFields_array; // Array of key=>type where type can be 'Numeric', 'Date', 'Text', 'Boolean', 'Status', 'List:xxx:login:rowid' public $export_entities_array; - public $export_special_array; // special or computed field + public $export_special_array; // special or computed field public $export_dependencies_array; public $export_sql_start; public $export_sql_end; @@ -367,75 +367,75 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { // phpcs:enable global $conf; - $err=0; + $err = 0; $this->db->begin(); // Insert activation module constant - if (! $err) { - $err+=$this->_active(); + if (!$err) { + $err += $this->_active(); } // Insert new pages for tabs (into llx_const) - if (! $err) { - $err+=$this->insert_tabs(); + if (!$err) { + $err += $this->insert_tabs(); } // Insert activation of module's parts - if (! $err) { - $err+=$this->insert_module_parts(); + if (!$err) { + $err += $this->insert_module_parts(); } // Insert constant defined by modules (into llx_const) - if (! $err && ! preg_match('/newboxdefonly/', $options)) { - $err+=$this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade + if (!$err && !preg_match('/newboxdefonly/', $options)) { + $err += $this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade } // Insert boxes def into llx_boxes_def and boxes setup (into llx_boxes) - if (! $err && ! preg_match('/noboxes/', $options)) { - $err+=$this->insert_boxes($options); + if (!$err && !preg_match('/noboxes/', $options)) { + $err += $this->insert_boxes($options); } // Insert cron job entries (entry in llx_cronjobs) - if (! $err) { - $err+=$this->insert_cronjobs(); + if (!$err) { + $err += $this->insert_cronjobs(); } // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user. - if (! $err) { - $err+=$this->insert_permissions(1, null, 1); + if (!$err) { + $err += $this->insert_permissions(1, null, 1); } // Insert specific menus entries into database - if (! $err) { - $err+=$this->insert_menus(); + if (!$err) { + $err += $this->insert_menus(); } // Create module's directories - if (! $err) { - $err+=$this->create_dirs(); + if (!$err) { + $err += $this->create_dirs(); } // Execute addons requests - $num=count($array_sql); + $num = count($array_sql); for ($i = 0; $i < $num; $i++) { - if (! $err) { - $val=$array_sql[$i]; - $sql=$val; - $ignoreerror=0; + if (!$err) { + $val = $array_sql[$i]; + $sql = $val; + $ignoreerror = 0; if (is_array($val)) { - $sql=$val['sql']; - $ignoreerror=$val['ignoreerror']; + $sql = $val['sql']; + $ignoreerror = $val['ignoreerror']; } // Add current entity id - $sql=str_replace('__ENTITY__', $conf->entity, $sql); + $sql = str_replace('__ENTITY__', $conf->entity, $sql); dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror."", LOG_DEBUG); - $result=$this->db->query($sql, $ignoreerror); - if (! $result) { - if (! $ignoreerror) { - $this->error=$this->db->lasterror(); + $result = $this->db->query($sql, $ignoreerror); + if (!$result) { + if (!$ignoreerror) { + $this->error = $this->db->lasterror(); $err++; } else @@ -447,7 +447,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } // Return code - if (! $err) { + if (!$err) { $this->db->commit(); return 1; } @@ -470,71 +470,71 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it protected function _remove($array_sql, $options = '') { // phpcs:enable - $err=0; + $err = 0; $this->db->begin(); // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const) - if (! $err) { - $err+=$this->_unactive(); + if (!$err) { + $err += $this->_unactive(); } // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const) - if (! $err) { - $err+=$this->delete_tabs(); + if (!$err) { + $err += $this->delete_tabs(); } // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const) - if (! $err) { - $err+=$this->delete_module_parts(); + if (!$err) { + $err += $this->delete_module_parts(); } // Remove constants defined by modules - if (! $err) { - $err+=$this->delete_const(); + if (!$err) { + $err += $this->delete_const(); } // Remove list of module's available boxes (entry in llx_boxes) - if (! $err && ! preg_match('/(newboxdefonly|noboxes)/', $options)) { - $err+=$this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only + if (!$err && !preg_match('/(newboxdefonly|noboxes)/', $options)) { + $err += $this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only } // Remove list of module's cron job entries (entry in llx_cronjobs) - if (! $err) { - $err+=$this->delete_cronjobs(); + if (!$err) { + $err += $this->delete_cronjobs(); } // Remove module's permissions from list of available permissions (entries in llx_rights_def) - if (! $err) { - $err+=$this->delete_permissions(); + if (!$err) { + $err += $this->delete_permissions(); } // Remove module's menus (entries in llx_menu) - if (! $err) { - $err+=$this->delete_menus(); + if (!$err) { + $err += $this->delete_menus(); } // Remove module's directories - if (! $err) { - $err+=$this->delete_dirs(); + if (!$err) { + $err += $this->delete_dirs(); } // Run complementary sql requests - $num=count($array_sql); + $num = count($array_sql); for ($i = 0; $i < $num; $i++) { - if (! $err) { + if (!$err) { dol_syslog(get_class($this)."::_remove", LOG_DEBUG); - $result=$this->db->query($array_sql[$i]); - if (! $result) { - $this->error=$this->db->error(); + $result = $this->db->query($array_sql[$i]); + if (!$result) { + $this->error = $this->db->error(); $err++; } } } // Return code - if (! $err) { + if (!$err) { $this->db->commit(); return 1; } @@ -565,7 +565,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { // If module name translation using it's unique id does not exist, we try to use its name to find translation if (is_array($this->langfiles)) { - foreach($this->langfiles as $val) + foreach ($this->langfiles as $val) { if ($val) { $langs->load($val); } @@ -601,7 +601,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { // If module description translation does not exist using its unique id, we can use its name to find translation if (is_array($this->langfiles)) { - foreach($this->langfiles as $val) + foreach ($this->langfiles as $val) { if ($val) { $langs->load($val); } @@ -659,9 +659,9 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it else { // Mostly for internal modules - if (! empty($this->descriptionlong)) { + if (!empty($this->descriptionlong)) { if (is_array($this->langfiles)) { - foreach($this->langfiles as $val) + foreach ($this->langfiles as $val) { if ($val) { $langs->load($val); } @@ -684,7 +684,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { global $langs; - $filefound= false; + $filefound = false; // Define path to file README.md. // First check README-la_LA.md then README-la.md then README.md @@ -692,21 +692,21 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it if (dol_is_file($pathoffile)) { $filefound = true; } - if (! $filefound) { - $tmp=explode('_', $langs->defaultlang); + if (!$filefound) { + $tmp = explode('_', $langs->defaultlang); $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0); if (dol_is_file($pathoffile)) { $filefound = true; } } - if (! $filefound) { + if (!$filefound) { $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0); if (dol_is_file($pathoffile)) { $filefound = true; } } - return ($filefound?$pathoffile:''); + return ($filefound ? $pathoffile : ''); } @@ -723,7 +723,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - $filefound= false; + $filefound = false; // Define path to file README.md. // First check ChangeLog-la_LA.md then ChangeLog.md @@ -731,7 +731,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it if (dol_is_file($pathoffile)) { $filefound = true; } - if (! $filefound) { + if (!$filefound) { $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0); if (dol_is_file($pathoffile)) { $filefound = true; @@ -788,23 +788,23 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it global $langs; $langs->load("admin"); - $ret=''; + $ret = ''; - $newversion=preg_replace('/_deprecated/', '', $this->version); + $newversion = preg_replace('/_deprecated/', '', $this->version); if ($newversion == 'experimental') { - $ret=($translated?$langs->transnoentitiesnoconv("VersionExperimental"):$newversion); + $ret = ($translated ? $langs->transnoentitiesnoconv("VersionExperimental") : $newversion); } elseif ($newversion == 'development') { - $ret=($translated?$langs->transnoentitiesnoconv("VersionDevelopment"):$newversion); + $ret = ($translated ? $langs->transnoentitiesnoconv("VersionDevelopment") : $newversion); } elseif ($newversion == 'dolibarr') { - $ret=DOL_VERSION; + $ret = DOL_VERSION; } elseif ($newversion) { - $ret=$newversion; + $ret = $newversion; } else { - $ret=($translated?$langs->transnoentitiesnoconv("VersionUnknown"):'unknown'); + $ret = ($translated ? $langs->transnoentitiesnoconv("VersionUnknown") : 'unknown'); } if (preg_match('/_deprecated/', $this->version)) { - $ret.=($translated?' ('.$langs->transnoentitiesnoconv("Deprecated").')':$this->version); + $ret .= ($translated ? ' ('.$langs->transnoentitiesnoconv("Deprecated").')' : $this->version); } return $ret; } @@ -820,10 +820,10 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') { return 'core'; } - if (! empty($this->version) && ! in_array($this->version, array('experimental','development'))) { + if (!empty($this->version) && !in_array($this->version, array('experimental', 'development'))) { return 'external'; } - if (! empty($this->editor_name) || ! empty($this->editor_url)) { + if (!empty($this->editor_name) || !empty($this->editor_url)) { return 'external'; } if ($this->numero >= 100000) { @@ -854,7 +854,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { global $langs; - $langstring="ExportDataset_".$this->export_code[$r]; + $langstring = "ExportDataset_".$this->export_code[$r]; if ($langs->trans($langstring) == $langstring) { // Translation not found return $langs->trans($this->export_label[$r]); @@ -878,7 +878,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it { global $langs; - $langstring="ImportDataset_".$this->import_code[$r]; + $langstring = "ImportDataset_".$this->import_code[$r]; //print "x".$langstring; if ($langs->trans($langstring) == $langstring) { // Translation not found @@ -904,18 +904,18 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $err = 0; $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$conf->entity.")"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql .= " AND entity IN (0, ".$conf->entity.")"; dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $err++; } else { - $obj=$this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); if ($obj) { return $this->db->jdate($obj->tms); } @@ -937,21 +937,21 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $err = 0; $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$conf->entity.")"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql .= " AND entity IN (0, ".$conf->entity.")"; dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { $err++; } else { - $obj=$this->db->fetch_object($resql); - $tmp=array(); + $obj = $this->db->fetch_object($resql); + $tmp = array(); if ($obj->note) { - $tmp=json_decode($obj->note, true); + $tmp = json_decode($obj->note, true); } if ($obj) { return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms)); @@ -976,29 +976,29 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $err = 0; // Common module - $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); + $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity); $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$entity.")"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql .= " AND entity IN (0, ".$entity.")"; dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { + $resql = $this->db->query($sql); + if (!$resql) { $err++; } - $note=json_encode(array('authorid'=>(is_object($user)?$user->id:0), 'ip'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']))); + $note = json_encode(array('authorid'=>(is_object($user) ? $user->id : 0), 'ip'=>(empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']))); $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES"; - $sql.= " (".$this->db->encrypt($this->const_name, 1); - $sql.= ", ".$this->db->encrypt('1', 1); - $sql.= ", 0, ".$entity; - $sql.= ", '".$this->db->escape($note)."')"; + $sql .= " (".$this->db->encrypt($this->const_name, 1); + $sql .= ", ".$this->db->encrypt('1', 1); + $sql .= ", 0, ".$entity; + $sql .= ", '".$this->db->escape($note)."')"; dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $err++; + $resql = $this->db->query($sql); + if (!$resql) { $err++; } return $err; @@ -1019,11 +1019,11 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $err = 0; // Common module - $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); + $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity); $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$entity.")"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql .= " AND entity IN (0, ".$entity.")"; dol_syslog(get_class($this)."::_unactive", LOG_DEBUG); $this->db->query($sql); @@ -1047,37 +1047,37 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $error=0; - $dirfound=0; + $error = 0; + $dirfound = 0; if (empty($reldir)) { return 1; } - include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; $ok = 1; - foreach($conf->file->dol_document_root as $dirroot) + foreach ($conf->file->dol_document_root as $dirroot) { if ($ok) { $dir = $dirroot.$reldir; $ok = 0; - $handle=@opendir($dir); // Dir may not exists + $handle = @opendir($dir); // Dir may not exists if (is_resource($handle)) { $dirfound++; // Run llx_mytable.sql files, then llx_mytable_*.sql $files = array(); - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { $files[] = $file; } sort($files); foreach ($files as $file) { - if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') { - $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1); + if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') { + $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1); if ($result <= 0) { $error++; } } @@ -1087,7 +1087,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql $files = array(); - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { $files[] = $file; } @@ -1095,7 +1095,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it foreach ($files as $file) { if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') { - $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1); + $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1); if ($result <= 0) { $error++; } } @@ -1105,15 +1105,15 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // Run data_xxx.sql files (Must be done after llx_mytable.key.sql) $files = array(); - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { $files[] = $file; } sort($files); foreach ($files as $file) { - if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') { - $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1); + if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') { + $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1); if ($result <= 0) { $error++; } } @@ -1123,15 +1123,15 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // Run update_xxx.sql files $files = array(); - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { $files[] = $file; } sort($files); foreach ($files as $file) { - if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') { - $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1); + if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') { + $result = run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG) ? 1 : 0, '', 1); if ($result <= 0) { $error++; } } @@ -1146,7 +1146,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } } - if (! $dirfound) { + if (!$dirfound) { dol_syslog("A module ask to load sql files into ".$reldir." but this directory was not found.", LOG_WARNING); } return $ok; @@ -1164,11 +1164,11 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it public function insert_boxes($option = '') { // phpcs:enable - include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; global $conf; - $err=0; + $err = 0; if (is_array($this->boxes)) { dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); @@ -1177,65 +1177,65 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it foreach ($this->boxes as $key => $value) { - $file = isset($this->boxes[$key]['file'])?$this->boxes[$key]['file']:''; - $note = isset($this->boxes[$key]['note'])?$this->boxes[$key]['note']:''; - $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton'])?$this->boxes[$key]['enabledbydefaulton']:'Home'; + $file = isset($this->boxes[$key]['file']) ? $this->boxes[$key]['file'] : ''; + $note = isset($this->boxes[$key]['note']) ? $this->boxes[$key]['note'] : ''; + $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton']) ? $this->boxes[$key]['enabledbydefaulton'] : 'Home'; - if (empty($file)) { $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility + if (empty($file)) { $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility } - if (empty($note)) { $note = isset($this->boxes[$key][2])?$this->boxes[$key][2]:''; // For backward compatibility + if (empty($note)) { $note = isset($this->boxes[$key][2]) ? $this->boxes[$key][2] : ''; // For backward compatibility } // Search if boxes def already present $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE file = '".$this->db->escape($file)."'"; - $sql.= " AND entity = ".$conf->entity; - if ($note) { $sql.=" AND note ='".$this->db->escape($note)."'"; + $sql .= " WHERE file = '".$this->db->escape($file)."'"; + $sql .= " AND entity = ".$conf->entity; + if ($note) { $sql .= " AND note ='".$this->db->escape($note)."'"; } - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); if ($obj->nb == 0) { $this->db->begin(); - if (! $err) { + if (!$err) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)"; - $sql.= " VALUES ('".$this->db->escape($file)."', "; - $sql.= $conf->entity.", "; - $sql.= $note?"'".$this->db->escape($note)."'":"null"; - $sql.= ")"; + $sql .= " VALUES ('".$this->db->escape($file)."', "; + $sql .= $conf->entity.", "; + $sql .= $note ? "'".$this->db->escape($note)."'" : "null"; + $sql .= ")"; dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $err++; + $resql = $this->db->query($sql); + if (!$resql) { $err++; } } - if (! $err && ! preg_match('/newboxdefonly/', $option)) { - $lastid=$this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid"); + if (!$err && !preg_match('/newboxdefonly/', $option)) { + $lastid = $this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid"); foreach ($pos_name as $key2 => $val2) { //print 'key2='.$key2.'-val2='.$val2."
\n"; - if ($enabledbydefaulton && $val2 != $enabledbydefaulton) { continue; // Not enabled by default onto this page. + if ($enabledbydefaulton && $val2 != $enabledbydefaulton) { continue; // Not enabled by default onto this page. } $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id,position,box_order,fk_user,entity)"; - $sql.= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")"; + $sql .= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")"; dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2."", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { $err++; + $resql = $this->db->query($sql); + if (!$resql) { $err++; } } } - if (! $err) { + if (!$err) { $this->db->commit(); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); } } @@ -1243,7 +1243,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $err++; } } @@ -1264,26 +1264,26 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; if (is_array($this->boxes)) { foreach ($this->boxes as $key => $value) { //$titre = $this->boxes[$key][0]; - $file = $this->boxes[$key]['file']; + $file = $this->boxes[$key]['file']; //$note = $this->boxes[$key][2]; // TODO If the box is also included by another module and the other module is still on, we should not remove it. // For the moment, we manage this with hard coded exception //print "Remove box ".$file.'
'; if ($file == 'box_graph_product_distribution.php') { - if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) { + if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { dol_syslog("We discard disabling of module ".$file." because another module still active require it."); continue; } } - if (empty($file)) { $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility + if (empty($file)) { $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility } if ($this->db->type == 'sqlite3') { @@ -1297,27 +1297,27 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; } else { $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes"; - $sql.= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid"; - $sql.= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'"; - $sql.= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; + $sql .= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def"; + $sql .= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid"; + $sql .= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'"; + $sql .= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; } dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { - $this->error=$this->db->lasterror(); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); $err++; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE file = '".$this->db->escape($file)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE file = '".$this->db->escape($file)."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { - $this->error=$this->db->lasterror(); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); $err++; } } @@ -1335,102 +1335,102 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it public function insert_cronjobs() { // phpcs:enable - include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; global $conf; - $err=0; + $err = 0; if (is_array($this->cronjobs)) { dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG); foreach ($this->cronjobs as $key => $value) { - $entity = isset($this->cronjobs[$key]['entity'])?$this->cronjobs[$key]['entity']:$conf->entity; - $label = isset($this->cronjobs[$key]['label'])?$this->cronjobs[$key]['label']:''; - $jobtype = isset($this->cronjobs[$key]['jobtype'])?$this->cronjobs[$key]['jobtype']:''; - $class = isset($this->cronjobs[$key]['class'])?$this->cronjobs[$key]['class']:''; - $objectname = isset($this->cronjobs[$key]['objectname'])?$this->cronjobs[$key]['objectname']:''; - $method = isset($this->cronjobs[$key]['method'])?$this->cronjobs[$key]['method']:''; - $command = isset($this->cronjobs[$key]['command'])?$this->cronjobs[$key]['command']:''; - $parameters = isset($this->cronjobs[$key]['parameters'])?$this->cronjobs[$key]['parameters']:''; - $comment = isset($this->cronjobs[$key]['comment'])?$this->cronjobs[$key]['comment']:''; - $frequency = isset($this->cronjobs[$key]['frequency'])?$this->cronjobs[$key]['frequency']:''; - $unitfrequency = isset($this->cronjobs[$key]['unitfrequency'])?$this->cronjobs[$key]['unitfrequency']:''; - $priority = isset($this->cronjobs[$key]['priority'])?$this->cronjobs[$key]['priority']:''; - $datestart = isset($this->cronjobs[$key]['datestart'])?$this->cronjobs[$key]['datestart']:''; - $dateend = isset($this->cronjobs[$key]['dateend'])?$this->cronjobs[$key]['dateend']:''; - $status = isset($this->cronjobs[$key]['status'])?$this->cronjobs[$key]['status']:''; - $test = isset($this->cronjobs[$key]['test'])?$this->cronjobs[$key]['test']:''; // Line must be enabled or not (so visible or not) + $entity = isset($this->cronjobs[$key]['entity']) ? $this->cronjobs[$key]['entity'] : $conf->entity; + $label = isset($this->cronjobs[$key]['label']) ? $this->cronjobs[$key]['label'] : ''; + $jobtype = isset($this->cronjobs[$key]['jobtype']) ? $this->cronjobs[$key]['jobtype'] : ''; + $class = isset($this->cronjobs[$key]['class']) ? $this->cronjobs[$key]['class'] : ''; + $objectname = isset($this->cronjobs[$key]['objectname']) ? $this->cronjobs[$key]['objectname'] : ''; + $method = isset($this->cronjobs[$key]['method']) ? $this->cronjobs[$key]['method'] : ''; + $command = isset($this->cronjobs[$key]['command']) ? $this->cronjobs[$key]['command'] : ''; + $parameters = isset($this->cronjobs[$key]['parameters']) ? $this->cronjobs[$key]['parameters'] : ''; + $comment = isset($this->cronjobs[$key]['comment']) ? $this->cronjobs[$key]['comment'] : ''; + $frequency = isset($this->cronjobs[$key]['frequency']) ? $this->cronjobs[$key]['frequency'] : ''; + $unitfrequency = isset($this->cronjobs[$key]['unitfrequency']) ? $this->cronjobs[$key]['unitfrequency'] : ''; + $priority = isset($this->cronjobs[$key]['priority']) ? $this->cronjobs[$key]['priority'] : ''; + $datestart = isset($this->cronjobs[$key]['datestart']) ? $this->cronjobs[$key]['datestart'] : ''; + $dateend = isset($this->cronjobs[$key]['dateend']) ? $this->cronjobs[$key]['dateend'] : ''; + $status = isset($this->cronjobs[$key]['status']) ? $this->cronjobs[$key]['status'] : ''; + $test = isset($this->cronjobs[$key]['test']) ? $this->cronjobs[$key]['test'] : ''; // Line must be enabled or not (so visible or not) // Search if cron entry already present $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob"; - $sql.= " WHERE module_name = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'"; + $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'"; if ($class) { - $sql.= " AND classesname = '".$this->db->escape($class)."'"; + $sql .= " AND classesname = '".$this->db->escape($class)."'"; } if ($objectname) { - $sql.= " AND objectname = '".$this->db->escape($objectname)."'"; + $sql .= " AND objectname = '".$this->db->escape($objectname)."'"; } if ($method) { - $sql.= " AND methodename = '".$this->db->escape($method)."'"; + $sql .= " AND methodename = '".$this->db->escape($method)."'"; } if ($command) { - $sql.= " AND command = '".$this->db->escape($command)."'"; + $sql .= " AND command = '".$this->db->escape($command)."'"; } - $sql.= " AND entity = ".$entity; // Must be exact entity + $sql .= " AND entity = ".$entity; // Must be exact entity - $now=dol_now(); + $now = dol_now(); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); if ($obj->nb == 0) { $this->db->begin(); - if (! $err) { + if (!$err) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, dateend, label, jobtype, classesname, objectname, methodename, command, params, note,"; - if (is_int($frequency)) { $sql.= ' frequency,'; } - if (is_int($unitfrequency)) { $sql.= ' unitfrequency,'; } - if (is_int($priority)) { $sql.= ' priority,'; } - if (is_int($status)) { $sql.= ' status,'; } - $sql.= " entity, test)"; - $sql.= " VALUES ("; - $sql.= "'".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."', "; - $sql.= "'".$this->db->idate($now)."', "; - $sql.= ($datestart ? "'".$this->db->idate($datestart)."'" : "'".$this->db->idate($now)."'").", "; - $sql.= ($dateend ? "'".$this->db->idate($dateend)."'" : "NULL").", "; - $sql.= "'".$this->db->escape($label)."', "; - $sql.= "'".$this->db->escape($jobtype)."', "; - $sql.= ($class?"'".$this->db->escape($class)."'":"null").","; - $sql.= ($objectname?"'".$this->db->escape($objectname)."'":"null").","; - $sql.= ($method?"'".$this->db->escape($method)."'":"null").","; - $sql.= ($command?"'".$this->db->escape($command)."'":"null").","; - $sql.= ($parameters?"'".$this->db->escape($parameters)."'":"null").","; - $sql.= ($comment?"'".$this->db->escape($comment)."'":"null").","; - if(is_int($frequency)) { $sql.= "'".$this->db->escape($frequency)."', "; + if (is_int($frequency)) { $sql .= ' frequency,'; } + if (is_int($unitfrequency)) { $sql .= ' unitfrequency,'; } + if (is_int($priority)) { $sql .= ' priority,'; } + if (is_int($status)) { $sql .= ' status,'; } + $sql .= " entity, test)"; + $sql .= " VALUES ("; + $sql .= "'".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."', "; + $sql .= "'".$this->db->idate($now)."', "; + $sql .= ($datestart ? "'".$this->db->idate($datestart)."'" : "'".$this->db->idate($now)."'").", "; + $sql .= ($dateend ? "'".$this->db->idate($dateend)."'" : "NULL").", "; + $sql .= "'".$this->db->escape($label)."', "; + $sql .= "'".$this->db->escape($jobtype)."', "; + $sql .= ($class ? "'".$this->db->escape($class)."'" : "null").","; + $sql .= ($objectname ? "'".$this->db->escape($objectname)."'" : "null").","; + $sql .= ($method ? "'".$this->db->escape($method)."'" : "null").","; + $sql .= ($command ? "'".$this->db->escape($command)."'" : "null").","; + $sql .= ($parameters ? "'".$this->db->escape($parameters)."'" : "null").","; + $sql .= ($comment ? "'".$this->db->escape($comment)."'" : "null").","; + if (is_int($frequency)) { $sql .= "'".$this->db->escape($frequency)."', "; } - if(is_int($unitfrequency)) { $sql.= "'".$this->db->escape($unitfrequency)."', "; + if (is_int($unitfrequency)) { $sql .= "'".$this->db->escape($unitfrequency)."', "; } - if(is_int($priority)) {$sql.= "'".$this->db->escape($priority)."', "; + if (is_int($priority)) {$sql .= "'".$this->db->escape($priority)."', "; } - if(is_int($status)) { $sql.= "'".$this->db->escape($status)."', "; + if (is_int($status)) { $sql .= "'".$this->db->escape($status)."', "; } - $sql.= $entity.","; - $sql.= "'".$this->db->escape($test)."'"; - $sql.= ")"; + $sql .= $entity.","; + $sql .= "'".$this->db->escape($test)."'"; + $sql .= ")"; - $resql=$this->db->query($sql); - if (! $resql) { $err++; + $resql = $this->db->query($sql); + if (!$resql) { $err++; } } - if (! $err) { + if (!$err) { $this->db->commit(); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); } } @@ -1438,7 +1438,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $err++; } } @@ -1459,19 +1459,19 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; if (is_array($this->cronjobs)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob"; - $sql.= " WHERE module_name = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'"; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND test = '1'"; // We delete on lines that are not set with a complete test that is '$conf->module->enabled' so when module is disabled, the cron is also removed. + $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'"; + $sql .= " AND entity = ".$conf->entity; + $sql .= " AND test = '1'"; // We delete on lines that are not set with a complete test that is '$conf->module->enabled' so when module is disabled, the cron is also removed. // For crons declared with a '$conf->module->enabled', there is no need to delete the line, so we don't loose setup if we reenable module. dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { - $this->error=$this->db->lasterror(); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); $err++; } } @@ -1490,15 +1490,15 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); $err++; } @@ -1516,18 +1516,18 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; - if (! empty($this->tabs)) { + if (!empty($this->tabs)) { dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG); - $i=0; + $i = 0; foreach ($this->tabs as $key => $value) { - if (is_array($value) && count($value) == 0) { continue; // Discard empty arrays + if (is_array($value) && count($value) == 0) { continue; // Discard empty arrays } - $entity=$conf->entity; + $entity = $conf->entity; $newvalue = $value; if (is_array($value)) { @@ -1538,24 +1538,24 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it if ($newvalue) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."const ("; - $sql.= "name"; - $sql.= ", type"; - $sql.= ", value"; - $sql.= ", note"; - $sql.= ", visible"; - $sql.= ", entity"; - $sql.= ")"; - $sql.= " VALUES ("; - $sql.= $this->db->encrypt($this->const_name."_TABS_".$i, 1); - $sql.= ", 'chaine'"; - $sql.= ", ".$this->db->encrypt($newvalue, 1); - $sql.= ", null"; - $sql.= ", '0'"; - $sql.= ", ".$entity; - $sql.= ")"; + $sql .= "name"; + $sql .= ", type"; + $sql .= ", value"; + $sql .= ", note"; + $sql .= ", visible"; + $sql .= ", entity"; + $sql .= ")"; + $sql .= " VALUES ("; + $sql .= $this->db->encrypt($this->const_name."_TABS_".$i, 1); + $sql .= ", 'chaine'"; + $sql .= ", ".$this->db->encrypt($newvalue, 1); + $sql .= ", null"; + $sql .= ", '0'"; + $sql .= ", ".$entity; + $sql .= ")"; $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { dol_syslog($this->db->lasterror(), LOG_ERR); if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error = $this->db->lasterror(); @@ -1582,7 +1582,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; if (empty($this->const)) { return 0; } @@ -1594,38 +1594,38 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $name = $this->const[$key][0]; $type = $this->const[$key][1]; $val = $this->const[$key][2]; - $note = isset($this->const[$key][3])?$this->const[$key][3]:''; - $visible = isset($this->const[$key][4])?$this->const[$key][4]:0; - $entity = (! empty($this->const[$key][5]) && $this->const[$key][5]!='current')?0:$conf->entity; + $note = isset($this->const[$key][3]) ? $this->const[$key][3] : ''; + $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0; + $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity; // Clean - if (empty($visible)) { $visible='0'; + if (empty($visible)) { $visible = '0'; } - if (empty($val) && $val != '0') { $val=''; + if (empty($val) && $val != '0') { $val = ''; } $sql = "SELECT count(*)"; - $sql.= " FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'"; - $sql.= " AND entity = ".$entity; + $sql .= " FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'"; + $sql .= " AND entity = ".$entity; - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $row = $this->db->fetch_row($result); if ($row[0] == 0) // If not found { $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; - $sql.= " VALUES ("; - $sql.= $this->db->encrypt($name, 1); - $sql.= ",'".$type."'"; - $sql.= ",".(($val != '')?$this->db->encrypt($val, 1):"''"); - $sql.= ",".($note?"'".$this->db->escape($note)."'":"null"); - $sql.= ",'".$visible."'"; - $sql.= ",".$entity; - $sql.= ")"; + $sql .= " VALUES ("; + $sql .= $this->db->encrypt($name, 1); + $sql .= ",'".$type."'"; + $sql .= ",".(($val != '') ? $this->db->encrypt($val, 1) : "''"); + $sql .= ",".($note ? "'".$this->db->escape($note)."'" : "null"); + $sql .= ",'".$visible."'"; + $sql .= ",".$entity; + $sql .= ")"; - if (! $this->db->query($sql) ) { + if (!$this->db->query($sql)) { $err++; } } @@ -1654,23 +1654,23 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; if (empty($this->const)) { return 0; } foreach ($this->const as $key => $value) { - $name = $this->const[$key][0]; - $deleteonunactive = (! empty($this->const[$key][6]))?1:0; + $name = $this->const[$key][0]; + $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0; if ($deleteonunactive) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; - $sql.= " AND entity in (0, ".$conf->entity.")"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; + $sql .= " AND entity in (0, ".$conf->entity.")"; dol_syslog(get_class($this)."::delete_const", LOG_DEBUG); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); $err++; } } @@ -1691,59 +1691,59 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0) { // phpcs:enable - global $conf,$user; + global $conf, $user; - $err=0; - $entity=(! empty($force_entity) ? $force_entity : $conf->entity); + $err = 0; + $entity = (!empty($force_entity) ? $force_entity : $conf->entity); dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG); // Test if module is activated $sql_del = "SELECT ".$this->db->decrypt('value')." as value"; - $sql_del.= " FROM ".MAIN_DB_PREFIX."const"; - $sql_del.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql_del.= " AND entity IN (0,".$entity.")"; + $sql_del .= " FROM ".MAIN_DB_PREFIX."const"; + $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql_del .= " AND entity IN (0,".$entity.")"; - $resql=$this->db->query($sql_del); + $resql = $this->db->query($sql_del); if ($resql) { - $obj=$this->db->fetch_object($resql); - if ($obj !== null && ! empty($obj->value) && ! empty($this->rights)) { + $obj = $this->db->fetch_object($resql); + if ($obj !== null && !empty($obj->value) && !empty($this->rights)) { // If the module is active foreach ($this->rights as $key => $value) { $r_id = $this->rights[$key][0]; $r_desc = $this->rights[$key][1]; - $r_type = isset($this->rights[$key][2])?$this->rights[$key][2]:''; + $r_type = isset($this->rights[$key][2]) ? $this->rights[$key][2] : ''; $r_def = $this->rights[$key][3]; $r_perms = $this->rights[$key][4]; - $r_subperms = isset($this->rights[$key][5])?$this->rights[$key][5]:''; - $r_modul = empty($this->rights_class)?strtolower($this->name):$this->rights_class; + $r_subperms = isset($this->rights[$key][5]) ? $this->rights[$key][5] : ''; + $r_modul = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class; - if (empty($r_type)) { $r_type='w'; } - if (empty($r_def)) { $r_def=0; } + if (empty($r_type)) { $r_type = 'w'; } + if (empty($r_def)) { $r_def = 0; } // Search if perm already present $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def"; - $sql.= " WHERE id = ".$r_id." AND entity = ".$entity; + $sql .= " WHERE id = ".$r_id." AND entity = ".$entity; - $resqlselect=$this->db->query($sql); + $resqlselect = $this->db->query($sql); if ($resqlselect) { $objcount = $this->db->fetch_object($resqlselect); if ($objcount && $objcount->nb == 0) { - if (dol_strlen($r_perms) ) { - if (dol_strlen($r_subperms) ) { + if (dol_strlen($r_perms)) { + if (dol_strlen($r_subperms)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; - $sql.= " (id, entity, libelle, module, type, bydefault, perms, subperms)"; - $sql.= " VALUES "; - $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."','".$r_subperms."')"; + $sql .= " (id, entity, libelle, module, type, bydefault, perms, subperms)"; + $sql .= " VALUES "; + $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."','".$r_subperms."')"; } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; - $sql.= " (id, entity, libelle, module, type, bydefault, perms)"; - $sql.= " VALUES "; - $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."')"; + $sql .= " (id, entity, libelle, module, type, bydefault, perms)"; + $sql .= " VALUES "; + $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."')"; } } else @@ -1754,11 +1754,11 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.")"; } - $resqlinsert=$this->db->query($sql, 1); + $resqlinsert = $this->db->query($sql, 1); - if (! $resqlinsert) { + if (!$resqlinsert) { if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $err++; break; } @@ -1774,21 +1774,21 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // If we want to init permissions on admin users if ($reinitadminperms) { - if (! class_exists('User')) { - include_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; + if (!class_exists('User')) { + include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; } - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1"; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1"; dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG); - $resqlseladmin=$this->db->query($sql, 1); + $resqlseladmin = $this->db->query($sql, 1); if ($resqlseladmin) { - $num=$this->db->num_rows($resqlseladmin); - $i=0; + $num = $this->db->num_rows($resqlseladmin); + $i = 0; while ($i < $num) { - $obj2=$this->db->fetch_object($resqlseladmin); + $obj2 = $this->db->fetch_object($resqlseladmin); dol_syslog(get_class($this)."::insert_permissions Add permission to user id=".$obj2->rowid); - $tmpuser=new User($this->db); + $tmpuser = new User($this->db); $result = $tmpuser->fetch($obj2->rowid); if ($result > 0) { $tmpuser->addrights($r_id, '', '', 0, 1); @@ -1807,7 +1807,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } } - if ($reinitadminperms && ! empty($user->admin)) // Reload permission for current user if defined + if ($reinitadminperms && !empty($user->admin)) // Reload permission for current user if defined { // We reload permissions $user->clearrights(); @@ -1818,7 +1818,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $err++; } @@ -1837,14 +1837,14 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def"; - $sql.= " WHERE module = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE module = '".$this->db->escape(empty($this->rights_class) ?strtolower($this->name) : $this->rights_class)."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); $err++; } @@ -1863,80 +1863,80 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $user; - if (! is_array($this->menu) || empty($this->menu)) { return 0; + if (!is_array($this->menu) || empty($this->menu)) { return 0; } - include_once DOL_DOCUMENT_ROOT . '/core/class/menubase.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php'; dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG); - $err=0; + $err = 0; $this->db->begin(); foreach ($this->menu as $key => $value) { $menu = new Menubase($this->db); - $menu->menu_handler='all'; + $menu->menu_handler = 'all'; //$menu->module=strtolower($this->name); TODO When right_class will be same than module name - $menu->module=empty($this->rights_class)?strtolower($this->name):$this->rights_class; + $menu->module = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class; - if (! $this->menu[$key]['fk_menu']) { - $menu->fk_menu=0; + if (!$this->menu[$key]['fk_menu']) { + $menu->fk_menu = 0; } else { - $foundparent=0; - $fk_parent=$this->menu[$key]['fk_menu']; + $foundparent = 0; + $fk_parent = $this->menu[$key]['fk_menu']; if (preg_match('/^r=/', $fk_parent)) // old deprecated method { - $fk_parent=str_replace('r=', '', $fk_parent); + $fk_parent = str_replace('r=', '', $fk_parent); if (isset($this->menu[$fk_parent]['rowid'])) { - $menu->fk_menu=$this->menu[$fk_parent]['rowid']; - $foundparent=1; + $menu->fk_menu = $this->menu[$fk_parent]['rowid']; + $foundparent = 1; } } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) { - $menu->fk_menu=-1; - $menu->fk_mainmenu=$reg[1]; - $menu->fk_leftmenu=$reg[2]; - $foundparent=1; + $menu->fk_menu = -1; + $menu->fk_mainmenu = $reg[1]; + $menu->fk_leftmenu = $reg[2]; + $foundparent = 1; } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) { - $menu->fk_menu=-1; - $menu->fk_mainmenu=$reg[1]; - $menu->fk_leftmenu=''; - $foundparent=1; + $menu->fk_menu = -1; + $menu->fk_mainmenu = $reg[1]; + $menu->fk_leftmenu = ''; + $foundparent = 1; } - if (! $foundparent) { - $this->error="ErrorBadDefinitionOfMenuArrayInModuleDescriptor"; + if (!$foundparent) { + $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor"; dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR); $err++; } } - $menu->type=$this->menu[$key]['type']; - $menu->mainmenu=isset($this->menu[$key]['mainmenu'])?$this->menu[$key]['mainmenu']:(isset($menu->fk_mainmenu)?$menu->fk_mainmenu:''); - $menu->leftmenu=isset($this->menu[$key]['leftmenu'])?$this->menu[$key]['leftmenu']:''; - $menu->titre=$this->menu[$key]['titre']; // deprecated - $menu->title=$this->menu[$key]['titre']; - $menu->url=$this->menu[$key]['url']; - $menu->langs=$this->menu[$key]['langs']; - $menu->position=$this->menu[$key]['position']; - $menu->perms=$this->menu[$key]['perms']; - $menu->target=isset($this->menu[$key]['target'])?$this->menu[$key]['target']:''; - $menu->user=$this->menu[$key]['user']; - $menu->enabled=isset($this->menu[$key]['enabled'])?$this->menu[$key]['enabled']:0; - $menu->position=$this->menu[$key]['position']; + $menu->type = $this->menu[$key]['type']; + $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : ''); + $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : ''; + $menu->titre = $this->menu[$key]['titre']; // deprecated + $menu->title = $this->menu[$key]['titre']; + $menu->url = $this->menu[$key]['url']; + $menu->langs = $this->menu[$key]['langs']; + $menu->position = $this->menu[$key]['position']; + $menu->perms = $this->menu[$key]['perms']; + $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : ''; + $menu->user = $this->menu[$key]['user']; + $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0; + $menu->position = $this->menu[$key]['position']; - if (! $err) { - $result=$menu->create($user); // Save menu entry into table llx_menu + if (!$err) { + $result = $menu->create($user); // Save menu entry into table llx_menu if ($result > 0) { - $this->menu[$key]['rowid']=$result; + $this->menu[$key]['rowid'] = $result; } else { - $this->error=$menu->error; + $this->error = $menu->error; dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR); $err++; break; @@ -1944,7 +1944,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } } - if (! $err) { + if (!$err) { $this->db->commit(); } else @@ -1968,19 +1968,19 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; //$module=strtolower($this->name); TODO When right_class will be same than module name - $module=empty($this->rights_class)?strtolower($this->name):$this->rights_class; + $module = empty($this->rights_class) ?strtolower($this->name) : $this->rights_class; $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu"; - $sql.= " WHERE module = '".$this->db->escape($module)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE module = '".$this->db->escape($module)."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { - $this->error=$this->db->lasterror(); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); $err++; } @@ -1998,24 +1998,24 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $langs, $conf; - $err=0; + $err = 0; if (isset($this->dirs) && is_array($this->dirs)) { foreach ($this->dirs as $key => $value) { - $addtodatabase=0; + $addtodatabase = 0; - if (! is_array($value)) { $dir=$value; // Default simple mode + if (!is_array($value)) { $dir = $value; // Default simple mode } else { $constname = $this->const_name."_DIR_"; $dir = $this->dirs[$key][1]; - $addtodatabase = empty($this->dirs[$key][2])?'':$this->dirs[$key][2]; // Create constante in llx_const - $subname = empty($this->dirs[$key][3])?'':strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output) - $forcename = empty($this->dirs[$key][4])?'':strtoupper($this->dirs[$key][4]); // Change the module name if different + $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const + $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output) + $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different - if (! empty($forcename)) { $constname = 'MAIN_MODULE_'.$forcename."_DIR_"; + if (!empty($forcename)) { $constname = 'MAIN_MODULE_'.$forcename."_DIR_"; } - if (! empty($subname)) { $constname = $constname.$subname."_"; + if (!empty($subname)) { $constname = $constname.$subname."_"; } $name = $constname.strtoupper($this->dirs[$key][0]); @@ -2026,7 +2026,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } else { $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir; } // Create dir if it does not exists - if (! empty($fulldir) && ! file_exists($fulldir)) { + if (!empty($fulldir) && !file_exists($fulldir)) { if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) { $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir); dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR); @@ -2035,7 +2035,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } // Define the constant in database if requested (not the default mode) - if (! empty($addtodatabase)) { + if (!empty($addtodatabase)) { $result = $this->insert_dirs($name, $dir); if ($result) { $err++; } @@ -2061,21 +2061,21 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; $sql = "SELECT count(*)"; - $sql.= " FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."const"; + $sql .= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $row = $this->db->fetch_row($result); if ($row[0] == 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; - $sql.= " VALUES (".$this->db->encrypt($name, 1).",'chaine',".$this->db->encrypt($dir, 1).",'Directory for module ".$this->name."','0',".$conf->entity.")"; + $sql .= " VALUES (".$this->db->encrypt($name, 1).",'chaine',".$this->db->encrypt($dir, 1).",'Directory for module ".$this->name."','0',".$conf->entity.")"; dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); $this->db->query($sql); @@ -2083,7 +2083,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $err++; } @@ -2102,15 +2102,15 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; + $err = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'"; + $sql .= " AND entity = ".$conf->entity; dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); $err++; } @@ -2128,15 +2128,15 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $error=0; + $error = 0; - if (is_array($this->module_parts) && ! empty($this->module_parts)) { - foreach($this->module_parts as $key => $value) + if (is_array($this->module_parts) && !empty($this->module_parts)) { + foreach ($this->module_parts as $key => $value) { - if (is_array($value) && count($value) == 0) { continue; // Discard empty arrays + if (is_array($value) && count($value) == 0) { continue; // Discard empty arrays } - $entity=$conf->entity; // Reset the current entity + $entity = $conf->entity; // Reset the current entity $newvalue = $value; // Serialize array parameters @@ -2160,29 +2160,29 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it } $sql = "INSERT INTO ".MAIN_DB_PREFIX."const ("; - $sql.= "name"; - $sql.= ", type"; - $sql.= ", value"; - $sql.= ", note"; - $sql.= ", visible"; - $sql.= ", entity"; - $sql.= ")"; - $sql.= " VALUES ("; - $sql.= $this->db->encrypt($this->const_name."_".strtoupper($key), 1); - $sql.= ", 'chaine'"; - $sql.= ", ".$this->db->encrypt($newvalue, 1); - $sql.= ", null"; - $sql.= ", '0'"; - $sql.= ", ".$entity; - $sql.= ")"; + $sql .= "name"; + $sql .= ", type"; + $sql .= ", value"; + $sql .= ", note"; + $sql .= ", visible"; + $sql .= ", entity"; + $sql .= ")"; + $sql .= " VALUES ("; + $sql .= $this->db->encrypt($this->const_name."_".strtoupper($key), 1); + $sql .= ", 'chaine'"; + $sql .= ", ".$this->db->encrypt($newvalue, 1); + $sql .= ", null"; + $sql .= ", '0'"; + $sql .= ", ".$entity; + $sql .= ")"; dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG); - $resql=$this->db->query($sql, 1); - if (! $resql) { + $resql = $this->db->query($sql, 1); + if (!$resql) { if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') { $error++; - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); } else { @@ -2205,23 +2205,23 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it // phpcs:enable global $conf; - $err=0; - $entity=$conf->entity; + $err = 0; + $entity = $conf->entity; - if (is_array($this->module_parts) && ! empty($this->module_parts)) { - foreach($this->module_parts as $key => $value) + if (is_array($this->module_parts) && !empty($this->module_parts)) { + foreach ($this->module_parts as $key => $value) { // If entity is defined if (is_array($value) && isset($value['entity'])) { $entity = $value['entity']; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'"; - $sql.= " AND entity = ".$entity; + $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'"; + $sql .= " AND entity = ".$entity; dol_syslog(get_class($this)."::delete_const_".$key."", LOG_DEBUG); - if (! $this->db->query($sql)) { - $this->error=$this->db->lasterror(); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); $err++; } } diff --git a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php index 794e7c57a29..4694cdaf6ee 100644 --- a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php +++ b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php @@ -4,7 +4,7 @@ * Copyright (C) 2014 Marcos García * Copyright (C) 2016 Charlie Benke * Copyright (C) 2018-2019 Philippe Grand - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -118,7 +118,7 @@ class doc_generic_order_odt extends ModelePDFCommandes $form = new Form($this->db); $texte = $this->description.".
\n"; - $texte .= '
'; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= ''; @@ -177,6 +177,11 @@ class doc_generic_order_odt extends ModelePDFCommandes } $texte .= ''; } + // Add input to upload a new template file. + $texte .= '
'.$langs->trans("UploadNewTemplate").' '; + $texte .= ''; + $texte .= ''; + $texte .= '
'; $texte .= ''; diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php index 30fd293533b..25fe672d8e9 100644 --- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php @@ -116,7 +116,7 @@ class pdf_einstein extends ModelePDFCommandes /** * Issuer - * @var Societe object that emits + * @var Societe Object that emits */ public $emetteur; @@ -128,7 +128,7 @@ class pdf_einstein extends ModelePDFCommandes */ public function __construct($db) { - global $conf,$langs,$mysoc; + global $conf, $langs, $mysoc; // Translations $langs->loadLangs(array("main", "bills", "products")); @@ -136,72 +136,70 @@ class pdf_einstein extends ModelePDFCommandes $this->db = $db; $this->name = "einstein"; $this->description = $langs->trans('PDFEinsteinDescription'); - $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template // Dimension page $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Display logo - $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION - $this->option_modereg = 1; // Display payment mode - $this->option_condreg = 1; // Display payment terms - $this->option_codeproduitservice = 1; // Display product-service code - $this->option_multilang = 1; // Available in several languages - $this->option_escompte = 0; // Displays if there has been a discount - $this->option_credit_note = 0; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 0; // Displays if there has been a discount + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; - if($conf->global->PRODUCT_USE_UNITS) + $this->posxdesc = $this->marge_gauche + 1; + if ($conf->global->PRODUCT_USE_UNITS) { - $this->posxtva=101; - $this->posxup=118; - $this->posxqty=135; - $this->posxunit=151; + $this->posxtva = 101; + $this->posxup = 118; + $this->posxqty = 135; + $this->posxunit = 151; } else { - $this->posxtva=110; - $this->posxup=126; - $this->posxqty=145; - $this->posxunit=162; + $this->posxtva = 110; + $this->posxup = 126; + $this->posxqty = 145; + $this->posxunit = 162; } - $this->posxdiscount=162; - $this->postotalht=174; - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || ! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxtva=$this->posxup; - $this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images + $this->posxdiscount = 162; + $this->postotalht = 174; + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || !empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxtva = $this->posxup; + $this->posxpicture = $this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images if ($this->page_largeur < 210) // To work with US executive format { - $this->posxpicture-=20; - $this->posxtva-=20; - $this->posxup-=20; - $this->posxqty-=20; - $this->posxunit-=20; - $this->posxdiscount-=20; - $this->postotalht-=20; + $this->posxpicture -= 20; + $this->posxtva -= 20; + $this->posxup -= 20; + $this->posxqty -= 20; + $this->posxunit -= 20; + $this->posxdiscount -= 20; + $this->postotalht -= 20; } - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -221,9 +219,9 @@ class pdf_einstein extends ModelePDFCommandes // phpcs:enable global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load translation files required by the page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries")); @@ -240,20 +238,20 @@ class pdf_einstein extends ModelePDFCommandes if ($object->specimen) { $dir = $conf->commande->multidir_output[$conf->entity]; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->commande->multidir_output[$object->entity] . "/" . $objectref; - $file = $dir . "/" . $objectref . ".pdf"; + $dir = $conf->commande->multidir_output[$object->entity]."/".$objectref; + $file = $dir."/".$objectref.".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -261,25 +259,25 @@ class pdf_einstein extends ModelePDFCommandes if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Create pdf instance - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance $pdf->SetAutoPageBreak(1, 0); - $heightforinfotot = 40; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $heightforinfotot = 40; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; if (class_exists('TCPDF')) { @@ -288,14 +286,14 @@ class pdf_einstein extends ModelePDFCommandes } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -303,12 +301,12 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfOrderTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // Set $this->atleastonediscount if you have at least one discount - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if ($object->lines[$i]->remise_percent) { @@ -318,27 +316,27 @@ class pdf_einstein extends ModelePDFCommandes if (empty($this->atleastonediscount)) { $delta = ($this->postotalht - $this->posxdiscount); - $this->posxpicture+=$delta; - $this->posxtva+=$delta; - $this->posxup+=$delta; - $this->posxqty+=$delta; - $this->posxunit+=$delta; - $this->posxdiscount+=$delta; + $this->posxpicture += $delta; + $this->posxtva += $delta; + $this->posxup += $delta; + $this->posxqty += $delta; + $this->posxunit += $delta; + $this->posxdiscount += $delta; // post of fields after are not modified, stay at same position } // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); - $tab_top = 90+$top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42+$top_shift:10); + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); // Incoterm if ($conf->incoterm->enabled) @@ -349,50 +347,50 @@ class pdf_einstein extends ModelePDFCommandes $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } } // Displays notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } if ($notetoshow) { $tab_top -= 2; - $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object); $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($notetoshow), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($notetoshow), 0, 1); $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } $iniY = $tab_top + 7; @@ -400,49 +398,48 @@ class pdf_einstein extends ModelePDFCommandes $nexY = $tab_top + 7; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); // Description of product line - $curX = $this->posxdesc-1; + $curX = $this->posxdesc - 1; - $showpricebeforepagebreak=1; + $showpricebeforepagebreak = 1; $pdf->startTransaction(); - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva-$curX, 3, $curX, $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva - $curX, 3, $curX, $curY, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva-$curX, 4, $curX, $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva - $curX, 4, $curX, $curY, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -452,109 +449,109 @@ class pdf_einstein extends ModelePDFCommandes { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font + $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font // VAT Rate if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); - $pdf->SetXY($this->posxtva-5, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva+4, 3, $vat_rate, 0, 'R'); + $pdf->SetXY($this->posxtva - 5, $curY); + $pdf->MultiCell($this->posxup - $this->posxtva + 4, 3, $vat_rate, 0, 'R'); } // Unit price before discount $up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxup, $curY); - $pdf->MultiCell($this->posxqty-$this->posxup-0.8, 3, $up_excl_tax, 0, 'R', 0); + $pdf->MultiCell($this->posxqty - $this->posxup - 0.8, 3, $up_excl_tax, 0, 'R', 0); // Quantity $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxqty, $curY); - $pdf->MultiCell($this->posxunit-$this->posxqty-0.8, 4, $qty, 0, 'R'); // Enough for 6 chars + $pdf->MultiCell($this->posxunit - $this->posxqty - 0.8, 4, $qty, 0, 'R'); // Enough for 6 chars // Unit - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { $unit = pdf_getlineunit($object, $i, $outputlangs, $hidedetails, $hookmanager); $pdf->SetXY($this->posxunit, $curY); - $pdf->MultiCell($this->posxdiscount-$this->posxunit-0.8, 4, $unit, 0, 'L'); + $pdf->MultiCell($this->posxdiscount - $this->posxunit - 0.8, 4, $unit, 0, 'L'); } // Discount on line $pdf->SetXY($this->posxdiscount, $curY); if ($object->lines[$i]->remise_percent) { - $pdf->SetXY($this->posxdiscount-2, $curY); + $pdf->SetXY($this->posxdiscount - 2, $curY); $remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails); - $pdf->MultiCell($this->postotalht-$this->posxdiscount+2, 3, $remise_percent, 0, 'R'); + $pdf->MultiCell($this->postotalht - $this->posxdiscount + 2, 3, $remise_percent, 0, 'R'); } // Total HT line $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->postotalht, $curY); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 3, $total_excl_tax, 0, 'R', 0); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $total_excl_tax, 0, 'R', 0); // Collection of totals by value of vat in $this->vat["rate"] = total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -571,10 +568,10 @@ class pdf_einstein extends ModelePDFCommandes $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -587,7 +584,7 @@ class pdf_einstein extends ModelePDFCommandes $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -598,13 +595,13 @@ class pdf_einstein extends ModelePDFCommandes $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0, $object->multicurrency_code); else $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; // Affiche zone infos - $posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); // Affiche zone totaux - $posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); // Affiche zone versements /* @@ -624,31 +621,31 @@ class pdf_einstein extends ModelePDFCommandes // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR"); + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR"); return 0; } } @@ -683,22 +680,22 @@ class pdf_einstein extends ModelePDFCommandes protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("VATIsNotUsedForInvoice"), 0, 'L', 0); - $posy=$pdf->GetY()+4; + $posy = $pdf->GetY() + 4; } - $posxval=52; + $posxval = 52; // Show payments conditions if ($object->cond_reglement_code || $object->cond_reglement) @@ -710,11 +707,11 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_condition_paiement=$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code)!=('PaymentCondition'.$object->cond_reglement_code)?$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code):$outputlangs->convToOutputCharset($object->cond_reglement_doc); - $lib_condition_paiement=str_replace('\n', "\n", $lib_condition_paiement); + $lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement_doc); + $lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement); $pdf->MultiCell(67, 4, $lib_condition_paiement, 0, 'L'); - $posy=$pdf->GetY()+3; + $posy = $pdf->GetY() + 3; } // Check a payment mode is defined @@ -745,7 +742,7 @@ class pdf_einstein extends ModelePDFCommandes }*/ // Show planed date of delivery - if (! empty($object->date_livraison)) + if (!empty($object->date_livraison)) { $outputlangs->load("sendings"); $pdf->SetFont('', 'B', $default_font_size - 2); @@ -754,10 +751,10 @@ class pdf_einstein extends ModelePDFCommandes $pdf->MultiCell(80, 4, $titre, 0, 'L'); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $dlp=dol_print_date($object->date_livraison, "daytext", false, $outputlangs, true); + $dlp = dol_print_date($object->date_livraison, "daytext", false, $outputlangs, true); $pdf->MultiCell(80, 4, $dlp, 0, 'L'); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; } elseif ($object->availability_code || $object->availability) // Show availability conditions { @@ -768,11 +765,11 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_availability=$outputlangs->transnoentities("AvailabilityType".$object->availability_code)!=('AvailabilityType'.$object->availability_code)?$outputlangs->transnoentities("AvailabilityType".$object->availability_code):$outputlangs->convToOutputCharset(isset($object->availability)?$object->availability:''); - $lib_availability=str_replace('\n', "\n", $lib_availability); + $lib_availability = $outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : ''); + $lib_availability = str_replace('\n', "\n", $lib_availability); $pdf->MultiCell(80, 4, $lib_availability, 0, 'L'); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; } // Show payment mode @@ -786,17 +783,17 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_mode_reg=$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code)!=('PaymentType'.$object->mode_reglement_code)?$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code):$outputlangs->convToOutputCharset($object->mode_reglement); + $lib_mode_reg = $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) != ('PaymentType'.$object->mode_reglement_code) ? $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) : $outputlangs->convToOutputCharset($object->mode_reglement); $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } // Show payment mode CHQ if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'CHQ') { // Si mode reglement non force ou si force a CHQ - if (! empty($conf->global->FACTURE_CHQ_NUMBER)) + if (!empty($conf->global->FACTURE_CHQ_NUMBER)) { if ($conf->global->FACTURE_CHQ_NUMBER > 0) { @@ -806,14 +803,14 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', 'B', $default_font_size - 3); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $account->proprio), 0, 'L', 0); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', '', $default_font_size - 3); $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($account->owner_address), 0, 'L', 0); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } } if ($conf->global->FACTURE_CHQ_NUMBER == -1) @@ -821,14 +818,14 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', 'B', $default_font_size - 3); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $this->emetteur->name), 0, 'L', 0); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', '', $default_font_size - 3); $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($this->emetteur->getFullAddress()), 0, 'L', 0); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } } } @@ -837,19 +834,19 @@ class pdf_einstein extends ModelePDFCommandes // If payment mode not forced or forced to VIR, show payment with BAN if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'VIR') { - if (! empty($object->fk_account) || ! empty($object->fk_bank) || ! empty($conf->global->FACTURE_RIB_NUMBER)) + if (!empty($object->fk_account) || !empty($object->fk_bank) || !empty($conf->global->FACTURE_RIB_NUMBER)) { - $bankid=(empty($object->fk_account)?$conf->global->FACTURE_RIB_NUMBER:$object->fk_account); - if (! empty($object->fk_bank)) $bankid=$object->fk_bank; // For backward compatibility when object->fk_account is forced with object->fk_bank + $bankid = (empty($object->fk_account) ? $conf->global->FACTURE_RIB_NUMBER : $object->fk_account); + if (!empty($object->fk_bank)) $bankid = $object->fk_bank; // For backward compatibility when object->fk_account is forced with object->fk_bank $account = new Account($this->db); $account->fetch($bankid); - $curx=$this->marge_gauche; - $cury=$posy; + $curx = $this->marge_gauche; + $cury = $posy; - $posy=pdf_bank($pdf, $outputlangs, $curx, $cury, $account, 0, $default_font_size); + $posy = pdf_bank($pdf, $outputlangs, $curx, $cury, $account, 0, $default_font_size); - $posy+=2; + $posy += 2; } } @@ -871,7 +868,7 @@ class pdf_einstein extends ModelePDFCommandes protected function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs) { // phpcs:enable - global $conf,$mysoc; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -883,32 +880,32 @@ class pdf_einstein extends ModelePDFCommandes $col1x = 120; $col2x = 170; if ($this->page_largeur < 210) // To work with US executive format { - $col2x-=20; + $col2x -= 20; } $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); - $useborder=0; + $useborder = 0; $index = 0; // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); $pdf->SetXY($col2x, $tab2_top + 0); - $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (! empty($object->remise)?$object->remise:0), 0, $outputlangs), 0, 'R', 1); + $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (!empty($object->remise) ? $object->remise : 0), 0, $outputlangs), 0, 'R', 1); // Show VAT by rates and total $pdf->SetFillColor(248, 248, 248); $total_ttc = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ttc : $object->total_ttc; - $this->atleastoneratenotnull=0; + $this->atleastoneratenotnull = 0; if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { - $tvaisnull=((! empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) + $tvaisnull = ((!empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) { // Nothing to do } @@ -917,27 +914,27 @@ class pdf_einstein extends ModelePDFCommandes //Local tax 1 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -948,27 +945,27 @@ class pdf_einstein extends ModelePDFCommandes //Local tax 2 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -977,7 +974,7 @@ class pdf_einstein extends ModelePDFCommandes } //} // VAT - foreach($this->tva as $tvakey => $tvaval) + foreach ($this->tva as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -986,15 +983,15 @@ class pdf_einstein extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; - $totalvat.=vatrate($tvakey, 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat .= vatrate($tvakey, 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1004,11 +1001,11 @@ class pdf_einstein extends ModelePDFCommandes //Local tax 1 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1017,16 +1014,16 @@ class pdf_einstein extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); } @@ -1036,11 +1033,11 @@ class pdf_einstein extends ModelePDFCommandes //Local tax 2 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1049,16 +1046,16 @@ class pdf_einstein extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1072,7 +1069,7 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($total_ttc, 0, $outputlangs), $useborder, 'R', 1); @@ -1081,13 +1078,13 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 0); - $creditnoteamount=0; - $depositsamount=0; + $creditnoteamount = 0; + $depositsamount = 0; //$creditnoteamount=$object->getSumCreditNotesUsed(); //$depositsamount=$object->getSumDepositsUsed(); //print "x".$creditnoteamount."-".$depositsamount;exit; $resteapayer = price2num($total_ttc - $deja_regle - $creditnoteamount - $depositsamount, 'MT'); - if (! empty($object->paye)) $resteapayer=0; + if (!empty($object->paye)) $resteapayer = 0; if ($deja_regle > 0) { @@ -1095,7 +1092,7 @@ class pdf_einstein extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle, 0, $outputlangs), 0, 'R', 0); @@ -1103,7 +1100,7 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); @@ -1135,8 +1132,8 @@ class pdf_einstein extends ModelePDFCommandes global $conf; // Force to disable hidetop and hidebottom - $hidebottom=0; - if ($hidetop) $hidetop=-1; + $hidebottom = 0; + if ($hidetop) $hidetop = -1; $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1148,52 +1145,52 @@ class pdf_einstein extends ModelePDFCommandes if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5); // line takes a position y in 2nd parameter and 4th parameter + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); // line takes a position y in 2nd parameter and 4th parameter - $pdf->SetXY($this->posxdesc-1, $tab_top+1); + $pdf->SetXY($this->posxdesc - 1, $tab_top + 1); $pdf->MultiCell(108, 2, $outputlangs->transnoentities("Designation"), '', 'L'); } if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { - $pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height); + $pdf->line($this->posxtva - 1, $tab_top, $this->posxtva - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxtva-3, $tab_top+1); - $pdf->MultiCell($this->posxup-$this->posxtva+3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); + $pdf->SetXY($this->posxtva - 3, $tab_top + 1); + $pdf->MultiCell($this->posxup - $this->posxtva + 3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); } } - $pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height); + $pdf->line($this->posxup - 1, $tab_top, $this->posxup - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxup-1, $tab_top+1); - $pdf->MultiCell($this->posxqty-$this->posxup-1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); + $pdf->SetXY($this->posxup - 1, $tab_top + 1); + $pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); } - $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height); + $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxqty-1, $tab_top+1); - $pdf->MultiCell($this->posxunit-$this->posxqty-1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); + $pdf->SetXY($this->posxqty - 1, $tab_top + 1); + $pdf->MultiCell($this->posxunit - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); } - if($conf->global->PRODUCT_USE_UNITS) { + if ($conf->global->PRODUCT_USE_UNITS) { $pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height); if (empty($hidetop)) { $pdf->SetXY($this->posxunit - 1, $tab_top + 1); @@ -1201,13 +1198,13 @@ class pdf_einstein extends ModelePDFCommandes } } - $pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height); + $pdf->line($this->posxdiscount - 1, $tab_top, $this->posxdiscount - 1, $tab_top + $tab_height); if (empty($hidetop)) { if ($this->atleastonediscount) { - $pdf->SetXY($this->posxdiscount-1, $tab_top+1); - $pdf->MultiCell($this->postotalht-$this->posxdiscount+1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); + $pdf->SetXY($this->posxdiscount - 1, $tab_top + 1); + $pdf->MultiCell($this->postotalht - $this->posxdiscount + 1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); } } @@ -1217,7 +1214,7 @@ class pdf_einstein extends ModelePDFCommandes } if (empty($hidetop)) { - $pdf->SetXY($this->postotalht-1, $tab_top+1); + $pdf->SetXY($this->postotalht - 1, $tab_top + 1); $pdf->MultiCell(30, 2, $outputlangs->transnoentities("TotalHT"), '', 'C'); } } @@ -1237,7 +1234,7 @@ class pdf_einstein extends ModelePDFCommandes protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "PdfOrderTitle") { // phpcs:enable - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; // Load traductions files required by page $outputlangs->loadLangs(array("main", "bills", "propal", "orders", "companies")); @@ -1247,7 +1244,7 @@ class pdf_einstein extends ModelePDFCommandes pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark - if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) ) + if ($object->statut == 0 && (!empty($conf->global->COMMANDE_DRAFT_WATERMARK))) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->COMMANDE_DRAFT_WATERMARK); } @@ -1255,8 +1252,8 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); @@ -1266,7 +1263,7 @@ class pdf_einstein extends ModelePDFCommandes if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; @@ -1276,20 +1273,20 @@ class pdf_einstein extends ModelePDFCommandes } if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { $pdf->SetTextColor(200, 0, 0); - $pdf->SetFont('', 'B', $default_font_size -2); + $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); } } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } } @@ -1297,56 +1294,56 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetFont('', 'B', $default_font_size + 3); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $title=$outputlangs->transnoentities($titlekey); + $title = $outputlangs->transnoentities($titlekey); $pdf->MultiCell(100, 3, $title, '', 'R'); $pdf->SetFont('', 'B', $default_font_size); - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R'); + $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref), '', 'R'); - $posy+=1; + $posy += 1; $pdf->SetFont('', '', $default_font_size - 1); if ($object->ref_client) { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : " . $outputlangs->convToOutputCharset($object->ref_client), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : " . dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R'); - if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && ! empty($object->thirdparty->code_client)) + if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && !empty($object->thirdparty->code_client)) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); } // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { - $usertmp=new User($this->db); + $usertmp = new User($this->db); $usertmp->fetch($arrayidcontact[0]); - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell(100, 3, $langs->trans("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); } } - $posy+=2; + $posy += 2; $top_shift = 0; // Show list of linked objects @@ -1360,28 +1357,28 @@ class pdf_einstein extends ModelePDFCommandes if ($showaddress) { // Sender properties - $carac_emetteur=''; + $carac_emetteur = ''; // Add internal contact of proposal if defined - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { $object->fetch_user($arrayidcontact[0]); - $labelbeforecontactname=($outputlangs->transnoentities("FromContactName")!='FromContactName'?$outputlangs->transnoentities("FromContactName"):$outputlangs->transnoentities("Name")); - $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$labelbeforecontactname." ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; + $labelbeforecontactname = ($outputlangs->transnoentities("FromContactName") != 'FromContactName' ? $outputlangs->transnoentities("FromContactName") : $outputlangs->transnoentities("Name")); + $carac_emetteur .= ($carac_emetteur ? "\n" : '').$labelbeforecontactname." ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender - $posy=42+$top_shift; - $posx=$this->marge_gauche; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80; - $hautcadre=40; + $posy = 42 + $top_shift; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + $hautcadre = 40; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom").":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); @@ -1389,25 +1386,25 @@ class pdf_einstein extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 60); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); // If CUSTOMER contact defined on order, we use it - $usecontact=false; - $arrayidcontact=$object->getIdContact('external', 'CUSTOMER'); + $usecontact = false; + $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); if (count($arrayidcontact) > 0) { - $usecontact=true; - $result=$object->fetch_contact($arrayidcontact[0]); + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); } //Recipient name @@ -1418,26 +1415,26 @@ class pdf_einstein extends ModelePDFCommandes $thirdparty = $object->thirdparty; } - $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs); + $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact?$object->contact:''), $usecontact, 'target', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object); // Show recipient - $widthrecbox=100; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=42+$top_shift; - $posx=$this->page_largeur-$this->marge_droite-$widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = 42 + $top_shift; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); @@ -1445,7 +1442,7 @@ class pdf_einstein extends ModelePDFCommandes // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } @@ -1468,7 +1465,7 @@ class pdf_einstein extends ModelePDFCommandes { // phpcs:enable global $conf; - $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; return pdf_pagefoot($pdf, $outputlangs, 'ORDER_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); } } diff --git a/htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php b/htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php index 250f8095b05..6b6d6e1a890 100644 --- a/htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php @@ -77,7 +77,7 @@ class pdf_eratosthene extends ModelePDFCommandes * Dolibarr version of the loaded document * @var string */ - public $version = 'development'; + public $version = 'dolibarr'; /** * @var int page_largeur @@ -116,7 +116,7 @@ class pdf_eratosthene extends ModelePDFCommandes /** * Issuer - * @var Societe + * @var Societe Object that emits */ public $emetteur; @@ -136,47 +136,45 @@ class pdf_eratosthene extends ModelePDFCommandes $this->db = $db; $this->name = "eratosthene"; $this->description = $langs->trans('PDFEratostheneDescription'); - $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template // Dimension page $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Display logo - $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION - $this->option_modereg = 1; // Display payment mode - $this->option_condreg = 1; // Display payment terms - $this->option_codeproduitservice = 1; // Display product-service code - $this->option_multilang = 1; // Available in several languages - $this->option_escompte = 0; // Displays if there has been a discount - $this->option_credit_note = 0; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 0; // Displays if there has been a discount + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; + $this->posxdesc = $this->marge_gauche + 1; $this->tabTitleHeight = 5; // default height - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -196,48 +194,55 @@ class pdf_eratosthene extends ModelePDFCommandes // phpcs:enable global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Translations + // Load translation files required by the page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries")); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries")); + } + $nblines = count($object->lines); - $hidetop=0; - if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){ - $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; } // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); + $realpatharray = array(); $this->atleastonephoto = false; - if (! empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE)) + if (!empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE)) { $objphoto = new Product($this->db); - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto->fetch($object->lines[$i]->fk_product); //var_dump($objphoto->ref);exit; - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; - $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; } else { - $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; // default - $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; // alternative + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative } $arephoto = false; foreach ($pdir as $midir) { - if (! $arephoto) + if (!$arephoto) { $dir = $conf->product->dir_output.'/'.$midir; @@ -282,20 +287,20 @@ class pdf_eratosthene extends ModelePDFCommandes if ($object->specimen) { $dir = $conf->commande->multidir_output[$conf->entity]; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->commande->multidir_output[$object->entity] . "/" . $objectref; - $file = $dir . "/" . $objectref . ".pdf"; + $dir = $conf->commande->multidir_output[$object->entity]."/".$objectref; + $file = $dir."/".$objectref.".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -329,14 +334,14 @@ class pdf_eratosthene extends ModelePDFCommandes } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -359,16 +364,16 @@ class pdf_eratosthene extends ModelePDFCommandes // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); - $tab_top = 90+$top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42+$top_shift:10); + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); // Incoterm if ($conf->incoterm->enabled) @@ -379,39 +384,39 @@ class pdf_eratosthene extends ModelePDFCommandes $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } } - // Affiche notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + // Displays notes + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } $pagenb = $pdf->getPage(); if ($notetoshow) { - $tab_width = $this->page_largeur-$this->marge_gauche-$this->marge_droite; + $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; $pageposbeforenote = $pagenb; - $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object); $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); @@ -539,42 +544,42 @@ class pdf_eratosthene extends ModelePDFCommandes $nexY = $tab_top + $this->tabTitleHeight + 2; // Loop on each lines - $pageposbeforeprintlines=$pdf->getPage(); + $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); // Description of product line - $curX = $this->posxdesc-1; + $curX = $this->posxdesc - 1; - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; - if($this->getColumnStatus('photo')) + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) // If photo too high, we moved completely on new page + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposbefore+1); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -582,40 +587,39 @@ class pdf_eratosthene extends ModelePDFCommandes if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } } - if($this->getColumnStatus('desc')) + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -627,7 +631,7 @@ class pdf_eratosthene extends ModelePDFCommandes { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); } @@ -635,18 +639,18 @@ class pdf_eratosthene extends ModelePDFCommandes $nexY = max($pdf->GetY(), $posYAfterImage); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font + $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font // VAT Rate if ($this->getColumnStatus('vat')) @@ -708,56 +712,56 @@ class pdf_eratosthene extends ModelePDFCommandes 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails ); - $reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook // Collection of totals by value of vat in $this->tva["rate"] = total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -827,31 +831,31 @@ class pdf_eratosthene extends ModelePDFCommandes // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR"); + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR"); return 0; } } @@ -876,17 +880,17 @@ class pdf_eratosthene extends ModelePDFCommandes * @param Object $object Object to show * @param int $posy Y * @param Translate $outputlangs Langs object - * @return void + * @return int Pos y */ protected function drawInfoTable(&$pdf, $object, $posy, $outputlangs) { - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); @@ -1083,11 +1087,19 @@ class pdf_eratosthene extends ModelePDFCommandes $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); $useborder = 0; $index = 0; + + $outputlangsbis = null; + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + } + // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); - $total_ht = ($conf->multicurrency->enabled && $object->mylticurrency_tx != 1 ? $object->multicurrency_total_ht : $object->total_ht); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalHT") : ''), 0, 'L', 1); + $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); $pdf->SetXY($col2x, $tab2_top + 0); $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (!empty($object->remise) ? $object->remise : 0), 0, $outputlangs), 0, 'R', 1); @@ -1109,26 +1121,27 @@ class pdf_eratosthene extends ModelePDFCommandes //Local tax 1 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1139,27 +1152,28 @@ class pdf_eratosthene extends ModelePDFCommandes //Local tax 2 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1183,7 +1197,8 @@ class pdf_eratosthene extends ModelePDFCommandes $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalVAT", $mysoc->country_code) : ''); + $totalvat .= ' '; $totalvat .= vatrate($tvakey, 1).$tvacompl; $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); @@ -1195,11 +1210,11 @@ class pdf_eratosthene extends ModelePDFCommandes //Local tax 1 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1208,16 +1223,17 @@ class pdf_eratosthene extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); } @@ -1227,11 +1243,11 @@ class pdf_eratosthene extends ModelePDFCommandes //Local tax 2 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1240,16 +1256,17 @@ class pdf_eratosthene extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1263,7 +1280,7 @@ class pdf_eratosthene extends ModelePDFCommandes $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalTTC", $mysoc->country_code) : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($total_ttc, 0, $outputlangs), $useborder, 'R', 1); @@ -1286,7 +1303,7 @@ class pdf_eratosthene extends ModelePDFCommandes $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("AlreadyPaid") : ''), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle, 0, $outputlangs), 0, 'R', 0); @@ -1294,7 +1311,7 @@ class pdf_eratosthene extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("AlreadyPaid") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); @@ -1339,24 +1356,26 @@ class pdf_eratosthene extends ModelePDFCommandes if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - if (empty($hidetop)){ - $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -1370,14 +1389,14 @@ class pdf_eratosthene extends ModelePDFCommandes * @param int $showaddress 0=no, 1=yes * @param Translate $outputlangs Object lang for output * @param string $titlekey Translation key to show as title of document - * @return void + * @return int Return topshift value */ protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "PdfOrderTitle") { // phpcs:enable - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; - // Translations + // Load traductions files required by page $outputlangs->loadLangs(array("main", "bills", "propal", "orders", "companies")); $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1393,8 +1412,8 @@ class pdf_eratosthene extends ModelePDFCommandes $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); @@ -1404,7 +1423,7 @@ class pdf_eratosthene extends ModelePDFCommandes if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; @@ -1414,20 +1433,20 @@ class pdf_eratosthene extends ModelePDFCommandes } if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { $pdf->SetTextColor(200, 0, 0); - $pdf->SetFont('', 'B', $default_font_size -2); + $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); } } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } } @@ -1459,7 +1478,15 @@ class pdf_eratosthene extends ModelePDFCommandes $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date, "%d %b %Y", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R'); + + if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && !empty($object->thirdparty->code_client)) + { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + } // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) diff --git a/htdocs/core/modules/commande/doc/pdf_proforma.modules.php b/htdocs/core/modules/commande/doc/pdf_proforma.modules.php index 9ba5c731ef5..c36b78d66ab 100644 --- a/htdocs/core/modules/commande/doc/pdf_proforma.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_proforma.modules.php @@ -28,7 +28,7 @@ * \brief File of Class to generate PDF orders with template Proforma */ -require_once DOL_DOCUMENT_ROOT.'/core/modules/commande/doc/pdf_einstein.modules.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/commande/doc/pdf_eratosthene.modules.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; @@ -38,7 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; /** * Class to generate PDF orders with template Proforma */ -class pdf_proforma extends pdf_einstein +class pdf_proforma extends pdf_eratosthene { /** diff --git a/htdocs/core/modules/contract/doc/doc_generic_contract_odt.modules.php b/htdocs/core/modules/contract/doc/doc_generic_contract_odt.modules.php index e7770981d09..4594a9d63cd 100644 --- a/htdocs/core/modules/contract/doc/doc_generic_contract_odt.modules.php +++ b/htdocs/core/modules/contract/doc/doc_generic_contract_odt.modules.php @@ -2,7 +2,7 @@ /* Copyright (C) 2010-2012 Laurent Destailleur * Copyright (C) 2012 Juanjo Menent * Copyright (C) 2018 Ferran Marcet - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -162,7 +162,7 @@ class doc_generic_contract_odt extends ModelePDFContract $texte .= $langs->trans("NumberOfModelFilesFound").': '.count($listoffiles).''; } - // Add select to upload a new template file. TODO Copy this feature on other admin pages. + // Add input to upload a new template file. $texte .= '
'.$langs->trans("UploadNewTemplate").' '; $texte .= ''; $texte .= ''; diff --git a/htdocs/core/modules/expedition/doc/doc_generic_shipment_odt.modules.php b/htdocs/core/modules/expedition/doc/doc_generic_shipment_odt.modules.php index 747096e852a..1ea817709e1 100644 --- a/htdocs/core/modules/expedition/doc/doc_generic_shipment_odt.modules.php +++ b/htdocs/core/modules/expedition/doc/doc_generic_shipment_odt.modules.php @@ -4,7 +4,7 @@ * Copyright (C) 2014 Marcos García * Copyright (C) 2016 Charlie Benke * Copyright (C) 2018-2019 Philippe Grand - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -119,7 +119,7 @@ class doc_generic_shipment_odt extends ModelePdfExpedition $form = new Form($this->db); $texte = $this->description.".
\n"; - $texte .= ''; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= ''; @@ -177,7 +177,11 @@ class doc_generic_shipment_odt extends ModelePdfExpedition } $texte .= '
'; } - + // Add input to upload a new template file. + $texte .= '
'.$langs->trans("UploadNewTemplate").' '; + $texte .= ''; + $texte .= ''; + $texte .= '
'; $texte .= ''; $texte .= '
'; $texte .= '
'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).''; - if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath); print '
'.$titre; if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print ' ('.$totalnboflines.')'; print '
'; /*if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("UserIsNotContactOfProject")); - else if ($disabledtask) + elseif ($disabledtask) { $titleassigntask = $langs->trans("AssignTaskToMe"); if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); @@ -1141,7 +1149,7 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; - print '
'; + print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); + if ($projectstatic->title) + { + print ' - '; + print ''.$projectstatic->title.''; + } + print '
'; + print $fuser->getNomUrl(1, 'withproject', 'time'); + print ''; + if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + print "'; + if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); + print ''; + print ''; + for ($k = 0 ; $k < $level ; $k++) print "   "; + print $taskstatic->getNomUrl(1, 'withproject', 'time'); + // Label task + print '
'; + for ($k = 0 ; $k < $level ; $k++) print "   "; + //print $taskstatic->getNomUrl(0, 'withproject', 'time'); + print $taskstatic->label; + //print "
"; + //for ($k = 0 ; $k < $level ; $k++) print "   "; + //print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0); + print "
'; + if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + else print '--:--'; + print ''; + print $formother->select_percent($lines[$i]->progress, $lines[$i]->id . 'progress'); + print ''; + // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user + if ($lines[$i]->duration) + { + print ''; + print convertSecondToTime($lines[$i]->duration, 'allhourmin'); + print ''; + } + else print '--:--'; + print "'; + $tmptimespent=$taskstatic->getSummaryOfTimeSpent($fuser->id); + if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + else print '--:--'; + print "'; + $placeholder=''; + if ($alreadyspent) + { + $tableCell.=''; + //$placeholder=' placeholder="00:00"'; + //$tableCell.='+'; + } + + $tableCell.=''; + $tableCell.=''; + if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + elseif ($disabledtask) + { + $titleassigntask = $langs->trans("AssignTaskToMe"); + if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + + print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); + } + print '
'; diff --git a/htdocs/core/modules/expedition/doc/pdf_espadon.modules.php b/htdocs/core/modules/expedition/doc/pdf_espadon.modules.php index 0d702adab60..b47149f26a6 100644 --- a/htdocs/core/modules/expedition/doc/pdf_espadon.modules.php +++ b/htdocs/core/modules/expedition/doc/pdf_espadon.modules.php @@ -168,25 +168,32 @@ class pdf_espadon extends ModelePdfExpedition // Load traductions files required by page $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch")); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch")); + } + $nblines = count($object->lines); // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); - if (! empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE)) + $realpatharray = array(); + if (!empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE)) { $objphoto = new Product($this->db); - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto = new Product($this->db); $objphoto->fetch($object->lines[$i]->fk_product); - $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/"; + $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/"; $dir = $conf->product->dir_output.'/'.$pdir; - $realpath=''; + $realpath = ''; foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { @@ -243,25 +250,25 @@ class pdf_espadon extends ModelePdfExpedition if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Set nblines with the new facture lines content after hook $nblines = count($object->lines); - $pdf=pdf_getInstance($this->format); + $pdf = pdf_getInstance($this->format); $default_font_size = pdf_getPDFFontSize($outputlangs); - $heightforinfotot = 8; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $heightforinfotot = 8; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -316,51 +323,51 @@ class pdf_espadon extends ModelePdfExpedition $tab_top = 88; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; $height_incoterms += 4; } } - if (! empty($object->note_public) || ! empty($object->tracking_number)) + if (!empty($object->note_public) || !empty($object->tracking_number)) { $tab_top = 88 + $height_incoterms; $tab_top_alt = $tab_top; $pdf->SetFont('', 'B', $default_font_size - 2); - $pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $outputlangs->transnoentities("TrackingNumber")." : " . $object->tracking_number, 0, 1, false, true, 'L'); + $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top - 1, $outputlangs->transnoentities("TrackingNumber")." : ".$object->tracking_number, 0, 1, false, true, 'L'); $tab_top_alt = $pdf->GetY(); //$tab_top_alt += 1; // Tracking number - if (! empty($object->tracking_number)) + if (!empty($object->tracking_number)) { $object->getUrlTrackingStatus($object->tracking_number); - if (! empty($object->tracking_url)) + if (!empty($object->tracking_url)) { if ($object->shipping_method_id > 0) { // Get code using getLabelFromKey - $code=$outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code'); - $label=''; - if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."
"; - $label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code)); + $code = $outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code'); + $label = ''; + if ($object->tracking_url != $object->tracking_number) $label .= $outputlangs->trans("LinkToTrackYourPackage")."
"; + $label .= $outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code)); //var_dump($object->tracking_url != $object->tracking_number);exit; if ($object->tracking_url != $object->tracking_number) { - $label.=" : "; - $label.=$object->tracking_url; + $label .= " : "; + $label .= $object->tracking_url; } $pdf->SetFont('', 'B', $default_font_size - 2); - $pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top_alt, $label, 0, 1, false, true, 'L'); + $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top_alt, $label, 0, 1, false, true, 'L'); $tab_top_alt = $pdf->GetY(); } @@ -368,25 +375,25 @@ class pdf_espadon extends ModelePdfExpedition } // Notes - if (! empty($object->note_public)) + if (!empty($object->note_public)) { - $pdf->SetFont('', '', $default_font_size - 1); // In loop to manage multi-page - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1); + $pdf->SetFont('', '', $default_font_size - 1); // In loop to manage multi-page + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1); } $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); $tab_height = $tab_height - $height_note; - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } else { - $height_note=0; + $height_note = 0; } @@ -407,30 +414,30 @@ class pdf_espadon extends ModelePdfExpedition for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; - if($this->getColumnStatus('photo')) + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot))) // If photo too high, we moved completely on new page + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposbefore+1); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; @@ -444,43 +451,42 @@ class pdf_espadon extends ModelePdfExpedition if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } } // Description of product line - if($this->getColumnStatus('desc')) + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot))) // There is no space left for total+free text + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -492,15 +498,15 @@ class pdf_espadon extends ModelePdfExpedition { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description or photo were moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { @@ -512,25 +518,25 @@ class pdf_espadon extends ModelePdfExpedition $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font + $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font // weight - $weighttxt=''; + $weighttxt = ''; if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight) { - $weighttxt=round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "weight", $object->lines[$i]->weight_units, 1); + $weighttxt = round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "weight", $object->lines[$i]->weight_units, 1); } - $voltxt=''; + $voltxt = ''; if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume) { - $voltxt=round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "volume", $object->lines[$i]->volume_units?$object->lines[$i]->volume_units:0, 1); + $voltxt = round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "volume", $object->lines[$i]->volume_units ? $object->lines[$i]->volume_units : 0, 1); } if ($this->getColumnStatus('weight')) { - $this->printStdColumnContent($pdf, $curY, 'weight', $weighttxt.(($weighttxt && $voltxt)?'
':'').$voltxt, array('html'=>1)); + $this->printStdColumnContent($pdf, $curY, 'weight', $weighttxt.(($weighttxt && $voltxt) ? '
' : '').$voltxt, array('html'=>1)); $nexY = max($pdf->GetY(), $nexY); } @@ -554,16 +560,16 @@ class pdf_espadon extends ModelePdfExpedition - $nexY+=3; - if ($weighttxt && $voltxt) $nexY+=2; + $nexY += 3; + if ($weighttxt && $voltxt) $nexY += 2; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY-1, $this->page_largeur - $this->marge_droite, $nexY-1); + $pdf->line($this->marge_gauche, $nexY - 1, $this->page_largeur - $this->marge_droite, $nexY - 1); $pdf->SetLineStyle(array('dash'=>0)); } @@ -582,10 +588,10 @@ class pdf_espadon extends ModelePdfExpedition $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -608,16 +614,16 @@ class pdf_espadon extends ModelePdfExpedition if ($pagenb == 1) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Display total area - $posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs); // Pagefoot $this->_pagefoot($pdf, $object, $outputlangs); @@ -684,7 +690,7 @@ class pdf_espadon extends ModelePdfExpedition $pdf->SetFont('', 'B', $default_font_size - 1); // Total table - $col1x = $this->posxweightvol-50; $col2x = $this->posxweightvol; + $col1x = $this->posxweightvol - 50; $col2x = $this->posxweightvol; /*if ($this->page_largeur < 210) // To work with US executive format { $col2x-=20; @@ -791,20 +797,22 @@ class pdf_espadon extends ModelePdfExpedition if (empty($hidetop)) { //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - if (empty($hidetop)){ - $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -840,19 +848,19 @@ class pdf_espadon extends ModelePdfExpedition $w = 110; - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-$w; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -864,21 +872,21 @@ class pdf_espadon extends ModelePdfExpedition } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } // Show barcode - if (! empty($conf->barcode->enabled)) + if (!empty($conf->barcode->enabled)) { - $posx=105; + $posx = 105; } else { - $posx=$this->marge_gauche+3; + $posx = $this->marge_gauche + 3; } //$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30); - if (! empty($conf->barcode->enabled)) + if (!empty($conf->barcode->enabled)) { // TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref //$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3); @@ -894,67 +902,67 @@ class pdf_espadon extends ModelePdfExpedition } - $posx=$this->page_largeur - $w - $this->marge_droite; - $posy=$this->marge_haute; + $posx = $this->page_largeur - $w - $this->marge_droite; + $posy = $this->marge_haute; $pdf->SetFont('', 'B', $default_font_size + 2); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $title=$outputlangs->transnoentities("SendingSheet"); + $title = $outputlangs->transnoentities("SendingSheet"); $pdf->MultiCell($w, 4, $title, '', 'R'); $pdf->SetFont('', '', $default_font_size + 1); - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending") ." : ".$object->ref, '', 'R'); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending")." : ".$object->ref, '', 'R'); // Date planned delivery - if (! empty($object->date_delivery)) + if (!empty($object->date_delivery)) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery, "day", false, $outputlangs, true), '', 'R'); } - if (! empty($object->thirdparty->code_client)) + if (!empty($object->thirdparty->code_client)) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); } $pdf->SetFont('', '', $default_font_size + 3); - $Yoff=25; + $Yoff = 25; // Add list of linked orders - $origin = $object->origin; - $origin_id = $object->origin_id; + $origin = $object->origin; + $origin_id = $object->origin_id; // TODO move to external function - if (! empty($conf->$origin->enabled)) // commonly $origin='commande' + if (!empty($conf->$origin->enabled)) // commonly $origin='commande' { $outputlangs->load('orders'); $classname = ucfirst($origin); $linkedobject = new $classname($this->db); - $result=$linkedobject->fetch($origin_id); + $result = $linkedobject->fetch($origin_id); if ($result >= 0) { //$linkedobject->fetchObjectLinked() Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects $pdf->SetFont('', '', $default_font_size - 2); - $text=$linkedobject->ref; - if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')'; - $Yoff = $Yoff+8; + $text = $linkedobject->ref; + if ($linkedobject->ref_client) $text .= ' ('.$linkedobject->ref_client.')'; + $Yoff = $Yoff + 8; $pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff); - $pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R'); - $Yoff = $Yoff+3; + $pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder")." : ".$outputlangs->transnoentities($text), 0, 'R'); + $Yoff = $Yoff + 3; $pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff); $pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date, "day", false, $outputlangs, true), 0, 'R'); } @@ -995,24 +1003,24 @@ class pdf_espadon extends ModelePdfExpedition $pdf->SetFillColor(255, 255, 255); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); - $pdf->MultiCell($widthrecbox-2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell($widthrecbox-2, 4, $carac_emetteur, 0, 'L'); + $pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L'); // If SHIPPING contact defined, we use it - $usecontact=false; - $arrayidcontact=$object->$origin->getIdContact('external', 'SHIPPING'); + $usecontact = false; + $arrayidcontact = $object->$origin->getIdContact('external', 'SHIPPING'); if (count($arrayidcontact) > 0) { - $usecontact=true; - $result=$object->fetch_contact($arrayidcontact[0]); + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); } //Recipient name @@ -1023,26 +1031,26 @@ class pdf_espadon extends ModelePdfExpedition $thirdparty = $object->thirdparty; } - $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs); + $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact)?$object->contact:null), $usecontact, 'targetwithdetails', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact) ? $object->contact : null), $usecontact, 'targetwithdetails', $object); // Show recipient - $widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; - $posx=$this->page_largeur - $this->marge_droite - $widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L'); @@ -1050,7 +1058,7 @@ class pdf_espadon extends ModelePdfExpedition // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } diff --git a/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php b/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php index c1654aa0aec..76743258193 100644 --- a/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php +++ b/htdocs/core/modules/expensereport/doc/pdf_standard.modules.php @@ -135,43 +135,41 @@ class pdf_standard extends ModeleExpenseReport // Page size for A4 format $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION - $this->option_modereg = 1; // Affiche mode reglement - $this->option_condreg = 1; // Affiche conditions reglement - $this->option_codeproduitservice = 1; // Affiche code produit-service - $this->option_multilang = 1; // Dispo en plusieurs langues - $this->option_escompte = 0; // Affiche si il y a eu escompte - $this->option_credit_note = 0; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise = !$mysoc->tva_assuj; + $this->option_logo = 1; // Affiche logo + $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION + $this->option_modereg = 1; // Affiche mode reglement + $this->option_condreg = 1; // Affiche conditions reglement + $this->option_codeproduitservice = 1; // Affiche code produit-service + $this->option_multilang = 1; // Dispo en plusieurs langues + $this->option_escompte = 0; // Affiche si il y a eu escompte + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; + $this->emetteur = $mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxpiece=$this->marge_gauche+1; - $this->posxcomment=$this->marge_gauche+10; + $this->posxpiece = $this->marge_gauche + 1; + $this->posxcomment = $this->marge_gauche + 10; //$this->posxdate=88; //$this->posxtype=107; //$this->posxprojet=120; - $this->posxtva=130; - $this->posxup=145; - $this->posxqty=168; - $this->postotalttc=178; + $this->posxtva = 130; + $this->posxup = 145; + $this->posxqty = 168; + $this->postotalttc = 178; // if (empty($conf->projet->enabled)) { // $this->posxtva-=20; // $this->posxup-=20; @@ -289,40 +287,40 @@ class pdf_standard extends ModeleExpenseReport $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Trips")); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); $tab_top = 95; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?65:10); + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 65 : 10); $tab_height = 130; $tab_height_newpage = 150; // Show notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } if ($notetoshow) { - $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object); $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); @@ -330,20 +328,20 @@ class pdf_standard extends ModeleExpenseReport $tab_top = 95; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxpiece-1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxpiece - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); $tab_height = $tab_height - $height_note; - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } else { - $height_note=0; + $height_note = 0; } $iniY = $tab_top + 7; @@ -351,41 +349,40 @@ class pdf_standard extends ModeleExpenseReport $nexY = $tab_top + 7; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) { - $pdf->SetFont('', '', $default_font_size - 2); // Into loop to work with multipage + for ($i = 0; $i < $nblines; $i++) { + $pdf->SetFont('', '', $default_font_size - 2); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. $pageposbefore = $pdf->getPage(); $curY = $nexY; $pdf->startTransaction(); $this->printLine($pdf, $object, $i, $curY, $default_font_size, $outputlangs, $hidedetails); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) { // There is a pagebreak $pdf->rollbackTransaction(true); $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. $this->printLine($pdf, $object, $i, $curY, $default_font_size, $outputlangs, $hidedetails); $pageposafter = $pdf->getPage(); $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) { + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text - if ($i == ($nblines-1)) { + if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -420,7 +417,7 @@ class pdf_standard extends ModeleExpenseReport // } //$nexY+=$nblineFollowComment*($pdf->getFontSize()*1.3); // Add space between lines - $nexY += ($pdf->getFontSize()*1.3); // Add space between lines + $nexY += ($pdf->getFontSize() * 1.3); // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -516,31 +513,31 @@ class pdf_standard extends ModeleExpenseReport // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "EXPENSEREPORT_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "EXPENSEREPORT_OUTPUTDIR"); return 0; } } @@ -599,30 +596,30 @@ class pdf_standard extends ModeleExpenseReport if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { $vat_rate = pdf_getlinevatrate($object, $linenumber, $outputlangs, $hidedetails); $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva-0.8, 4, $vat_rate, 0, 'R'); + $pdf->MultiCell($this->posxup - $this->posxtva - 0.8, 4, $vat_rate, 0, 'R'); } // Unit price $pdf->SetXY($this->posxup, $curY); - $pdf->MultiCell($this->posxqty-$this->posxup-0.8, 4, price($object->lines[$linenumber]->value_unit), 0, 'R'); + $pdf->MultiCell($this->posxqty - $this->posxup - 0.8, 4, price($object->lines[$linenumber]->value_unit), 0, 'R'); // Quantity $pdf->SetXY($this->posxqty, $curY); - $pdf->MultiCell($this->postotalttc-$this->posxqty-0.8, 4, $object->lines[$linenumber]->qty, 0, 'R'); + $pdf->MultiCell($this->postotalttc - $this->posxqty - 0.8, 4, $object->lines[$linenumber]->qty, 0, 'R'); // Total with all taxes - $pdf->SetXY($this->postotalttc-1, $curY); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalttc, 4, price($object->lines[$linenumber]->total_ttc), 0, 'R'); + $pdf->SetXY($this->postotalttc - 1, $curY); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalttc, 4, price($object->lines[$linenumber]->total_ttc), 0, 'R'); // Comments $pdf->SetXY($this->posxcomment, $curY); - $comment = $outputlangs->trans("Date").':'. dol_print_date($object->lines[$linenumber]->date, "day", false, $outputlangs).' '; - $comment .= $outputlangs->trans("Type").':'. $expensereporttypecodetoshow.'
'; - if (! empty($object->lines[$linenumber]->projet_ref)) { - $comment .= $outputlangs->trans("Project").':'. $object->lines[$linenumber]->projet_ref.'
'; + $comment = $outputlangs->trans("Date").':'.dol_print_date($object->lines[$linenumber]->date, "day", false, $outputlangs).' '; + $comment .= $outputlangs->trans("Type").':'.$expensereporttypecodetoshow.'
'; + if (!empty($object->lines[$linenumber]->projet_ref)) { + $comment .= $outputlangs->trans("Project").':'.$object->lines[$linenumber]->projet_ref.'
'; } $comment .= $object->lines[$linenumber]->comments; - $pdf->writeHTMLCell($this->posxtva-$this->posxcomment-0.8, 4, $this->posxcomment-1, $curY, $comment, 0, 1); + $pdf->writeHTMLCell($this->posxtva - $this->posxcomment - 0.8, 4, $this->posxcomment - 1, $curY, $comment, 0, 1); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore @@ -758,96 +755,96 @@ class pdf_standard extends ModeleExpenseReport // Show sender information if (empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) { - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $pdf->SetXY($posx+2, $posy+8); + $pdf->SetXY($posx + 2, $posy + 8); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); } else { - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset(dolGetFirstLastname($receiver->firstname, $receiver->lastname)), 0, 'L'); - $pdf->SetXY($posx+2, $posy+8); + $pdf->SetXY($posx + 2, $posy + 8); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $expense_receiver, 0, 'L'); } // Show recipient - $posy=50; - $posx=100; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $posy = 50; + $posx = 100; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', 'B', 8); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(80, 5, $outputlangs->transnoentities("TripNDF")." :", 0, 'L'); $pdf->rect($posx, $posy, $this->page_largeur - $this->marge_gauche - $posx, $hautcadre); // Informations for trip (dates and users workflow) if ($object->fk_user_author > 0) { - $userfee=new User($this->db); + $userfee = new User($this->db); $userfee->fetch($object->fk_user_author); - $posy+=3; - $pdf->SetXY($posx+2, $posy); + $posy += 3; + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', 10); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("AUTHOR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("DateCreation")." : ".dol_print_date($object->date_create, "day", false, $outputlangs), 0, 'L'); } - if ($object->fk_statut==99) { + if ($object->fk_statut == 99) { if ($object->fk_user_refuse > 0) { - $userfee=new User($this->db); - $userfee->fetch($object->fk_user_refuse); $posy+=6; - $pdf->SetXY($posx+2, $posy); + $userfee = new User($this->db); + $userfee->fetch($object->fk_user_refuse); $posy += 6; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("REFUSEUR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("MOTIF_REFUS")." : ".$outputlangs->convToOutputCharset($object->detail_refuse), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_REFUS")." : ".dol_print_date($object->date_refuse, "day", false, $outputlangs), 0, 'L'); } } - elseif($object->fk_statut==4) + elseif ($object->fk_statut == 4) { if ($object->fk_user_cancel > 0) { - $userfee=new User($this->db); - $userfee->fetch($object->fk_user_cancel); $posy+=6; - $pdf->SetXY($posx+2, $posy); + $userfee = new User($this->db); + $userfee->fetch($object->fk_user_cancel); $posy += 6; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("CANCEL_USER")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("MOTIF_CANCEL")." : ".$outputlangs->convToOutputCharset($object->detail_cancel), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_CANCEL")." : ".dol_print_date($object->date_cancel, "day", false, $outputlangs), 0, 'L'); } } else { if ($object->fk_user_approve > 0) { - $userfee=new User($this->db); - $userfee->fetch($object->fk_user_approve); $posy+=6; - $pdf->SetXY($posx+2, $posy); + $userfee = new User($this->db); + $userfee->fetch($object->fk_user_approve); $posy += 6; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("VALIDOR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("DateApprove")." : ".dol_print_date($object->date_approve, "day", false, $outputlangs), 0, 'L'); } } - if($object->fk_statut==6) { + if ($object->fk_statut == 6) { if ($object->fk_user_paid > 0) { - $userfee=new User($this->db); - $userfee->fetch($object->fk_user_paid); $posy+=6; - $pdf->SetXY($posx+2, $posy); + $userfee = new User($this->db); + $userfee->fetch($object->fk_user_paid); $posy += 6; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("AUTHORPAIEMENT")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L'); - $posy+=5; - $pdf->SetXY($posx+2, $posy); + $posy += 5; + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_PAIEMENT")." : ".dol_print_date($object->date_paiement, "day", false, $outputlangs), 0, 'L'); } } @@ -883,31 +880,31 @@ class pdf_standard extends ModeleExpenseReport $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 4), $tab_top -4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 4), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); $pdf->SetDrawColor(128, 128, 128); // Rect takes a length in 3rd parameter - $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height); + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height); // line prend une position y en 3eme param if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5); + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); } $pdf->SetFont('', '', 8); // Accountancy piece if (empty($hidetop)) { - $pdf->SetXY($this->posxpiece-1, $tab_top+1); - $pdf->MultiCell($this->posxcomment-$this->posxpiece-1, 1, '', '', 'R'); + $pdf->SetXY($this->posxpiece - 1, $tab_top + 1); + $pdf->MultiCell($this->posxcomment - $this->posxpiece - 1, 1, '', '', 'R'); } // Comments - $pdf->line($this->posxcomment-1, $tab_top, $this->posxcomment-1, $tab_top + $tab_height); + $pdf->line($this->posxcomment - 1, $tab_top, $this->posxcomment - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxcomment-1, $tab_top+1); - $pdf->MultiCell($this->posxdate-$this->posxcomment-1, 1, $outputlangs->transnoentities("Description"), '', 'L'); + $pdf->SetXY($this->posxcomment - 1, $tab_top + 1); + $pdf->MultiCell($this->posxdate - $this->posxcomment - 1, 1, $outputlangs->transnoentities("Description"), '', 'L'); } // Date @@ -938,32 +935,32 @@ class pdf_standard extends ModeleExpenseReport // VAT if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { - $pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height); + $pdf->line($this->posxtva - 1, $tab_top, $this->posxtva - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxtva-1, $tab_top+1); - $pdf->MultiCell($this->posxup-$this->posxtva - 1, 2, $outputlangs->transnoentities("VAT"), '', 'C'); + $pdf->SetXY($this->posxtva - 1, $tab_top + 1); + $pdf->MultiCell($this->posxup - $this->posxtva - 1, 2, $outputlangs->transnoentities("VAT"), '', 'C'); } } // Unit price - $pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height); + $pdf->line($this->posxup - 1, $tab_top, $this->posxup - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxup-1, $tab_top+1); - $pdf->MultiCell($this->posxqty-$this->posxup-1, 2, $outputlangs->transnoentities("PriceU"), '', 'C'); + $pdf->SetXY($this->posxup - 1, $tab_top + 1); + $pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceU"), '', 'C'); } // Quantity - $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height); + $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxqty-1, $tab_top+1); - $pdf->MultiCell($this->postotalttc-$this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); + $pdf->SetXY($this->posxqty - 1, $tab_top + 1); + $pdf->MultiCell($this->postotalttc - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); } // Total with all taxes $pdf->line($this->postotalttc, $tab_top, $this->postotalttc, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->postotalttc-1, $tab_top+1); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalttc, 2, $outputlangs->transnoentities("TotalTTC"), '', 'R'); + $pdf->SetXY($this->postotalttc - 1, $tab_top + 1); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalttc, 2, $outputlangs->transnoentities("TotalTTC"), '', 'R'); } $pdf->SetTextColor(0, 0, 0); @@ -990,94 +987,94 @@ class pdf_standard extends ModeleExpenseReport $default_font_size = pdf_getPDFFontSize($outputlangs); - $title=$outputlangs->transnoentities("PaymentsAlreadyDone"); + $title = $outputlangs->transnoentities("PaymentsAlreadyDone"); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($tab3_posx, $tab3_top - 4); $pdf->SetTextColor(0, 0, 0); $pdf->MultiCell(60, 3, $title, 0, 'L', 0); - $pdf->line($tab3_posx, $tab3_top, $tab3_posx+$tab3_width+2, $tab3_top); // Top border line of table title + $pdf->line($tab3_posx, $tab3_top, $tab3_posx + $tab3_width + 2, $tab3_top); // Top border line of table title - $pdf->SetXY($tab3_posx, $tab3_top+1); + $pdf->SetXY($tab3_posx, $tab3_top + 1); $pdf->MultiCell(20, 3, $outputlangs->transnoentities("Date"), 0, 'L', 0); - $pdf->SetXY($tab3_posx+19, $tab3_top+1); // Old value 17 + $pdf->SetXY($tab3_posx + 19, $tab3_top + 1); // Old value 17 $pdf->MultiCell(15, 3, $outputlangs->transnoentities("Amount"), 0, 'C', 0); - $pdf->SetXY($tab3_posx+35, $tab3_top+1); + $pdf->SetXY($tab3_posx + 35, $tab3_top + 1); $pdf->MultiCell(30, 3, $outputlangs->transnoentities("Type"), 0, 'L', 0); - if (! empty($conf->banque->enabled)) { - $pdf->SetXY($tab3_posx+65, $tab3_top+1); + if (!empty($conf->banque->enabled)) { + $pdf->SetXY($tab3_posx + 65, $tab3_top + 1); $pdf->MultiCell(25, 3, $outputlangs->transnoentities("BankAccount"), 0, 'L', 0); } - $pdf->line($tab3_posx, $tab3_top+$tab3_height, $tab3_posx+$tab3_width+2, $tab3_top+$tab3_height); // Bottom border line of table title + $pdf->line($tab3_posx, $tab3_top + $tab3_height, $tab3_posx + $tab3_width + 2, $tab3_top + $tab3_height); // Bottom border line of table title - $y=0; + $y = 0; // Loop on each payment // TODO create method on expensereport class to get payments // Payments already done (from payment on this expensereport) $sql = "SELECT p.rowid, p.num_payment, p.datep as dp, p.amount, p.fk_bank,"; - $sql.= "c.code as p_code, c.libelle as payment_type,"; - $sql.= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal"; - $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = 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.= " WHERE e.rowid = '".$object->id."'"; - $sql.= " AND p.fk_expensereport = e.rowid"; - $sql.= ' AND e.entity IN ('.getEntity('expensereport').')'; - $sql.= " ORDER BY dp"; + $sql .= "c.code as p_code, c.libelle as payment_type,"; + $sql .= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = 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 .= " WHERE e.rowid = '".$object->id."'"; + $sql .= " AND p.fk_expensereport = e.rowid"; + $sql .= ' AND e.entity IN ('.getEntity('expensereport').')'; + $sql .= " ORDER BY dp"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $totalpaid = 0; - $i=0; + $i = 0; while ($i < $num) { - $y+=$tab3_height; + $y += $tab3_height; $row = $this->db->fetch_object($resql); - $pdf->SetXY($tab3_posx, $tab3_top+$y+1); + $pdf->SetXY($tab3_posx, $tab3_top + $y + 1); $pdf->MultiCell(20, 3, dol_print_date($this->db->jdate($row->dp), 'day', false, $outputlangs, true), 0, 'L', 0); - $pdf->SetXY($tab3_posx+17, $tab3_top+$y+1); + $pdf->SetXY($tab3_posx + 17, $tab3_top + $y + 1); $pdf->MultiCell(15, 3, price($sign * $row->amount, 0, $outputlangs), 0, 'R', 0); - $pdf->SetXY($tab3_posx+35, $tab3_top+$y+1); - $oper = $outputlangs->transnoentitiesnoconv("PaymentTypeShort" . $row->p_code); + $pdf->SetXY($tab3_posx + 35, $tab3_top + $y + 1); + $oper = $outputlangs->transnoentitiesnoconv("PaymentTypeShort".$row->p_code); $pdf->MultiCell(40, 3, $oper, 0, 'L', 0); - if (! empty($conf->banque->enabled)) { - $pdf->SetXY($tab3_posx+65, $tab3_top+$y+1); + if (!empty($conf->banque->enabled)) { + $pdf->SetXY($tab3_posx + 65, $tab3_top + $y + 1); $pdf->MultiCell(30, 3, $row->baref, 0, 'L', 0); } - $pdf->line($tab3_posx, $tab3_top+$y+$tab3_height, $tab3_posx+$tab3_width+2, $tab3_top+$y+$tab3_height); // Bottom line border of table + $pdf->line($tab3_posx, $tab3_top + $y + $tab3_height, $tab3_posx + $tab3_width + 2, $tab3_top + $y + $tab3_height); // Bottom line border of table $totalpaid += $row->amount; $i++; } if ($num > 0 && $object->paid == 0) { - $y+=$tab3_height; + $y += $tab3_height; - $pdf->SetXY($tab3_posx+17, $tab3_top+$y); + $pdf->SetXY($tab3_posx + 17, $tab3_top + $y); $pdf->MultiCell(15, 3, price($totalpaid), 0, 'R', 0); - $pdf->SetXY($tab3_posx+35, $tab3_top+$y); + $pdf->SetXY($tab3_posx + 35, $tab3_top + $y); $pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("AlreadyPaid"), 0, 'L', 0); - $y+=$tab3_height-2; - $pdf->SetXY($tab3_posx+17, $tab3_top+$y); + $y += $tab3_height - 2; + $pdf->SetXY($tab3_posx + 17, $tab3_top + $y); $pdf->MultiCell(15, 3, price($object->total_ttc), 0, 'R', 0); - $pdf->SetXY($tab3_posx+35, $tab3_top+$y); + $pdf->SetXY($tab3_posx + 35, $tab3_top + $y); $pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("AmountExpected"), 0, 'L', 0); - $y+=$tab3_height-2; + $y += $tab3_height - 2; $remaintopay = $object->total_ttc - $totalpaid; - $pdf->SetXY($tab3_posx+17, $tab3_top+$y); + $pdf->SetXY($tab3_posx + 17, $tab3_top + $y); $pdf->MultiCell(15, 3, price($remaintopay), 0, 'R', 0); - $pdf->SetXY($tab3_posx+35, $tab3_top+$y); + $pdf->SetXY($tab3_posx + 35, $tab3_top + $y); $pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("RemainderToPay"), 0, 'L', 0); } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } diff --git a/htdocs/core/modules/export/export_excel.modules.php b/htdocs/core/modules/export/export_excel.modules.php deleted file mode 100644 index 43cb4d6e9cd..00000000000 --- a/htdocs/core/modules/export/export_excel.modules.php +++ /dev/null @@ -1,526 +0,0 @@ - - * Copyright (C) 2012 Marcos García - * - * 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/modules/export/export_excel.modules.php - * \ingroup export - * \brief File of class to generate export file with Excel format - */ - -require_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - -/** - * Class to build export files with Excel format - */ -class ExportExcel extends ModeleExports -{ - /** - * @var string ID - */ - public $id; - - /** - * @var string Export Excel label - */ - public $label; - - public $extension; - - /** - * Dolibarr version of the loaded document - * @var string - */ - public $version = 'dolibarr'; - - public $label_lib; - - public $version_lib; - - public $workbook; // Handle file - - public $worksheet; // Handle sheet - - public $row; - - public $col; - - public $file; // To save filename - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs; - $this->db = $db; - - $this->id='excel'; // Same value then xxx in file name export_xxx.modules.php - $this->label='Excel 95 (old library)'; // Label of driver - $this->desc = $langs->trans('Excel95FormatDesc'); - $this->extension='xls'; // Extension for generated file by this driver - $this->picto='mime/xls'; // Picto - $this->version='1.30'; // Driver version - - $this->disabled = (in_array(constant('PHPEXCEL_PATH'), array('disabled','disabled/'))?1:0); // A condition to disable module (used for native debian packages) - - if (empty($this->disabled)) - { - // If driver use an external library, put its name here - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_workbookbig.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_worksheet.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'functions.writeexcel_utility.inc.php'; - $this->label_lib='PhpWriteExcel'; - $this->version_lib='unknown'; - } - else - { - require_once PHPEXCEL_PATH.'PHPExcel.php'; - require_once PHPEXCEL_PATH.'PHPExcel/Style/Alignment.php'; - $this->label_lib='PhpExcel'; - $this->version_lib='1.8.0'; // No way to get info from library - } - } - - $this->row=0; - } - - /** - * getDriverId - * - * @return string - */ - public function getDriverId() - { - return $this->id; - } - - /** - * getDriverLabel - * - * @return string Return driver label - */ - public function getDriverLabel() - { - return $this->label; - } - - /** - * getDriverDesc - * - * @return string - */ - public function getDriverDesc() - { - return $this->desc; - } - - /** - * getDriverExtension - * - * @return string - */ - public function getDriverExtension() - { - return $this->extension; - } - - /** - * getDriverVersion - * - * @return string - */ - public function getDriverVersion() - { - return $this->version; - } - - /** - * getLibLabel - * - * @return string - */ - public function getLibLabel() - { - return $this->label_lib; - } - - /** - * getLibVersion - * - * @return string - */ - public function getLibVersion() - { - return $this->version_lib; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Open output file - * - * @param string $file File name to generate - * @param Translate $outputlangs Output language object - * @return int <0 if KO, >=0 if OK - */ - public function open_file($file, $outputlangs) - { - // phpcs:enable - global $user,$conf,$langs; - - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $outputlangs->charset_output='ISO-8859-1'; // Because Excel 5 format is ISO - } - - dol_syslog(get_class($this)."::open_file file=".$file); - $this->file=$file; - - $ret=1; - - $outputlangs->load("exports"); - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) { - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_workbookbig.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_worksheet.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'functions.writeexcel_utility.inc.php'; - $this->workbook = new writeexcel_workbookbig($file); - $this->workbook->set_tempdir($conf->export->dir_temp); // Set temporary directory - $this->workbook->set_sheetname($outputlangs->trans("Sheet")); - $this->worksheet = &$this->workbook->addworksheet(); - } - else - { - require_once PHPEXCEL_PATH.'PHPExcel.php'; - require_once PHPEXCEL_PATH.'PHPExcel/Style/Alignment.php'; - - if ($this->id == 'excel2007') - { - if (! class_exists('ZipArchive')) // For Excel2007, PHPExcel need ZipArchive - { - $langs->load("errors"); - $this->error=$langs->trans('ErrorPHPNeedModule', 'zip'); - return -1; - } - } - - if (!empty($conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR)) { - $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_discISAM; - $cacheSettings = array ( - 'dir' => $conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR - ); - PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); - } - - $this->workbook = new PHPExcel(); - $this->workbook->getProperties()->setCreator($user->getFullName($outputlangs).' - '.DOL_APPLICATION_TITLE.' '.DOL_VERSION); - //$this->workbook->getProperties()->setLastModifiedBy('Dolibarr '.DOL_VERSION); - $this->workbook->getProperties()->setTitle(basename($file)); - $this->workbook->getProperties()->setSubject(basename($file)); - $this->workbook->getProperties()->setDescription(DOL_APPLICATION_TITLE.' '.DOL_VERSION); - - $this->workbook->setActiveSheetIndex(0); - $this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet")); - $this->workbook->getActiveSheet()->getDefaultRowDimension()->setRowHeight(16); - } - return $ret; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Write header - * - * @param Translate $outputlangs Object lang to translate values - * @return int <0 if KO, >0 if OK - */ - public function write_header($outputlangs) - { - // phpcs:enable - //$outputlangs->charset_output='ISO-8859-1'; // Because Excel 5 format is ISO - - return 0; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output title line into file - * - * @param array $array_export_fields_label Array with list of label of fields - * @param array $array_selected_sorted Array with list of field to export - * @param Translate $outputlangs Object lang to translate values - * @param array $array_types Array with types of fields - * @return int <0 if KO, >0 if OK - */ - public function write_title($array_export_fields_label, $array_selected_sorted, $outputlangs, $array_types) - { - // phpcs:enable - global $conf; - - // Create a format for the column headings - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $outputlangs->charset_output='ISO-8859-1'; // Because Excel 5 format is ISO - - $formatheader =$this->workbook->addformat(); - $formatheader->set_bold(); - $formatheader->set_color('blue'); - //$formatheader->set_size(12); - //$formatheader->set_font("Courier New"); - //$formatheader->set_align('center'); - } - else - { - $this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true); - $this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); - } - - $this->col=0; - foreach($array_selected_sorted as $code => $value) - { - $alias=$array_export_fields_label[$code]; - //print "dd".$alias; - if (empty($alias)) dol_print_error('', 'Bad value for field with code='.$code.'. Try to redefine export.'); - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $this->worksheet->write($this->row, $this->col, $outputlangs->transnoentities($alias), $formatheader); - } - else - { - $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row+1, $outputlangs->transnoentities($alias)); - if (! empty($array_types[$code]) && in_array($array_types[$code], array('Date','Numeric','TextAuto'))) // Set autowidth for some types - { - $this->workbook->getActiveSheet()->getColumnDimension($this->column2Letter($this->col + 1))->setAutoSize(true); - } - } - $this->col++; - } - $this->row++; - return 0; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output record line into file - * - * @param array $array_selected_sorted Array with list of field to export - * @param resource $objp A record from a fetch with all fields from select - * @param Translate $outputlangs Object lang to translate values - * @param array $array_types Array with types of fields - * @return int <0 if KO, >0 if OK - */ - public function write_record($array_selected_sorted, $objp, $outputlangs, $array_types) - { - // phpcs:enable - global $conf; - - // Create a format for the column headings - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $outputlangs->charset_output='ISO-8859-1'; // Because Excel 5 format is ISO - } - - // Define first row - $this->col=0; - - $reg=array(); - - foreach($array_selected_sorted as $code => $value) - { - if (strpos($code, ' as ') == 0) $alias=str_replace(array('.','-','(',')'), '_', $code); - else $alias=substr($code, strpos($code, ' as ') + 4); - if (empty($alias)) dol_print_error('', 'Bad value for field with code='.$code.'. Try to redefine export.'); - $newvalue=$objp->$alias; - - $newvalue=$this->excel_clean($newvalue); - $typefield=isset($array_types[$code])?$array_types[$code]:''; - - if (preg_match('/^Select:/i', $typefield, $reg) && $typefield = substr($typefield, 7)) - { - $array = unserialize($typefield); - $array = $array['options']; - $newvalue = $array[$newvalue]; - } - - // Traduction newvalue - if (preg_match('/^\((.*)\)$/i', $newvalue, $reg)) - { - $newvalue=$outputlangs->transnoentities($reg[1]); - } - else - { - $newvalue=$outputlangs->convToOutputCharset($newvalue); - } - - if (preg_match('/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$/i', $newvalue)) - { - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $formatdate=$this->workbook->addformat(); - $formatdate->set_num_format('yyyy-mm-dd'); - //$formatdate->set_num_format(0x0f); - $arrayvalue=preg_split('/[.,]/', xl_parse_date($newvalue)); - //print "x".$arrayvalue[0].'.'.strval($arrayvalue[1]).'
'; - $newvalue=strval($arrayvalue[0]).'.'.strval($arrayvalue[1]); // $newvalue=strval(36892.521); directly does not work because . will be convert into , later - $this->worksheet->write($this->row, $this->col, $newvalue, PHPExcel_Shared_Date::PHPToExcel($formatdate)); - } - else - { - $newvalue=dol_stringtotime($newvalue); - $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row+1, PHPExcel_Shared_Date::PHPToExcel($newvalue)); - $coord=$this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row+1)->getCoordinate(); - $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('yyyy-mm-dd'); - } - } - elseif (preg_match('/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/i', $newvalue)) - { - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $formatdatehour=$this->workbook->addformat(); - $formatdatehour->set_num_format('yyyy-mm-dd hh:mm:ss'); - //$formatdatehour->set_num_format(0x0f); - $arrayvalue=preg_split('/[.,]/', xl_parse_date($newvalue)); - //print "x".$arrayvalue[0].'.'.strval($arrayvalue[1]).'
'; - $newvalue=strval($arrayvalue[0]).'.'.strval($arrayvalue[1]); // $newvalue=strval(36892.521); directly does not work because . will be convert into , later - $this->worksheet->write($this->row, $this->col, $newvalue, $formatdatehour); - } - else - { - $newvalue=dol_stringtotime($newvalue); - $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row+1, PHPExcel_Shared_Date::PHPToExcel($newvalue)); - $coord=$this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row+1)->getCoordinate(); - $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('yyyy-mm-dd h:mm:ss'); - } - } - else - { - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $this->worksheet->write($this->row, $this->col, $newvalue); - } - else - { - if ($typefield == 'Text' || $typefield == 'TextAuto') - { - //$this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row+1)->setValueExplicit($newvalue, PHPExcel_Cell_DataType::TYPE_STRING); - $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row+1, (string) $newvalue); - $coord=$this->workbook->getActiveSheet()->getCellByColumnAndRow($this->col, $this->row+1)->getCoordinate(); - $this->workbook->getActiveSheet()->getStyle($coord)->getNumberFormat()->setFormatCode('@'); - $this->workbook->getActiveSheet()->getStyle($coord)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); - } - else - { - $this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($this->col, $this->row+1, $newvalue); - } - } - } - $this->col++; - } - $this->row++; - return 0; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Write footer - * - * @param Translate $outputlangs Output language object - * @return int <0 if KO, >0 if OK - */ - public function write_footer($outputlangs) - { - // phpcs:enable - return 0; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Close Excel file - * - * @return int <0 if KO, >0 if OK - */ - public function close_file() - { - // phpcs:enable - global $conf; - - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $this->workbook->close(); - } - else - { - require_once PHPEXCEL_PATH.'PHPExcel/Writer/Excel5.php'; - $objWriter = new PHPExcel_Writer_Excel5($this->workbook); - $objWriter->save($this->file); - $this->workbook->disconnectWorksheets(); - unset($this->workbook); - } - return 1; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Clean a cell to respect rules of Excel file cells - * - * @param string $newvalue String to clean - * @return string Value cleaned - */ - public function excel_clean($newvalue) - { - // phpcs:enable - // Rule Dolibarr: No HTML - $newvalue=dol_string_nohtmltag($newvalue); - - return $newvalue; - } - - - /** - * Convert a column to letter (1->A, 0->B, 27->AA, ...) - * - * @param int $c Column position - * @return string Letter - */ - public function column2Letter($c) - { - - $c = intval($c); - $letter = ''; - if ($c <= 0) { - return ''; - } - - while ($c != 0) { - $p = ($c - 1) % 26; - $c = intval(($c - $p) / 26); - $letter = chr(65 + $p) . $letter; - } - - return $letter; - } -} diff --git a/htdocs/core/modules/export/export_excel2007.modules.php b/htdocs/core/modules/export/export_excel2007.modules.php deleted file mode 100644 index ac9eb3ddfe6..00000000000 --- a/htdocs/core/modules/export/export_excel2007.modules.php +++ /dev/null @@ -1,135 +0,0 @@ - - * Copyright (C) 2012 Marcos García - * - * 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/modules/export/export_excel2007.modules.php - * \ingroup export - * \brief File of class to generate export file with Excel format - */ - -require_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; -require_once DOL_DOCUMENT_ROOT.'/core/modules/export/export_excel.modules.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - -/** - * Class to build export files with Excel format - */ -class ExportExcel2007 extends ExportExcel -{ - /** - * @var string ID - */ - public $id; - - /** - * @var string label - */ - public $label; - - public $extension; - - /** - * Dolibarr version of the loaded document - * @var string - */ - public $version = 'dolibarr'; - - public $label_lib; - - public $version_lib; - - public $workbook; // Handle fichier - - public $worksheet; // Handle onglet - - public $row; - - public $col; - - public $file; // To save filename - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs; - $this->db = $db; - - $this->id='excel2007'; // Same value then xxx in file name export_xxx.modules.php - $this->label='Excel 2007 (old library)'; // Label of driver - $this->desc = $langs->trans('Excel2007FormatDesc'); - $this->extension='xlsx'; // Extension for generated file by this driver - $this->picto='mime/xls'; // Picto - $this->version='1.30'; // Driver version - - $this->disabled = (in_array(constant('PHPEXCEL_PATH'), array('disabled','disabled/'))?1:0); // A condition to disable module (used for native debian packages) - - if (empty($this->disabled)) - { - // If driver use an external library, put its name here - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_workbookbig.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'class.writeexcel_worksheet.inc.php'; - require_once PHP_WRITEEXCEL_PATH.'functions.writeexcel_utility.inc.php'; - $this->label_lib='PhpWriteExcel'; - $this->version_lib='unknown'; - } - else - { - require_once PHPEXCEL_PATH.'PHPExcel.php'; - require_once PHPEXCEL_PATH.'PHPExcel/Style/Alignment.php'; - $this->label_lib='PhpExcel'; - $this->version_lib='1.8.0'; // No way to get info from library - } - } - - $this->row=0; - } - - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Close Excel file - * - * @return int <0 if KO, >0 if OK - */ - public function close_file() - { - // phpcs:enable - global $conf; - - if (! empty($conf->global->MAIN_USE_PHP_WRITEEXCEL)) - { - $this->workbook->close(); - } - else - { - require_once PHPEXCEL_PATH.'PHPExcel/Writer/Excel5.php'; - $objWriter = new PHPExcel_Writer_Excel2007($this->workbook); - $objWriter->save($this->file); - $this->workbook->disconnectWorksheets(); - unset($this->workbook); - } - return 1; - } -} diff --git a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php index a6e28214335..ef05b9b2df9 100644 --- a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php +++ b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php @@ -3,7 +3,7 @@ * Copyright (C) 2012 Regis Houssin * Copyright (C) 2014 Marcos García * Copyright (C) 2016 Charlie Benke - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -118,7 +118,7 @@ class doc_generic_invoice_odt extends ModelePDFFactures $form = new Form($this->db); $texte = $this->description.".
\n"; - $texte .= ''; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= ''; @@ -176,7 +176,11 @@ class doc_generic_invoice_odt extends ModelePDFFactures } $texte .= ''; } - + // Add input to upload a new template file. + $texte .= '
'.$langs->trans("UploadNewTemplate").' '; + $texte .= ''; + $texte .= ''; + $texte .= '
'; $texte .= '
'; diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index 6b6c6bb2beb..f0a3230595e 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -117,7 +117,7 @@ class pdf_crabe extends ModelePDFFactures /** * Issuer - * @var Societe object that emits + * @var Societe Object that emits */ public $emetteur; @@ -171,8 +171,6 @@ class pdf_crabe extends ModelePDFFactures $this->option_freetext = 1; // Support add of a personalised text $this->option_draft_watermark = 1; // Support add of a watermark on drafts - $this->franchise = !$mysoc->tva_assuj; - // Get source company $this->emetteur = $mysoc; if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined @@ -977,14 +975,14 @@ class pdf_crabe extends ModelePDFFactures protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); @@ -1052,13 +1050,28 @@ class pdf_crabe extends ModelePDFFactures $lib_mode_reg = $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) != ('PaymentType'.$object->mode_reglement_code) ? $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) : $outputlangs->convToOutputCharset($object->mode_reglement); $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); + // Show online payment link + $useonlinepayment = ((! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)) && !empty($conf->global->PDF_SHOW_LINK_TO_ONLINE_PAYMENT)); + if (($object->mode_reglement_code == 'CB' || $object->mode_reglement_code == 'VAD') && $object->statut != Facture::STATUS_DRAFT && $useonlinepayment) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + global $langs; + + $langs->loadLangs(array('payment', 'paybox')); + $servicename=$langs->transnoentities('Online'); + $paiement_url = getOnlinePaymentUrl('', 'invoice', $object->ref, '', '', ''); + $linktopay = $langs->trans("ToOfferALinkForOnlinePayment", $servicename).' '.$outputlangs->transnoentities("ClickHere").''; + + $pdf->writeHTMLCell(80, 10, '', '', dol_htmlentitiesbr($linktopay), 0, 1); + } + + $posy = $pdf->GetY() + 2; } // Show payment mode CHQ if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'CHQ') { - // If unregulated or forced payment mode to CHQ + // If payment mode unregulated or payment mode forced to CHQ if (!empty($conf->global->FACTURE_CHQ_NUMBER)) { $diffsizetitle = (empty($conf->global->PDF_DIFFSIZE_TITLE) ? 3 : $conf->global->PDF_DIFFSIZE_TITLE); @@ -1631,7 +1644,7 @@ class pdf_crabe extends ModelePDFFactures if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; diff --git a/htdocs/core/modules/facture/doc/pdf_sponge.modules.php b/htdocs/core/modules/facture/doc/pdf_sponge.modules.php index 0df384cdeb6..60d4650921b 100644 --- a/htdocs/core/modules/facture/doc/pdf_sponge.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_sponge.modules.php @@ -78,7 +78,7 @@ class pdf_sponge extends ModelePDFFactures * Dolibarr version of the loaded document * @var string */ - public $version = 'development'; + public $version = 'dolibarr'; /** * @var int page_largeur @@ -117,7 +117,7 @@ class pdf_sponge extends ModelePDFFactures /** * Issuer - * @var Societe + * @var Societe Object that emits */ public $emetteur; @@ -147,50 +147,48 @@ class pdf_sponge extends ModelePDFFactures $this->db = $db; $this->name = "sponge"; $this->description = $langs->trans('PDFSpongeDescription'); - $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template // Dimension page $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Display logo - $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION - $this->option_modereg = 1; // Display payment mode - $this->option_condreg = 1; // Display payment terms - $this->option_codeproduitservice = 1; // Display product-service code - $this->option_multilang = 1; // Available in several languages - $this->option_escompte = 1; // Displays if there has been a discount - $this->option_credit_note = 1; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 1; // Displays if there has been a discount + $this->option_credit_note = 1; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; // used for notes ans other stuff + $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff $this->tabTitleHeight = 5; // default height // Use new system for position of columns, view $this->defineColumnField() - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; - $this->situationinvoice=false; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; + $this->situationinvoice = false; } @@ -209,50 +207,59 @@ class pdf_sponge extends ModelePDFFactures public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$mysoc,$db,$hookmanager,$nblines; + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Translations + // Load translation files required by the page $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies")); + } + $nblines = count($object->lines); - $hidetop=0; - if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){ - $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; } // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); + $realpatharray = array(); $this->atleastonephoto = false; - if (! empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE)) + if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE)) { $objphoto = new Product($this->db); - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto->fetch($object->lines[$i]->fk_product); //var_dump($objphoto->ref);exit; - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; - $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; } else { - $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; // default - $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; // alternative + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative } $arephoto = false; foreach ($pdir as $midir) { - if (! $arephoto) + if (!$arephoto) { $dir = $conf->product->dir_output.'/'.$midir; @@ -319,28 +326,28 @@ class pdf_sponge extends ModelePDFFactures if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Set nblines with the new facture lines content after hook $nblines = count($object->lines); $nbpayments = count($object->getListOfPayments()); // Create pdf instance - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance $pdf->SetAutoPageBreak(1, 0); - $heightforinfotot = 50+(4*$nbpayments); // Height reserved to output the info and total part and payment part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS)?12:22); // Height reserved to output the footer (value include bottom margin) + $heightforinfotot = 50 + (4 * $nbpayments); // Height reserved to output the info and total part and payment part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) if (class_exists('TCPDF')) { @@ -350,14 +357,14 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -365,9 +372,9 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfInvoiceTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // Does we have at least one line with discount $this->atleastonediscount foreach ($object->lines as $line) { @@ -410,30 +417,30 @@ class pdf_sponge extends ModelePDFFactures $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = max($pdf->GetY(), $nexY); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; $height_incoterms += 4; } } // Display notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } @@ -570,34 +577,34 @@ class pdf_sponge extends ModelePDFFactures $nexY = $tab_top + $this->tabTitleHeight + 2; // Loop on each lines - $pageposbeforeprintlines=$pdf->getPage(); + $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; - if($this->getColumnStatus('photo')) + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) // If photo too high, we moved completely on new page + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposbefore+1); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; @@ -610,9 +617,9 @@ class pdf_sponge extends ModelePDFFactures if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } } @@ -621,30 +628,29 @@ class pdf_sponge extends ModelePDFFactures { $pdf->startTransaction(); pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposafter+1); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -656,21 +662,21 @@ class pdf_sponge extends ModelePDFFactures { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description or photo were moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // VAT Rate if ($this->getColumnStatus('vat')) @@ -752,56 +758,56 @@ class pdf_sponge extends ModelePDFFactures if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; } else { - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne= $sign * $object->lines[$i]->multicurrency_total_tva; - else $tvaligne= $sign * $object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $sign * $object->lines[$i]->total_tva; } - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) { - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; } if ($localtax2_type && $localtax2ligne != 0) { - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; } - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; $nexY = max($nexY, $posYAfterImage); // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) { @@ -816,11 +822,11 @@ class pdf_sponge extends ModelePDFFactures $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) { + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == $pageposafter) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code); } @@ -831,7 +837,7 @@ class pdf_sponge extends ModelePDFFactures $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -841,24 +847,24 @@ class pdf_sponge extends ModelePDFFactures if ($pagenb == $pageposbeforeprintlines) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Display infos area - $posy=$this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); + $posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); // Display total zone - $posy=$this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + $posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); // Display payment area if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) { - $posy=$this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); + $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); } // Pagefoot @@ -954,7 +960,7 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetFont('', '', $default_font_size - 4); - // Loop on each deposits and credit notes included + // Loop on each discount available (deposits and credit notes and excess of payment included) $sql = "SELECT re.rowid, re.amount_ht, re.multicurrency_amount_ht, re.amount_tva, re.multicurrency_amount_tva, re.amount_ttc, re.multicurrency_amount_ttc,"; $sql .= " re.description, re.fk_facture_source,"; $sql .= " f.type, f.datef"; @@ -971,9 +977,10 @@ class pdf_sponge extends ModelePDFFactures $y += 3; $obj = $this->db->fetch_object($resql); - if ($obj->type == 2) $text = $outputlangs->trans("CreditNote"); - elseif ($obj->type == 3) $text = $outputlangs->trans("Deposit"); - else $text = $outputlangs->trans("UnknownType"); + if ($obj->type == 2) $text = $outputlangs->transnoentities("CreditNote"); + elseif ($obj->type == 3) $text = $outputlangs->transnoentities("Deposit"); + elseif ($obj->type == 0) $text = $outputlangs->transnoentities("ExcessReceived"); + else $text = $outputlangs->transnoentities("UnknownType"); $invoice->fetch($obj->fk_facture_source); @@ -1049,18 +1056,18 @@ class pdf_sponge extends ModelePDFFactures * @param Object $object Object to show * @param int $posy Y * @param Translate $outputlangs Langs object - * @return void + * @return int Pos y */ protected function drawInfoTable(&$pdf, $object, $posy, $outputlangs) { - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); @@ -1128,13 +1135,27 @@ class pdf_sponge extends ModelePDFFactures $lib_mode_reg=$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code)!=('PaymentType'.$object->mode_reglement_code)?$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code):$outputlangs->convToOutputCharset($object->mode_reglement); $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); + // Show online payment link + $useonlinepayment = ((! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)) && !empty($conf->global->PDF_SHOW_LINK_TO_ONLINE_PAYMENT)); + if (($object->mode_reglement_code == 'CB' || $object->mode_reglement_code == 'VAD') && $object->statut != Facture::STATUS_DRAFT && $useonlinepayment) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + global $langs; + + $langs->loadLangs(array('payment', 'paybox')); + $servicename=$langs->transnoentities('Online'); + $paiement_url = getOnlinePaymentUrl('', 'invoice', $object->ref, '', '', ''); + $linktopay = $langs->trans("ToOfferALinkForOnlinePayment", $servicename).' '.$outputlangs->transnoentities("ClickHere").''; + + $pdf->writeHTMLCell(80, 10, '', '', dol_htmlentitiesbr($linktopay), 0, 1); + } + $posy=$pdf->GetY()+2; } // Show payment mode CHQ if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'CHQ') { - // If payment mode not forced or forced to CHQ + // If payment mode unregulated or payment mode forced to CHQ if (! empty($conf->global->FACTURE_CHQ_NUMBER)) { $diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE); @@ -1202,9 +1223,9 @@ class pdf_sponge extends ModelePDFFactures /** * Show total to pay * - * @param PDF $pdf Object PDF + * @param PDF $pdf Object PDF * @param Facture $object Object invoice - * @param int $deja_regle Montant deja regle + * @param int $deja_regle Amount already paid (in the currency of invoice) * @param int $posy Position depart * @param Translate $outputlangs Objet langs * @return int Position pour suite @@ -1226,29 +1247,34 @@ class pdf_sponge extends ModelePDFFactures $col1x = 120; $col2x = 170; if ($this->page_largeur < 210) // To work with US executive format { - $col2x-=20; + $col2x -= 20; } $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); - $useborder=0; + $useborder = 0; $index = 0; - + $outputlangsbis = null; + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + } // overall percentage of advancement $percent = 0; - $i=0; + $i = 0; foreach ($object->lines as $line) { - if(!class_exists('TSubtotal') || !TSubtotal::isModSubtotalLine($line)){ + if (!class_exists('TSubtotal') || !TSubtotal::isModSubtotalLine($line)) { $percent += $line->situation_percent; $i++; } } - if(!empty($i)){ - $avancementGlobal = $percent/$i; + if (!empty($i)) { + $avancementGlobal = $percent / $i; } - else{ + else { $avancementGlobal = 0; } @@ -1257,18 +1283,18 @@ class pdf_sponge extends ModelePDFFactures $total_a_payer = 0; $total_a_payer_ttc = 0; - foreach ($TPreviousIncoice as &$fac){ + foreach ($TPreviousIncoice as &$fac) { $total_a_payer += $fac->total_ht; $total_a_payer_ttc += $fac->total_ttc; } $total_a_payer += $object->total_ht; $total_a_payer_ttc += $object->total_ttc; - if(!empty($avancementGlobal)){ + if (!empty($avancementGlobal)) { $total_a_payer = $total_a_payer * 100 / $avancementGlobal; - $total_a_payer_ttc = $total_a_payer_ttc * 100 / $avancementGlobal; + $total_a_payer_ttc = $total_a_payer_ttc * 100 / $avancementGlobal; } - else{ + else { $total_a_payer = 0; $total_a_payer_ttc = 0; } @@ -1280,7 +1306,7 @@ class pdf_sponge extends ModelePDFFactures $posy = $pdf->GetY(); foreach ($TPreviousIncoice as &$fac) { - if($posy > $this->page_hauteur - 4 ) { + if ($posy > $this->page_hauteur - 4) { $this->_pagefoot($pdf, $object, $outputlangs, 1); $pdf->addPage(); $pdf->setY($this->marge_haute); @@ -1291,13 +1317,13 @@ class pdf_sponge extends ModelePDFFactures $index++; $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $posy); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("PDFSituationTitle", $fac->situation_counter).' '.$outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("PDFSituationTitle", $fac->situation_counter).' '.$outputlangs->transnoentities("TotalHT"), 0, 'L', 1); $pdf->SetXY($col2x, $posy); $facSign = ''; - if ($i>1) { - $facSign = $fac->total_ht>=0?'+':''; + if ($i > 1) { + $facSign = $fac->total_ht >= 0 ? '+' : ''; } $displayAmount = ' '.$facSign.' '.price($fac->total_ht, 0, $outputlangs); @@ -1314,12 +1340,12 @@ class pdf_sponge extends ModelePDFFactures // Display current total $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $posy); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("PDFSituationTitle", $object->situation_counter).' '.$outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("PDFSituationTitle", $object->situation_counter).' '.$outputlangs->transnoentities("TotalHT"), 0, 'L', 1); $pdf->SetXY($col2x, $posy); $facSign = ''; - if ($i>1) { - $facSign = $object->total_ht>=0?'+':''; // management of a particular customer case + if ($i > 1) { + $facSign = $object->total_ht >= 0 ? '+' : ''; // management of a particular customer case } if ($fac->type === facture::TYPE_CREDIT_NOTE) { @@ -1336,22 +1362,22 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetFont('', '', $default_font_size - 1); $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $posy); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("SituationTotalProgress", $avancementGlobal), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("SituationTotalProgress", $avancementGlobal), 0, 'L', 1); $pdf->SetXY($col2x, $posy); - $pdf->MultiCell($largcol2, $tab2_hl, price($total_a_payer*$avancementGlobal/100, 0, $outputlangs), 0, 'R', 1); + $pdf->MultiCell($largcol2, $tab2_hl, price($total_a_payer * $avancementGlobal / 100, 0, $outputlangs), 0, 'R', 1); $pdf->SetFont('', '', $default_font_size - 2); $posy += $tab2_hl; - if($posy > $this->page_hauteur - 4 ) { + if ($posy > $this->page_hauteur - 4) { $pdf->addPage(); $pdf->setY($this->marge_haute); $posy = $pdf->GetY(); } $tab2_top = $posy; - $index=0; + $index = 0; } $tab2_top += 3; @@ -1360,27 +1386,27 @@ class pdf_sponge extends ModelePDFFactures $total_ht = ($conf->multicurrency->enabled && $object->mylticurrency_tx != 1 ? $object->multicurrency_total_ht : $object->total_ht); // Total remise - $total_line_remise=0; - foreach($object->lines as $i => $line) { - $total_line_remise+= pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, 2); // TODO: add this methode to core/lib/pdf.lib + $total_line_remise = 0; + foreach ($object->lines as $i => $line) { + $total_line_remise += pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, 2); // TODO: add this methode to core/lib/pdf.lib // Gestion remise sous forme de ligne négative - if($line->total_ht < 0) $total_line_remise += -$line->total_ht; + if ($line->total_ht < 0) $total_line_remise += -$line->total_ht; } - if($total_line_remise > 0) { - if (! empty($conf->global->MAIN_SHOW_AMOUNT_DISCOUNT)) { + if ($total_line_remise > 0) { + if (!empty($conf->global->MAIN_SHOW_AMOUNT_DISCOUNT)) { $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + $tab2_hl); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalDiscount"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalDiscount").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalDiscount") : ''), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl); $pdf->MultiCell($largcol2, $tab2_hl, price($total_line_remise, 0, $outputlangs), 0, 'R', 1); $index++; } // Show total NET before discount - if (! empty($conf->global->MAIN_SHOW_AMOUNT_BEFORE_DISCOUNT)) { + if (!empty($conf->global->MAIN_SHOW_AMOUNT_BEFORE_DISCOUNT)) { $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalHTBeforeDiscount"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHTBeforeDiscount").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalHTBeforeDiscount") : ''), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + 0); $pdf->MultiCell($largcol2, $tab2_hl, price($total_line_remise + $total_ht, 0, $outputlangs), 0, 'R', 1); @@ -1391,21 +1417,22 @@ class pdf_sponge extends ModelePDFFactures // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalHT") : ''), 0, 'L', 1); + $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($largcol2, $tab2_hl, price($sign * ($total_ht + (! empty($object->remise)?$object->remise:0)), 0, $outputlangs), 0, 'R', 1); + $pdf->MultiCell($largcol2, $tab2_hl, price($sign * ($total_ht + (!empty($object->remise) ? $object->remise : 0)), 0, $outputlangs), 0, 'R', 1); // Show VAT by rates and total $pdf->SetFillColor(248, 248, 248); $total_ttc = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ttc : $object->total_ttc; - $this->atleastoneratenotnull=0; + $this->atleastoneratenotnull = 0; if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { - $tvaisnull=((! empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) + $tvaisnull = ((!empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) { // Nothing to do } @@ -1416,29 +1443,30 @@ class pdf_sponge extends ModelePDFFactures //Local tax 1 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1449,28 +1477,29 @@ class pdf_sponge extends ModelePDFFactures //Local tax 2 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1483,12 +1512,12 @@ class pdf_sponge extends ModelePDFFactures // Situations totals migth be wrong on huge amounts if ($object->situation_cycle_ref && $object->situation_counter > 1) { $sum_pdf_tva = 0; - foreach($this->tva as $tvakey => $tvaval){ - $sum_pdf_tva+=$tvaval; // sum VAT amounts to compare to object + foreach ($this->tva as $tvakey => $tvaval) { + $sum_pdf_tva += $tvaval; // sum VAT amounts to compare to object } - if($sum_pdf_tva!=$object->total_tva) { // apply coef to recover the VAT object amount (the good one) - if(!empty($sum_pdf_tva)) + if ($sum_pdf_tva != $object->total_tva) { // apply coef to recover the VAT object amount (the good one) + if (!empty($sum_pdf_tva)) { $coef_fix_tva = $object->total_tva / $sum_pdf_tva; } @@ -1497,13 +1526,13 @@ class pdf_sponge extends ModelePDFFactures } - foreach($this->tva as $tvakey => $tvaval) { - $this->tva[$tvakey]=$tvaval * $coef_fix_tva; + foreach ($this->tva as $tvakey => $tvaval) { + $this->tva[$tvakey] = $tvaval * $coef_fix_tva; } } } - foreach($this->tva as $tvakey => $tvaval) + foreach ($this->tva as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1518,7 +1547,8 @@ class pdf_sponge extends ModelePDFFactures $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalVAT", $mysoc->country_code) : ''); + $totalvat .= ' '; $totalvat .= vatrate($tvakey, 1).$tvacompl; $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); @@ -1530,11 +1560,11 @@ class pdf_sponge extends ModelePDFFactures //Local tax 1 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1543,16 +1573,17 @@ class pdf_sponge extends ModelePDFFactures $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); } @@ -1562,11 +1593,11 @@ class pdf_sponge extends ModelePDFFactures //Local tax 2 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { // retrieve global local tax if ($tvakey != 0) // On affiche pas taux 0 @@ -1576,16 +1607,17 @@ class pdf_sponge extends ModelePDFFactures $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1599,7 +1631,7 @@ class pdf_sponge extends ModelePDFFactures { $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RevenueStamp"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RevenueStamp").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("RevenueStamp", $mysoc->country_code) : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($sign * $object->revenuestamp), $useborder, 'R', 1); @@ -1610,7 +1642,7 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalTTC") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($sign * $total_ttc, 0, $outputlangs), $useborder, 'R', 1); @@ -1631,36 +1663,36 @@ class pdf_sponge extends ModelePDFFactures // Retained warranty - if( !empty($object->situation_final) && ( $object->type == Facture::TYPE_SITUATION && (!empty($object->retained_warranty) ) ) ) + if (!empty($object->situation_final) && ($object->type == Facture::TYPE_SITUATION && (!empty($object->retained_warranty)))) { $displayWarranty = false; // Check if this situation invoice is 100% for real - if(!empty($object->situation_final)){ + if (!empty($object->situation_final)) { $displayWarranty = true; } - elseif(!empty($object->lines) && $object->status == Facture::STATUS_DRAFT ){ + elseif (!empty($object->lines) && $object->status == Facture::STATUS_DRAFT) { // $object->situation_final need validation to be done so this test is need for draft $displayWarranty = true; - foreach($object->lines as $i => $line){ - if($line->product_type < 2 && $line->situation_percent < 100){ + foreach ($object->lines as $i => $line) { + if ($line->product_type < 2 && $line->situation_percent < 100) { $displayWarranty = false; break; } } } - if($displayWarranty){ + if ($displayWarranty) { $pdf->SetTextColor(40, 40, 40); $pdf->SetFillColor(255, 255, 255); $retainedWarranty = $total_a_payer_ttc * $object->retained_warranty / 100; - $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty ; + $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty; // Billed - retained warranty $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("PDFEVOLToPayOn", dol_print_date($object->date_lim_reglement, 'day')), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("PDFEVOLToPayOn", dol_print_date($object->date_lim_reglement, 'day')), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($billedWithRetainedWarranty), $useborder, 'R', 1); @@ -1669,10 +1701,10 @@ class pdf_sponge extends ModelePDFFactures $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $retainedWarrantyToPayOn = $outputlangs->transnoentities("PDFEVOLRetainedWarranty") . ' ('.$object->retained_warranty.'%)'; - $retainedWarrantyToPayOn.= !empty($object->retained_warranty_date_limit)?' '.$outputlangs->transnoentities("PDFEVOLtoPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')):''; + $retainedWarrantyToPayOn = $outputlangs->transnoentities("PDFEVOLRetainedWarranty").' ('.$object->retained_warranty.'%)'; + $retainedWarrantyToPayOn .= !empty($object->retained_warranty_date_limit) ? ' '.$outputlangs->transnoentities("PDFEVOLtoPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : ''; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $retainedWarrantyToPayOn, $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $retainedWarrantyToPayOn, $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($retainedWarranty), $useborder, 'R', 1); } @@ -1682,27 +1714,29 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetTextColor(0, 0, 0); - $creditnoteamount=$object->getSumCreditNotesUsed(($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? 1 : 0); - $depositsamount=$object->getSumDepositsUsed(($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? 1 : 0); + $creditnoteamount = $object->getSumCreditNotesUsed(($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? 1 : 0); // Warning, this also include excess received + $depositsamount = $object->getSumDepositsUsed(($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? 1 : 0); $resteapayer = price2num($total_ttc - $deja_regle - $creditnoteamount - $depositsamount, 'MT'); - if ($object->paye) $resteapayer=0; + if (!empty($object->paye)) $resteapayer = 0; if (($deja_regle > 0 || $creditnoteamount > 0 || $depositsamount > 0) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) { // Already paid + Deposits $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("Paid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("Paid").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("Paid") : ''), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle + $depositsamount, 0, $outputlangs), 0, 'R', 0); // Credit note if ($creditnoteamount) { + $labeltouse = ($outputlangs->transnoentities("CreditNotesOrExcessReceived") != "CreditNotesOrExcessReceived") ? $outputlangs->transnoentities("CreditNotesOrExcessReceived") : $outputlangs->transnoentities("CreditNotes"); + $labeltouse .= (is_object($outputlangsbis) ? ' / '.($outputlangsbis->transnoentities("CreditNotesOrExcessReceived") != "CreditNotesOrExcessReceived") ? $outputlangsbis->transnoentities("CreditNotesOrExcessReceived") : $outputlangsbis->transnoentities("CreditNotes") : ''); $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("CreditNotes"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $labeltouse, 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($creditnoteamount, 0, $outputlangs), 0, 'R', 0); } @@ -1714,7 +1748,7 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("EscompteOfferedShort"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("EscompteOfferedShort").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("EscompteOfferedShort") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_ttc - $deja_regle - $creditnoteamount - $depositsamount, 0, $outputlangs), $useborder, 'R', 1); @@ -1725,7 +1759,7 @@ class pdf_sponge extends ModelePDFFactures $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("RemainderToPay") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); @@ -1783,24 +1817,26 @@ class pdf_sponge extends ModelePDFFactures if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - if (empty($hidetop)){ - $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -1818,7 +1854,7 @@ class pdf_sponge extends ModelePDFFactures { global $conf, $langs; - // Translations + // Load traductions files required by page $outputlangs->loadLangs(array("main", "bills", "propal", "companies")); $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1836,8 +1872,8 @@ class pdf_sponge extends ModelePDFFactures $w = 110; - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-$w; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); @@ -1847,7 +1883,7 @@ class pdf_sponge extends ModelePDFFactures if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; @@ -1857,8 +1893,8 @@ class pdf_sponge extends ModelePDFFactures } if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { diff --git a/htdocs/core/modules/facture/modules_facture.php b/htdocs/core/modules/facture/modules_facture.php index ba65eeeca9c..56379a0c492 100644 --- a/htdocs/core/modules/facture/modules_facture.php +++ b/htdocs/core/modules/facture/modules_facture.php @@ -29,7 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commondocgenerator.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Required because used in classes that inherit +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Required because used in classes that inherit /** @@ -40,7 +40,11 @@ abstract class ModelePDFFactures extends CommonDocGenerator /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; + + public $atleastonediscount = 0; + public $atleastoneratenotnull = 0; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** @@ -55,11 +59,11 @@ abstract class ModelePDFFactures extends CommonDocGenerator // phpcs:enable global $conf; - $type='invoice'; - $liste=array(); + $type = 'invoice'; + $liste = array(); include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $liste=getListOfModels($db, $type, $maxfilenamelength); + $liste = getListOfModels($db, $type, $maxfilenamelength); return $liste; } @@ -73,7 +77,7 @@ abstract class ModeleNumRefFactures /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * Return if a module can be used or not diff --git a/htdocs/core/modules/import/import_csv.modules.php b/htdocs/core/modules/import/import_csv.modules.php index d6c43edd5c3..93d68691a11 100644 --- a/htdocs/core/modules/import/import_csv.modules.php +++ b/htdocs/core/modules/import/import_csv.modules.php @@ -123,7 +123,7 @@ class ImportCsv extends ModeleImports * Output header of an example file for this format * * @param Translate $outputlangs Output language - * @return string + * @return string Empty string */ public function write_header_example($outputlangs) { @@ -137,7 +137,7 @@ class ImportCsv extends ModeleImports * * @param Translate $outputlangs Output language * @param array $headerlinefields Array of fields name - * @return string$limittoachartaccount + * @return string String output */ public function write_title_example($outputlangs, $headerlinefields) { @@ -152,7 +152,7 @@ class ImportCsv extends ModeleImports * * @param Translate $outputlangs Output language * @param array $contentlinevalues Array of lines - * @return string + * @return string String output */ public function write_record_example($outputlangs, $contentlinevalues) { @@ -166,7 +166,7 @@ class ImportCsv extends ModeleImports * Output footer of an example file for this format * * @param Translate $outputlangs Output language - * @return string + * @return string Empty string */ public function write_footer_example($outputlangs) { @@ -175,7 +175,6 @@ class ImportCsv extends ModeleImports } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Open input file diff --git a/htdocs/core/modules/import/import_xlsx.modules.php b/htdocs/core/modules/import/import_xlsx.modules.php index 03b3f941a1d..09628739494 100644 --- a/htdocs/core/modules/import/import_xlsx.modules.php +++ b/htdocs/core/modules/import/import_xlsx.modules.php @@ -130,7 +130,7 @@ class ImportXlsx extends ModeleImports * Output header of an example file for this format * * @param Translate $outputlangs Output language - * @return string + * @return string Empty string */ public function write_header_example($outputlangs) { @@ -164,7 +164,7 @@ class ImportXlsx extends ModeleImports * * @param Translate $outputlangs Output language * @param array $headerlinefields Array of fields name - * @return string + * @return string String output */ public function write_title_example($outputlangs, $headerlinefields) { @@ -190,7 +190,7 @@ class ImportXlsx extends ModeleImports * * @param Translate $outputlangs Output language * @param array $contentlinevalues Array of lines - * @return string + * @return string Empty string */ public function write_record_example($outputlangs, $contentlinevalues) { @@ -210,7 +210,7 @@ class ImportXlsx extends ModeleImports * Output footer of an example file for this format * * @param Translate $outputlangs Output language - * @return string + * @return string String output */ public function write_footer_example($outputlangs) { @@ -258,7 +258,7 @@ class ImportXlsx extends ModeleImports * Return nb of records. File must be closed. * * @param string $file Path of filename - * @return int <0 if KO, >=0 if OK + * @return int <0 if KO, >=0 if OK */ public function import_get_nb_of_lines($file) { diff --git a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php index 88a51c7c94f..9c80c6a9020 100644 --- a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php +++ b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php @@ -118,7 +118,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder */ public function __construct($db) { - global $conf,$langs,$mysoc; + global $conf, $langs, $mysoc; // Translations $langs->loadLangs(array("main", "bills", "sendings", "companies")); @@ -129,47 +129,45 @@ class pdf_typhon extends ModelePDFDeliveryOrder // Page size for A4 format $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Display logo FAC_PDF_LOGO - $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION - $this->option_codeproduitservice = 1; // Display product-service code - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Display logo FAC_PDF_LOGO + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_codeproduitservice = 1; // Display product-service code // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; - $this->posxcomm=112; + $this->posxdesc = $this->marge_gauche + 1; + $this->posxcomm = 112; //$this->posxtva=112; //$this->posxup=126; - $this->posxqty=165; - $this->posxremainingqty=185; + $this->posxqty = 165; + $this->posxremainingqty = 185; //$this->posxdiscount=162; //$this->postotalht=174; if ($this->page_largeur < 210) // To work with US executive format { - $this->posxcomm-=20; + $this->posxcomm -= 20; //$this->posxtva-=20; //$this->posxup-=20; - $this->posxqty-=20; + $this->posxqty -= 20; //$this->posxdiscount-=20; //$this->postotalht-=20; } - $this->tva=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } @@ -188,11 +186,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$mysoc,$hookmanager; + global $user, $langs, $conf, $mysoc, $hookmanager; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load translation files required by the page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "sendings", "deliveries")); @@ -205,20 +203,20 @@ class pdf_typhon extends ModelePDFDeliveryOrder if ($object->specimen) { $dir = $conf->expedition->dir_output."/receipt"; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->expedition->dir_output."/receipt/" . $objectref; - $file = $dir . "/" . $objectref . ".pdf"; + $dir = $conf->expedition->dir_output."/receipt/".$objectref; + $file = $dir."/".$objectref.".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -226,25 +224,25 @@ class pdf_typhon extends ModelePDFDeliveryOrder if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $nblines = count($object->lines); // Create pdf instance - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $heightforinfotot = 30; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $heightforinfotot = 30; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -254,14 +252,14 @@ class pdf_typhon extends ModelePDFDeliveryOrder } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } // We get the shipment that is the origin of delivery receipt - $expedition=new Expedition($this->db); + $expedition = new Expedition($this->db); $result = $expedition->fetch($object->origin_id); // Now we get the order that is origin of shipment $commande = new Commande($this->db); @@ -269,12 +267,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder { $commande->fetch($expedition->origin_id); } - $object->commande=$commande; // We set order of shipment onto delivery. + $object->commande = $commande; // We set order of shipment onto delivery. $object->commande->loadExpeditions(); $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -282,9 +280,9 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("DeliveryOrder")); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right /* // Positionne $this->atleastonediscount si on a au moins une remise @@ -308,15 +306,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); $tab_top = 90; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10); + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10); $tab_height = 130; $tab_height_newpage = 150; @@ -330,39 +328,39 @@ class pdf_typhon extends ModelePDFDeliveryOrder $tab_top = 88; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; $height_incoterms += 4; } } // Affiche notes - if (! empty($object->note_public)) + if (!empty($object->note_public)) { $tab_top = 88 + $height_incoterms; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1); $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); $tab_height = $tab_height - $height_note; - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } else { - $height_note=0; + $height_note = 0; } $iniY = $tab_top + 11; @@ -370,46 +368,45 @@ class pdf_typhon extends ModelePDFDeliveryOrder $nexY = $tab_top + 11; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); // Description of product line - $curX = $this->posxdesc-1; + $curX = $this->posxdesc - 1; - $showpricebeforepagebreak=1; + $showpricebeforepagebreak = 1; $pdf->startTransaction(); - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm-$curX, 3, $curX, $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 3, $curX, $curY, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm-$curX, 4, $curX, $curY, $hideref, $hidedesc); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 4, $curX, $curY, $hideref, $hidedesc); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -423,17 +420,17 @@ class pdf_typhon extends ModelePDFDeliveryOrder } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut /* // TVA @@ -452,7 +449,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder // Remaining to ship $pdf->SetXY($this->posxremainingqty, $curY); $qtyRemaining = $object->lines[$i]->qty_asked - $object->commande->expeditions[$object->lines[$i]->fk_origin_line]; - $pdf->MultiCell($this->page_largeur-$this->marge_droite - $this->posxremainingqty, 3, $qtyRemaining, 0, 'R'); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxremainingqty, 3, $qtyRemaining, 0, 'R'); /* // Remise sur ligne $pdf->SetXY($this->posxdiscount, $curY); @@ -474,16 +471,16 @@ class pdf_typhon extends ModelePDFDeliveryOrder */ // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -500,10 +497,10 @@ class pdf_typhon extends ModelePDFDeliveryOrder $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -516,7 +513,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -526,12 +523,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder if ($pagenb == 1) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Affiche zone infos @@ -608,36 +605,36 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->Output($file, 'F'); // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } - $this->error=$langs->transnoentities("ErrorConstantNotDefined", "LIVRAISON_OUTPUTDIR"); + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "LIVRAISON_OUTPUTDIR"); return 0; } @@ -655,19 +652,19 @@ class pdf_typhon extends ModelePDFDeliveryOrder protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf,$mysoc; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size); $pdf->SetXY($this->marge_gauche, $posy); - $larg_sign = ($this->page_largeur-$this->marge_gauche-$this->marge_droite)/3; + $larg_sign = ($this->page_largeur - $this->marge_gauche - $this->marge_droite) / 3; $pdf->Rect($this->marge_gauche, $posy + 1, $larg_sign, 25); $pdf->SetXY($this->marge_gauche + 2, $posy + 2); $pdf->MultiCell($larg_sign, 2, $outputlangs->trans("For").' '.$outputlangs->convToOutputCharset($mysoc->name).":", '', 'L'); - $pdf->Rect(2*$larg_sign+$this->marge_gauche, $posy + 1, $larg_sign, 25); - $pdf->SetXY(2*$larg_sign+$this->marge_gauche + 2, $posy + 2); + $pdf->Rect(2 * $larg_sign + $this->marge_gauche, $posy + 1, $larg_sign, 25); + $pdf->SetXY(2 * $larg_sign + $this->marge_gauche + 2, $posy + 2); $pdf->MultiCell($larg_sign, 2, $outputlangs->trans("ForCustomer").':', '', 'L'); } @@ -686,11 +683,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder */ protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0) { - global $conf,$mysoc; + global $conf, $mysoc; // Force to disable hidetop and hidebottom - $hidebottom=0; - if ($hidetop) $hidetop=-1; + $hidebottom = 0; + if ($hidetop) $hidetop = -1; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -699,11 +696,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->SetFont('', '', $default_font_size - 2); // Output Rec - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top+10, $this->page_largeur-$this->marge_droite, $tab_top+10); + $pdf->line($this->marge_gauche, $tab_top + 10, $this->page_largeur - $this->marge_droite, $tab_top + 10); } $pdf->SetDrawColor(128, 128, 128); @@ -711,29 +708,29 @@ class pdf_typhon extends ModelePDFDeliveryOrder if (empty($hidetop)) { - $pdf->SetXY($this->posxdesc-1, $tab_top+1); + $pdf->SetXY($this->posxdesc - 1, $tab_top + 1); $pdf->MultiCell($this->posxcomm - $this->posxdesc, 2, $outputlangs->transnoentities("Designation"), '', 'L'); } // Modif SEB pour avoir une col en plus pour les commentaires clients $pdf->line($this->posxcomm, $tab_top, $this->posxcomm, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxcomm, $tab_top+1); + $pdf->SetXY($this->posxcomm, $tab_top + 1); $pdf->MultiCell($this->posxqty - $this->posxcomm, 2, $outputlangs->transnoentities("Comments"), '', 'L'); } // Qty $pdf->line($this->posxqty, $tab_top, $this->posxqty, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxqty, $tab_top+1); + $pdf->SetXY($this->posxqty, $tab_top + 1); $pdf->MultiCell($this->posxremainingqty - $this->posxqty, 2, $outputlangs->transnoentities("QtyShippedShort"), '', 'R'); } // Remain to ship $pdf->line($this->posxremainingqty, $tab_top, $this->posxremainingqty, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxremainingqty, $tab_top+1); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShipShort"), '', 'R'); + $pdf->SetXY($this->posxremainingqty, $tab_top + 1); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShipShort"), '', 'R'); } } @@ -749,14 +746,14 @@ class pdf_typhon extends ModelePDFDeliveryOrder */ protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs) { - global $conf,$langs,$hookmanager; + global $conf, $langs, $hookmanager; $default_font_size = pdf_getPDFFontSize($outputlangs); pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark - if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) ) + if ($object->statut == 0 && (!empty($conf->global->COMMANDE_DRAFT_WATERMARK))) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->COMMANDE_DRAFT_WATERMARK); } @@ -764,19 +761,19 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -795,12 +792,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->SetFont('', '', $default_font_size + 2); - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); if ($object->date_valid) { - $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Date")." : " . dol_print_date($object->date_delivery, "%d %b %Y", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Date")." : ".dol_print_date($object->date_delivery, "%d %b %Y", false, $outputlangs, true), '', 'R'); } else { @@ -811,15 +808,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder if ($object->thirdparty->code_client) { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); } $pdf->SetTextColor(0, 0, 60); - $posy+=2; + $posy += 2; // Show list of linked objects $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size); @@ -830,15 +827,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender - $posy=42; - $posx=$this->marge_gauche; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80; - $hautcadre=40; + $posy = 42; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + $hautcadre = 40; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom").":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); @@ -846,32 +843,32 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->SetTextColor(0, 0, 60); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); // Client destinataire - $posy=42; - $posx=102; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $posy = 42; + $posx = 102; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(80, 5, $outputlangs->transnoentities("DeliveryAddress").":", 0, 'L'); // If SHIPPING contact defined on order, we use it - $usecontact=false; - $arrayidcontact=$object->commande->getIdContact('external', 'SHIPPING'); + $usecontact = false; + $arrayidcontact = $object->commande->getIdContact('external', 'SHIPPING'); if (count($arrayidcontact) > 0) { - $usecontact=true; - $result=$object->fetch_contact($arrayidcontact[0]); + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); } //Recipient name @@ -882,26 +879,26 @@ class pdf_typhon extends ModelePDFDeliveryOrder $thirdparty = $object->thirdparty; } - $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs); + $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact?$object->contact:''), $usecontact, 'target', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object); // Show recipient - $widthrecbox=100; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=42; - $posx=$this->page_largeur-$this->marge_droite-$widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = 42; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); //$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":",0,'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); @@ -909,7 +906,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } @@ -929,7 +926,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) { global $conf; - $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; return pdf_pagefoot($pdf, $outputlangs, 'DELIVERY_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); } } diff --git a/htdocs/core/modules/mailings/contacts1.modules.php b/htdocs/core/modules/mailings/contacts1.modules.php index b3687e4f603..8e7b6bff77e 100644 --- a/htdocs/core/modules/mailings/contacts1.modules.php +++ b/htdocs/core/modules/mailings/contacts1.modules.php @@ -105,6 +105,8 @@ class mailing_contacts1 extends MailingTargets $sql.= " WHERE c.entity IN (".getEntity('socpeople').")"; $sql.= " AND c.email != ''"; // Note that null != '' is false $sql.= " AND c.no_email = 0"; + $sql .= " AND (SELECT count(*) FROM ". MAIN_DB_PREFIX . "mailing_unsubscribe WHERE email = c.email) = 0"; + // exclude unsubscribed users $sql.= " AND c.statut = 1"; // The request must return a field called "nb" to be understandable by parent::getNbOfRecipients @@ -384,6 +386,8 @@ class mailing_contacts1 extends MailingTargets $sql.= " WHERE sp.entity IN (".getEntity('socpeople').")"; $sql.= " AND sp.email <> ''"; $sql.= " AND sp.no_email = 0"; + $sql .= " AND (SELECT count(*) FROM ". MAIN_DB_PREFIX . "mailing_unsubscribe WHERE email = sp.email) = 0"; + // Exclude unsubscribed email adresses $sql.= " AND sp.statut = 1"; $sql.= " AND sp.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE fk_mailing=".$mailing_id.")"; // Filter on category diff --git a/htdocs/core/modules/modAgenda.class.php b/htdocs/core/modules/modAgenda.class.php index 13e47abbc74..2184500db8c 100644 --- a/htdocs/core/modules/modAgenda.class.php +++ b/htdocs/core/modules/modAgenda.class.php @@ -30,7 +30,7 @@ * \ingroup agenda * \brief File of class to describe and enable/disable module Agenda */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** * Class to describe and enable/disable module Agenda @@ -59,7 +59,7 @@ class modAgenda extends DolibarrModules $this->version = 'dolibarr'; // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); - $this->picto='action'; + $this->picto = 'action'; // Data directories to create when module is enabled $this->dirs = array("/agenda/temp"); @@ -68,12 +68,12 @@ class modAgenda extends DolibarrModules $this->config_page_url = array("agenda_other.php"); // Dependencies - $this->hidden = false; // A condition to hide module - $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled - $this->requiredby = array(); // List of module ids to disable if this one is disabled - $this->conflictwith = array(); // List of module class names as string this module is in conflict with + $this->hidden = false; // A condition to hide module + $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled + $this->requiredby = array(); // List of module ids to disable if this one is disabled + $this->conflictwith = array(); // List of module class names as string this module is in conflict with $this->langfiles = array("companies"); - $this->phpmin = array(5,4); // Minimum version of PHP required by module + $this->phpmin = array(5, 4); // Minimum version of PHP required by module // Module parts $this->module_parts = array(); @@ -86,14 +86,14 @@ class modAgenda extends DolibarrModules // ); $this->const = array(); //$this->const[] = array('AGENDA_DEFAULT_FILTER_TYPE', 'chaine', 'AC_NON_AUTO', 'Default filter for type of event on agenda', 0, 'current'); - $sqlreadactions="SELECT code, label, description FROM ".MAIN_DB_PREFIX."c_action_trigger ORDER by rang"; + $sqlreadactions = "SELECT code, label, description FROM ".MAIN_DB_PREFIX."c_action_trigger ORDER by rang"; $resql = $this->db->query($sqlreadactions); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { //if (preg_match('/_CREATE$/',$obj->code) && (! in_array($obj->code, array('COMPANY_CREATE','PRODUCT_CREATE','TASK_CREATE')))) continue; // We don't track such events (*_CREATE) by default, we prefer validation (except thirdparty/product/task creation because there is no validation). - if (preg_match('/^TASK_/', $obj->code)) continue; // We don't track such events by default. + if (preg_match('/^TASK_/', $obj->code)) continue; // We don't track such events by default. //if (preg_match('/^_MODIFY/',$obj->code)) continue; // We don't track such events by default. $this->const[] = array('MAIN_AGENDA_ACTIONAUTO_'.$obj->code, "chaine", "1", '', 0, 'current'); } @@ -109,11 +109,11 @@ class modAgenda extends DolibarrModules // Boxes //------ - $this->boxes = array(0=>array('file'=>'box_actions.php','enabledbydefaulton'=>'Home')); + $this->boxes = array(0=>array('file'=>'box_actions.php', 'enabledbydefaulton'=>'Home')); // Cronjobs //------------ - $datestart=dol_now(); + $datestart = dol_now(); $this->cronjobs = array( 0=>array('label'=>'SendEmailsReminders', 'jobtype'=>'method', 'class'=>'comm/action/class/actioncomm.class.php', 'objectname'=>'ActionComm', 'method'=>'sendEmailsReminder', 'parameters'=>'', 'comment'=>'SendEMailsReminder', 'frequency'=>10, 'unitfrequency'=>60, 'priority'=>10, 'status'=>1, 'test'=>'$conf->agenda->enabled', 'datestart'=>$datestart), ); @@ -122,7 +122,7 @@ class modAgenda extends DolibarrModules //------------ $this->rights = array(); $this->rights_class = 'agenda'; - $r=0; + $r = 0; // $this->rights[$r][0] Id permission (unique tous modules confondus) // $this->rights[$r][1] Libelle par defaut si traduction de cle "PermissionXXX" non trouvee (XXX = Id permission) @@ -187,8 +187,8 @@ class modAgenda extends DolibarrModules $this->rights[$r][4] = 'export'; // Main menu entries - $this->menu = array(); // List of menus to add - $r=0; + $this->menu = array(); // List of menus to add + $r = 0; // Add here entries to declare new menus // Example to declare the Top Menu entry: @@ -204,7 +204,7 @@ class modAgenda extends DolibarrModules // 'target'=>'', // 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both // $r++; - $this->menu[$r]=array( + $this->menu[$r] = array( 'fk_menu'=>0, 'type'=>'top', 'titre'=>'TMenuAgenda', @@ -219,207 +219,255 @@ class modAgenda extends DolibarrModules ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=0', - 'type'=>'left', - 'titre'=>'Actions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?mainmenu=agenda&leftmenu=agenda', - 'langs'=>'agenda', - 'position'=>100, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=0', + 'type'=>'left', + 'titre'=>'Actions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?mainmenu=agenda&leftmenu=agenda', + 'langs'=>'agenda', + 'position'=>100, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2, + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=1', - 'type'=>'left', - 'titre'=>'NewAction', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/card.php?mainmenu=agenda&leftmenu=agenda&action=create', - 'langs'=>'commercial', - 'position'=>101, - 'perms'=>'($user->rights->agenda->myactions->create||$user->rights->agenda->allactions->create)', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=1', + 'type'=>'left', + 'titre'=>'NewAction', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/card.php?mainmenu=agenda&leftmenu=agenda&action=create', + 'langs'=>'commercial', + 'position'=>101, + 'perms'=>'($user->rights->agenda->myactions->create||$user->rights->agenda->allactions->create)', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; // Calendar - $this->menu[$r]=array('fk_menu'=>'r=1', - 'type'=>'left', - 'titre'=>'Calendar', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda', - 'langs'=>'agenda', - 'position'=>140, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=1', + 'type'=>'left', + 'titre'=>'Calendar', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda', + 'langs'=>'agenda', + 'position'=>140, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=3', - 'type'=>'left', - 'titre'=>'MenuToDoMyActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=todo&filter=mine', - 'langs'=>'agenda', - 'position'=>141, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=3', + 'type'=>'left', + 'titre'=>'MenuToDoMyActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=todo&filter=mine', + 'langs'=>'agenda', + 'position'=>141, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=3', - 'type'=>'left', - 'titre'=>'MenuDoneMyActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=done&filter=mine', - 'langs'=>'agenda', - 'position'=>142, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=3', + 'type'=>'left', + 'titre'=>'MenuDoneMyActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=done&filter=mine', + 'langs'=>'agenda', + 'position'=>142, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=3', - 'type'=>'left', - 'titre'=>'MenuToDoActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=todo&filtert=-1', - 'langs'=>'agenda', - 'position'=>143, - 'perms'=>'$user->rights->agenda->allactions->read', - 'enabled'=>'$user->rights->agenda->allactions->read', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=3', + 'type'=>'left', + 'titre'=>'MenuToDoActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=todo&filtert=-1', + 'langs'=>'agenda', + 'position'=>143, + 'perms'=>'$user->rights->agenda->allactions->read', + 'enabled'=>'$user->rights->agenda->allactions->read', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=3', - 'type'=>'left', - 'titre'=>'MenuDoneActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=done&filtert=-1', - 'langs'=>'agenda', - 'position'=>144, - 'perms'=>'$user->rights->agenda->allactions->read', - 'enabled'=>'$user->rights->agenda->allactions->read', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=3', + 'type'=>'left', + 'titre'=>'MenuDoneActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/index.php?action=default&mainmenu=agenda&leftmenu=agenda&status=done&filtert=-1', + 'langs'=>'agenda', + 'position'=>144, + 'perms'=>'$user->rights->agenda->allactions->read', + 'enabled'=>'$user->rights->agenda->allactions->read', + 'target'=>'', + 'user'=>2 + ); // List $r++; - $this->menu[$r]=array('fk_menu'=>'r=1', - 'type'=>'left', - 'titre'=>'List', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda', - 'langs'=>'agenda', - 'position'=>110, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=1', + 'type'=>'left', + 'titre'=>'List', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda', + 'langs'=>'agenda', + 'position'=>110, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=8', - 'type'=>'left', - 'titre'=>'MenuToDoMyActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=todo&filter=mine', - 'langs'=>'agenda', - 'position'=>111, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=8', + 'type'=>'left', + 'titre'=>'MenuToDoMyActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=todo&filter=mine', + 'langs'=>'agenda', + 'position'=>111, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=8', - 'type'=>'left', - 'titre'=>'MenuDoneMyActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=done&filter=mine', - 'langs'=>'agenda', - 'position'=>112, - 'perms'=>'$user->rights->agenda->myactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=8', + 'type'=>'left', + 'titre'=>'MenuDoneMyActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=done&filter=mine', + 'langs'=>'agenda', + 'position'=>112, + 'perms'=>'$user->rights->agenda->myactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=8', - 'type'=>'left', - 'titre'=>'MenuToDoActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=todo&filtert=-1', - 'langs'=>'agenda', - 'position'=>113, - 'perms'=>'$user->rights->agenda->allactions->read', - 'enabled'=>'$user->rights->agenda->allactions->read', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=8', + 'type'=>'left', + 'titre'=>'MenuToDoActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=todo&filtert=-1', + 'langs'=>'agenda', + 'position'=>113, + 'perms'=>'$user->rights->agenda->allactions->read', + 'enabled'=>'$user->rights->agenda->allactions->read', + 'target'=>'', + 'user'=>2 + ); $r++; - $this->menu[$r]=array('fk_menu'=>'r=8', - 'type'=>'left', - 'titre'=>'MenuDoneActions', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=done&filtert=-1', - 'langs'=>'agenda', - 'position'=>114, - 'perms'=>'$user->rights->agenda->allactions->read', - 'enabled'=>'$user->rights->agenda->allactions->read', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=8', + 'type'=>'left', + 'titre'=>'MenuDoneActions', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/list.php?mainmenu=agenda&leftmenu=agenda&status=done&filtert=-1', + 'langs'=>'agenda', + 'position'=>114, + 'perms'=>'$user->rights->agenda->allactions->read', + 'enabled'=>'$user->rights->agenda->allactions->read', + 'target'=>'', + 'user'=>2 + ); $r++; // Reports - $this->menu[$r]=array('fk_menu'=>'r=1', - 'type'=>'left', - 'titre'=>'Reportings', - 'mainmenu'=>'agenda', - 'url'=>'/comm/action/rapport/index.php?mainmenu=agenda&leftmenu=agenda', - 'langs'=>'agenda', - 'position'=>160, - 'perms'=>'$user->rights->agenda->allactions->read', - 'enabled'=>'$conf->agenda->enabled', - 'target'=>'', - 'user'=>2); + $this->menu[$r] = array( + 'fk_menu'=>'r=1', + 'type'=>'left', + 'titre'=>'Reportings', + 'mainmenu'=>'agenda', + 'url'=>'/comm/action/rapport/index.php?mainmenu=agenda&leftmenu=agenda', + 'langs'=>'agenda', + 'position'=>160, + 'perms'=>'$user->rights->agenda->allactions->read', + 'enabled'=>'$conf->agenda->enabled', + 'target'=>'', + 'user'=>2 + ); + $r++; + // Categories + $this->menu[$r] = array( + 'fk_menu' => 'r=1', + 'type' => 'left', + 'titre' => 'Categories', + 'mainmenu' => 'agenda', + 'url'=>'/categories/index.php?mainmenu=agenda&leftmenu=agenda&type=10', + 'langs' => 'agenda', + 'position' => 170, + 'perms' => '$user->rights->agenda->allactions->read', + 'enabled' => '$conf->categorie->enabled&&$conf->categorie->enabled', + 'target' => '', + 'user' => 2 + ); $r++; // Exports //-------- - $r=0; + $r = 0; $r++; - $this->export_code[$r]=$this->rights_class.'_'.$r; - $this->export_label[$r]="ExportDataset_event1"; - $this->export_permission[$r]=array(array("agenda","export")); - $this->export_fields_array[$r]=array('ac.id'=>"IdAgenda",'ac.ref_ext'=>"ExternalRef",'ac.datec'=>"DateCreation",'ac.datep'=>"DateActionBegin", - 'ac.datep2'=>"DateActionEnd",'ac.label'=>"Title",'ac.note'=>"Note",'ac.percent'=>"Percent",'ac.durationp'=>"Duration", + $this->export_code[$r] = $this->rights_class.'_'.$r; + $this->export_label[$r] = "ExportDataset_event1"; + $this->export_permission[$r] = array(array("agenda", "export")); + $this->export_fields_array[$r] = array('ac.id'=>"IdAgenda", 'ac.ref_ext'=>"ExternalRef", 'ac.datec'=>"DateCreation", 'ac.datep'=>"DateActionBegin", + 'ac.datep2'=>"DateActionEnd", 'ac.label'=>"Title", 'ac.note'=>"Note", 'ac.percent'=>"Percent", 'ac.durationp'=>"Duration", 'cac.libelle'=>"ActionType", - 's.rowid'=>"IdCompany",'s.nom'=>'CompanyName','s.address'=>'Address','s.zip'=>'Zip','s.town'=>'Town', - 'co.code'=>'CountryCode','s.phone'=>'Phone','s.siren'=>'ProfId1','s.siret'=>'ProfId2','s.ape'=>'ProfId3','s.idprof4'=>'ProfId4','s.idprof5'=>'ProfId5','s.idprof6'=>'ProfId6', - 's.code_compta'=>'CustomerAccountancyCode','s.code_compta_fournisseur'=>'SupplierAccountancyCode','s.tva_intra'=>'VATIntra'); - $this->export_TypeFields_array[$r]=array('ac.ref_ext'=>"Text",'ac.datec'=>"Date",'ac.datep'=>"Date", - 'ac.datep2'=>"Date",'ac.label'=>"Text",'ac.note'=>"Text",'ac.percent'=>"Numeric", + 's.rowid'=>"IdCompany", 's.nom'=>'CompanyName', 's.address'=>'Address', 's.zip'=>'Zip', 's.town'=>'Town', + 'co.code'=>'CountryCode', 's.phone'=>'Phone', 's.siren'=>'ProfId1', 's.siret'=>'ProfId2', 's.ape'=>'ProfId3', 's.idprof4'=>'ProfId4', 's.idprof5'=>'ProfId5', 's.idprof6'=>'ProfId6', + 's.code_compta'=>'CustomerAccountancyCode', 's.code_compta_fournisseur'=>'SupplierAccountancyCode', 's.tva_intra'=>'VATIntra', + 'p.ref' => 'ProjectRef', + ); + $this->export_TypeFields_array[$r] = array('ac.ref_ext'=>"Text", 'ac.datec'=>"Date", 'ac.datep'=>"Date", + 'ac.datep2'=>"Date", 'ac.label'=>"Text", 'ac.note'=>"Text", 'ac.percent'=>"Numeric", 'ac.durationp'=>"Duree", 'cac.libelle'=>"List:c_actioncomm:libelle:libelle", - 's.nom'=>'Text','s.address'=>'Text','s.zip'=>'Text','s.town'=>'Text', - 'co.code'=>'Text','s.phone'=>'Text','s.siren'=>'Text','s.siret'=>'Text','s.ape'=>'Text','s.idprof4'=>'Text','s.idprof5'=>'Text','s.idprof6'=>'Text', - 's.code_compta'=>'Text','s.code_compta_fournisseur'=>'Text','s.tva_intra'=>'Text'); - $this->export_entities_array[$r]=array('ac.id'=>"action",'ac.ref_ext'=>"action",'ac.datec'=>"action",'ac.datep'=>"action", - 'ac.datep2'=>"action",'ac.label'=>"action",'ac.note'=>"action",'ac.percent'=>"action",'ac.durationp'=>"action", + 's.nom'=>'Text', 's.address'=>'Text', 's.zip'=>'Text', 's.town'=>'Text', + 'co.code'=>'Text', 's.phone'=>'Text', 's.siren'=>'Text', 's.siret'=>'Text', 's.ape'=>'Text', 's.idprof4'=>'Text', 's.idprof5'=>'Text', 's.idprof6'=>'Text', + 's.code_compta'=>'Text', 's.code_compta_fournisseur'=>'Text', 's.tva_intra'=>'Text', + 'p.ref' => 'Text', + ); + $this->export_entities_array[$r] = array('ac.id'=>"action", 'ac.ref_ext'=>"action", 'ac.datec'=>"action", 'ac.datep'=>"action", + 'ac.datep2'=>"action", 'ac.label'=>"action", 'ac.note'=>"action", 'ac.percent'=>"action", 'ac.durationp'=>"action", 'cac.libelle'=>"action", - 's.rowid'=>"company",'s.nom'=>'company','s.address'=>'company','s.zip'=>'company','s.town'=>'company', - 'co.code'=>'company','s.phone'=>'company','s.siren'=>'company','s.siret'=>'company','s.ape'=>'company','s.idprof4'=>'company','s.idprof5'=>'company','s.idprof6'=>'company', - 's.code_compta'=>'company','s.code_compta_fournisseur'=>'company','s.tva_intra'=>'company',); + 's.rowid'=>"company", 's.nom'=>'company', 's.address'=>'company', 's.zip'=>'company', 's.town'=>'company', + 'co.code'=>'company', 's.phone'=>'company', 's.siren'=>'company', 's.siret'=>'company', 's.ape'=>'company', 's.idprof4'=>'company', 's.idprof5'=>'company', 's.idprof6'=>'company', + 's.code_compta'=>'company', 's.code_compta_fournisseur'=>'company', 's.tva_intra'=>'company', + 'p.ref' => 'project', + ); - $this->export_sql_start[$r]='SELECT DISTINCT '; - $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'actioncomm as ac'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_actioncomm as cac on ac.fk_action = cac.id'; - if (! empty($user) && empty($user->rights->agenda->allactions->read)) $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_resources acr on ac.id = acr.fk_actioncomm'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'socpeople as sp on ac.fk_contact = sp.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s on ac.fk_soc = s.rowid'; - if (! empty($user) && empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co on s.fk_pays = co.rowid'; - $this->export_sql_end[$r] .=' WHERE ac.entity IN ('.getEntity('agenda').')'; - if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .=' AND (sc.fk_user = '.(empty($user)?0:$user->id).' OR ac.fk_soc IS NULL)'; - if (empty($user->rights->agenda->allactions->read)) $this->export_sql_end[$r] .=' AND acr.fk_element = '.(empty($user)?0:$user->id); - $this->export_sql_order[$r] =' ORDER BY ac.datep'; + $this->export_sql_start[$r] = 'SELECT DISTINCT '; + $this->export_sql_end[$r] = ' FROM '.MAIN_DB_PREFIX.'actioncomm as ac'; + $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_actioncomm as cac on ac.fk_action = cac.id'; + if (!empty($user) && empty($user->rights->agenda->allactions->read)) $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_resources acr on ac.id = acr.fk_actioncomm'; + $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'socpeople as sp on ac.fk_contact = sp.rowid'; + $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s on ac.fk_soc = s.rowid'; + if (!empty($user) && empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid'; + $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co on s.fk_pays = co.rowid'; + $this->export_sql_end[$r] .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = ac.fk_project"; + $this->export_sql_end[$r] .= ' WHERE ac.entity IN ('.getEntity('agenda').')'; + if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' AND (sc.fk_user = '.(empty($user) ? 0 : $user->id).' OR ac.fk_soc IS NULL)'; + if (empty($user->rights->agenda->allactions->read)) $this->export_sql_end[$r] .= ' AND acr.fk_element = '.(empty($user) ? 0 : $user->id); + $this->export_sql_order[$r] = ' ORDER BY ac.datep'; } } diff --git a/htdocs/core/modules/modCashDesk.class.php b/htdocs/core/modules/modCashDesk.class.php index afb5185fb51..9bff4afdaf8 100644 --- a/htdocs/core/modules/modCashDesk.class.php +++ b/htdocs/core/modules/modCashDesk.class.php @@ -22,7 +22,7 @@ * \ingroup pos * \brief File to enable/disable module Point Of Sales */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** @@ -64,13 +64,13 @@ class modCashDesk extends DolibarrModules $this->config_page_url = array("cashdesk.php@cashdesk"); // Dependencies - $this->hidden = false; // A condition to hide module - $this->depends = array('always'=>"modBanque", 'always'=>"modFacture", 'always'=>"modProduct", 'FR'=>'modBlockedLog'); // List of modules id that must be enabled if this module is enabled - $this->requiredby = array(); // List of modules id to disable if this one is disabled - $this->phpmin = array(5,4); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(2,4); // Minimum version of Dolibarr required by module + $this->hidden = false; // A condition to hide module + $this->depends = array('always'=>"modBanque", 'always'=>"modFacture", 'always'=>"modProduct", 'FR'=>'modBlockedLog'); // List of modules id that must be enabled if this module is enabled + $this->requiredby = array(); // List of modules id to disable if this one is disabled + $this->phpmin = array(5, 4); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(2, 4); // Minimum version of Dolibarr required by module $this->langfiles = array("cashdesk"); - $this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text') + $this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text') //$this->warnings_activation_ext = array('FR'=>'WarningInstallationMayBecomeNotCompliantWithLaw'); // Warning to show when we activate an external module. array('always'='text') or array('FR'='text') // Constants @@ -81,7 +81,7 @@ class modCashDesk extends DolibarrModules // Permissions $this->rights = array(); - $r=0; + $r = 0; $r++; $this->rights[$r][0] = 50101; @@ -91,21 +91,21 @@ class modCashDesk extends DolibarrModules $this->rights[$r][4] = 'run'; // Main menu entries - $this->menus = array(); // List of menus to add - $r=0; + $this->menus = array(); // List of menus to add + $r = 0; // This is to declare the Top Menu entry: - $this->menu[$r]=array( 'fk_menu'=>0, // Put 0 if this is a top menu - 'type'=>'top', // This is a Top menu entry + $this->menu[$r] = array('fk_menu'=>0, // Put 0 if this is a top menu + 'type'=>'top', // This is a Top menu entry 'titre'=>'PointOfSaleShort', 'mainmenu'=>'cashdesk', 'url'=>'/cashdesk/index.php?user=__USER_LOGIN__', - 'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>900, 'enabled'=>'$conf->cashdesk->enabled', - 'perms'=>'$user->rights->cashdesk->run', // Use 'perms'=>'1' if you want your menu with no permission rules + 'perms'=>'$user->rights->cashdesk->run', // Use 'perms'=>'1' if you want your menu with no permission rules 'target'=>'pointofsale', - 'user'=>0); // 0=Menu for internal users, 1=external users, 2=both + 'user'=>0); // 0=Menu for internal users, 1=external users, 2=both $r++; diff --git a/htdocs/core/modules/modContrat.class.php b/htdocs/core/modules/modContrat.class.php index fe846c1fd4c..3b8a7aa3f8b 100644 --- a/htdocs/core/modules/modContrat.class.php +++ b/htdocs/core/modules/modContrat.class.php @@ -165,7 +165,7 @@ class modContrat extends DolibarrModules $this->export_fields_array[$r]=array('s.rowid'=>"IdCompany",'s.nom'=>'CompanyName','s.address'=>'Address','s.zip'=>'Zip','s.town'=>'Town','c.code'=>'CountryCode', 's.phone'=>'Phone','s.siren'=>'ProfId1','s.siret'=>'ProfId2','s.ape'=>'ProfId3','s.idprof4'=>'ProfId4','s.code_compta'=>'CustomerAccountancyCode', 's.code_compta_fournisseur'=>'SupplierAccountancyCode','s.tva_intra'=>'VATIntra', - 'co.rowid'=>"Id",'co.ref'=>"Ref",'co.datec'=>"DateCreation",'co.date_contrat'=>"DateContract",'co.mise_en_service'=>"ContractStartDate", + 'co.rowid'=>"Id",'co.ref'=>"Ref",'co.datec'=>"DateCreation",'co.date_contrat'=>"DateContract", 'co.fin_validite'=>"ContractEndDate",'co.date_cloture'=>"Closing",'co.note_private'=>"NotePrivate",'co.note_public'=>"NotePublic", 'cod.rowid'=>'LineId','cod.label'=>"LineLabel",'cod.description'=>"LineDescription",'cod.price_ht'=>"LineUnitPrice",'cod.tva_tx'=>"LineVATRate", 'cod.qty'=>"LineQty",'cod.total_ht'=>"LineTotalHT",'cod.total_tva'=>"LineTotalVAT",'cod.total_ttc'=>"LineTotalTTC", @@ -175,7 +175,7 @@ class modContrat extends DolibarrModules $this->export_entities_array[$r]=array('s.rowid'=>"company",'s.nom'=>'company','s.address'=>'company','s.zip'=>'company', 's.town'=>'company','c.code'=>'company','s.phone'=>'company','s.siren'=>'company','s.siret'=>'company','s.ape'=>'company', 's.idprof4'=>'company','s.code_compta'=>'company','s.code_compta_fournisseur'=>'company','s.tva_intra'=>'company', - 'co.rowid'=>"contract",'co.ref'=>"contract",'co.datec'=>"contract",'co.date_contrat'=>"contract",'co.mise_en_service'=>"contract", + 'co.rowid'=>"contract",'co.ref'=>"contract",'co.datec'=>"contract",'co.date_contrat'=>"contract", 'co.fin_validite'=>"contract",'co.date_cloture'=>"contract",'co.note_private'=>"contract",'co.note_public'=>"contract", 'cod.rowid'=>'contract_line','cod.label'=>"contract_line",'cod.description'=>"contract_line",'cod.price_ht'=>"contract_line",'cod.tva_tx'=>"contract_line", 'cod.qty'=>"contract_line",'cod.total_ht'=>"contract_line",'cod.total_tva'=>"contract_line",'cod.total_ttc'=>"contract_line", @@ -185,7 +185,7 @@ class modContrat extends DolibarrModules $this->export_TypeFields_array[$r]=array('s.rowid'=>"List:societe:nom",'s.nom'=>'Text','s.address'=>'Text','s.zip'=>'Text','s.town'=>'Text','c.code'=>'Text', 's.phone'=>'Text','s.siren'=>'Text','s.siret'=>'Text','s.ape'=>'Text','s.idprof4'=>'Text','s.code_compta'=>'Text', 's.code_compta_fournisseur'=>'Text','s.tva_intra'=>'Text', - 'co.ref'=>"Text",'co.datec'=>"Date",'co.date_contrat'=>"Date",'co.mise_en_service'=>"Date", + 'co.ref'=>"Text",'co.datec'=>"Date",'co.date_contrat'=>"Date", 'co.fin_validite'=>"Date",'co.date_cloture'=>"Date",'co.note_private'=>"Text",'co.note_public'=>"Text", 'cod.label'=>"Text",'cod.description'=>"Text",'cod.price_ht'=>"Numeric",'cod.tva_tx'=>"Numeric", 'cod.qty'=>"Numeric",'cod.total_ht'=>"Numeric",'cod.total_tva'=>"Numeric",'cod.total_ttc'=>"Numeric", diff --git a/htdocs/core/modules/modLabel.class.php b/htdocs/core/modules/modLabel.class.php index c6f2c5267b5..5edd3bd3200 100644 --- a/htdocs/core/modules/modLabel.class.php +++ b/htdocs/core/modules/modLabel.class.php @@ -77,17 +77,17 @@ class modLabel extends DolibarrModules $this->rights_class = 'label'; $this->rights[1][0] = 601; // id de la permission - $this->rights[1][1] = 'Lire les etiquettes'; // libelle de la permission + $this->rights[1][1] = 'Read stickers'; $this->rights[1][3] = 1; // La permission est-elle une permission par defaut $this->rights[1][4] = 'lire'; $this->rights[2][0] = 602; // id de la permission - $this->rights[2][1] = 'Creer/modifier les etiquettes'; // libelle de la permission + $this->rights[2][1] = 'Create/modify stickers'; $this->rights[2][3] = 0; // La permission est-elle une permission par defaut $this->rights[2][4] = 'creer'; $this->rights[4][0] = 609; // id de la permission - $this->rights[4][1] = 'Supprimer les etiquettes'; // libelle de la permission + $this->rights[4][1] = 'Delete stickers'; $this->rights[4][3] = 0; // La permission est-elle une permission par defaut $this->rights[4][4] = 'supprimer'; } diff --git a/htdocs/core/modules/modMrp.class.php b/htdocs/core/modules/modMrp.class.php index a5d58bd8333..1ca8e380aa4 100644 --- a/htdocs/core/modules/modMrp.class.php +++ b/htdocs/core/modules/modMrp.class.php @@ -26,7 +26,7 @@ * \ingroup mrp * \brief Description and activation file for module Mrp */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** * Description and activation class for module Mrp @@ -40,7 +40,7 @@ class modMrp extends DolibarrModules */ public function __construct($db) { - global $langs,$conf; + global $langs, $conf; $this->db = $db; // Id for module (must be unique). @@ -71,7 +71,7 @@ class modMrp extends DolibarrModules // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' - $this->picto='mrp'; + $this->picto = 'mrp'; // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) $this->module_parts = array( // Set this to 1 if module has its own trigger directory (core/triggers) @@ -119,13 +119,13 @@ class modMrp extends DolibarrModules $this->hidden = false; // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) $this->depends = array('modBom'); - $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) - $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) $this->langfiles = array("mrp"); - $this->phpmin = array(5,5); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(8,0); // Minimum version of Dolibarr required by module - $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) - $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->phpmin = array(5, 5); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(8, 0); // Minimum version of Dolibarr required by module + $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) //$this->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice'); //$this->always_enabled = true; // If true, can't be disabled @@ -146,9 +146,9 @@ class modMrp extends DolibarrModules 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' )*/ - if (! isset($conf->mrp) || ! isset($conf->mrp->enabled)) { - $conf->mrp=new stdClass(); - $conf->mrp->enabled=0; + if (!isset($conf->mrp) || !isset($conf->mrp->enabled)) { + $conf->mrp = new stdClass(); + $conf->mrp->enabled = 0; } // Array to add new pages in new tabs @@ -180,7 +180,7 @@ class modMrp extends DolibarrModules // 'user' to add a tab in user view // Dictionaries - $this->dictionaries=array(); + $this->dictionaries = array(); /* Example: $this->dictionaries=array( 'langs'=>'mylangfile@mrp', @@ -236,35 +236,35 @@ class modMrp extends DolibarrModules // Permissions provided by this module $this->rights = array(); - $r=0; + $r = 0; // Add here entries to declare new permissions /* BEGIN MODULEBUILDER PERMISSIONS */ - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Read Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Read Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Create/Update Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Create/Update Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Delete Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Delete Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) $r++; /* END MODULEBUILDER PERMISSIONS */ // Main menu entries to add $this->menu = array(); - $r=0; + $r = 0; // Add here entries to declare new menus /* BEGIN MODULEBUILDER TOPMENU */ /* END MODULEBUILDER LEFTMENU MO */ // Exports profiles provided by this module - $r=1; + $r = 1; /* BEGIN MODULEBUILDER EXPORT MO */ /* $langs->load("mrp"); @@ -284,7 +284,7 @@ class modMrp extends DolibarrModules /* END MODULEBUILDER EXPORT MO */ // Imports profiles provided by this module - $r=1; + $r = 1; /* BEGIN MODULEBUILDER IMPORT MO */ /* $langs->load("mrp"); @@ -316,7 +316,7 @@ class modMrp extends DolibarrModules { global $conf, $langs; - $result=$this->_load_tables('/mrp/sql/'); + $result = $this->_load_tables('/mrp/sql/'); if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') // Create extrafields during init @@ -334,19 +334,19 @@ class modMrp extends DolibarrModules $sql = array(); // ODT template - $src=DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt'; - $dirodt=DOL_DATA_ROOT.'/doctemplates/mrps'; - $dest=$dirodt.'/template_mo.odt'; + $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt'; + $dirodt = DOL_DATA_ROOT.'/doctemplates/mrps'; + $dest = $dirodt.'/template_mo.odt'; - if (file_exists($src) && ! file_exists($dest)) + if (file_exists($src) && !file_exists($dest)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; dol_mkdir($dirodt); - $result=dol_copy($src, $dest, 0, 0); + $result = dol_copy($src, $dest, 0, 0); if ($result < 0) { $langs->load("errors"); - $this->error=$langs->trans('ErrorFailToCopyFile', $src, $dest); + $this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest); return 0; } } diff --git a/htdocs/core/modules/modReceiptPrinter.class.php b/htdocs/core/modules/modReceiptPrinter.class.php index f2d207e1983..f2fc5183668 100644 --- a/htdocs/core/modules/modReceiptPrinter.class.php +++ b/htdocs/core/modules/modReceiptPrinter.class.php @@ -132,13 +132,15 @@ class modReceiptPrinter extends DolibarrModules */ public function init($options = '') { - global $conf; + global $conf, $langs; // Clean before activation $this->remove($options); $sql = array( "CREATE TABLE IF NOT EXISTS ".MAIN_DB_PREFIX."printer_receipt (rowid integer AUTO_INCREMENT PRIMARY KEY, name varchar(128), fk_type integer, fk_profile integer, parameter varchar(128), entity integer) ENGINE=innodb;", "CREATE TABLE IF NOT EXISTS ".MAIN_DB_PREFIX."printer_receipt_template (rowid integer AUTO_INCREMENT PRIMARY KEY, name varchar(128), template text, entity integer) ENGINE=innodb;", - ); + "DELETE FROM ".MAIN_DB_PREFIX."printer_receipt_template WHERE name = '".$langs->trans('Example')."';", + "INSERT INTO ".MAIN_DB_PREFIX."printer_receipt_template (name,template,entity) VALUES ('".$langs->trans('Example')."', '\r\n\r\n\r\n\r\n\r\nFacture \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n', 1);", + ); return $this->_init($sql, $options); } } diff --git a/htdocs/core/modules/modTakePos.class.php b/htdocs/core/modules/modTakePos.class.php index 515f18cf690..804ce8152ab 100644 --- a/htdocs/core/modules/modTakePos.class.php +++ b/htdocs/core/modules/modTakePos.class.php @@ -24,7 +24,7 @@ * \ingroup takepos * \brief Description and activation file for module TakePos */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** @@ -39,7 +39,7 @@ class modTakePos extends DolibarrModules */ public function __construct($db) { - global $langs,$conf; + global $langs, $conf; $this->db = $db; @@ -71,21 +71,21 @@ class modTakePos extends DolibarrModules // Name of image file used for this module. // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' - $this->picto='list'; + $this->picto = 'list'; // Defined all module parts (triggers, login, substitutions, menus, css, etc...) // for default path (eg: /takepos/core/xxxxx) (0=disable, 1=enable) // for specific path of parts (eg: /takepos/core/modules/barcode) // for specific css file (eg: /takepos/css/takepos.css.php) $this->module_parts = array( - 'triggers' => 0, // Set this to 1 if module has its own trigger directory (core/triggers) - 'login' => 0, // Set this to 1 if module has its own login method file (core/login) - 'substitutions' => 1, // Set this to 1 if module has its own substitution function file (core/substitutions) - 'menus' => 0, // Set this to 1 if module has its own menus handler directory (core/menus) - 'theme' => 0, // Set this to 1 if module has its own theme directory (theme) - 'tpl' => 0, // Set this to 1 if module overwrite template dir (core/tpl) - 'barcode' => 0, // Set this to 1 if module has its own barcode directory (core/modules/barcode) - 'models' => 0, // Set this to 1 if module has its own models directory (core/modules/xxx) + 'triggers' => 0, // Set this to 1 if module has its own trigger directory (core/triggers) + 'login' => 0, // Set this to 1 if module has its own login method file (core/login) + 'substitutions' => 1, // Set this to 1 if module has its own substitution function file (core/substitutions) + 'menus' => 0, // Set this to 1 if module has its own menus handler directory (core/menus) + 'theme' => 0, // Set this to 1 if module has its own theme directory (theme) + 'tpl' => 0, // Set this to 1 if module overwrite template dir (core/tpl) + 'barcode' => 0, // Set this to 1 if module has its own barcode directory (core/modules/barcode) + 'models' => 0, // Set this to 1 if module has its own models directory (core/modules/xxx) 'hooks' => array() // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context 'all' ); @@ -97,15 +97,15 @@ class modTakePos extends DolibarrModules $this->config_page_url = array("setup.php@takepos"); // Dependencies - $this->hidden = false; // A condition to hide module - $this->depends = array('always1'=>"modBanque", 'always2'=>"modFacture", 'always3'=>"modProduct", 'always4'=>'modCategorie', 'FR1'=>'modBlockedLog'); // List of module class names as string that must be enabled if this module is enabled - $this->requiredby = array(); // List of module ids to disable if this one is disabled - $this->conflictwith = array(); // List of module class names as string this module is in conflict with + $this->hidden = false; // A condition to hide module + $this->depends = array('always1'=>"modBanque", 'always2'=>"modFacture", 'always3'=>"modProduct", 'always4'=>'modCategorie', 'FR1'=>'modBlockedLog'); // List of module class names as string that must be enabled if this module is enabled + $this->requiredby = array(); // List of module ids to disable if this one is disabled + $this->conflictwith = array(); // List of module class names as string this module is in conflict with $this->langfiles = array("cashdesk"); - $this->phpmin = array(5,4); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(4,0); // Minimum version of Dolibarr required by module - $this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text') - $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->phpmin = array(5, 4); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(4, 0); // Minimum version of Dolibarr required by module + $this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text') + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) //$this->automatic_activation = array('FR'=>'TakePosWasAutomaticallyActivatedBecauseOfYourCountryChoice'); //$this->always_enabled = true; // If true, can't be disabled @@ -119,10 +119,10 @@ class modTakePos extends DolibarrModules ); - if (! isset($conf->takepos) || ! isset($conf->takepos->enabled)) + if (!isset($conf->takepos) || !isset($conf->takepos->enabled)) { - $conf->takepos=new stdClass(); - $conf->takepos->enabled=0; + $conf->takepos = new stdClass(); + $conf->takepos->enabled = 0; } @@ -156,7 +156,7 @@ class modTakePos extends DolibarrModules // Dictionaries - $this->dictionaries=array(); + $this->dictionaries = array(); /* Example: $this->dictionaries=array( 'langs'=>'mylangfile@takepos', @@ -193,9 +193,9 @@ class modTakePos extends DolibarrModules // Permissions - $this->rights = array(); // Permission array used by this module + $this->rights = array(); // Permission array used by this module - $r=0; + $r = 0; $r++; $this->rights[$r][0] = 50151; @@ -206,24 +206,24 @@ class modTakePos extends DolibarrModules // Main menu entries - $this->menu = array(); // List of menus to add - $r=0; + $this->menu = array(); // List of menus to add + $r = 0; // Add here entries to declare new menus /* BEGIN MODULEBUILDER TOPMENU */ - $this->menu[$r++]=array('fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode - 'type'=>'top', // This is a Top menu entry + $this->menu[$r++] = array('fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'top', // This is a Top menu entry 'titre'=>'PointOfSaleShort', 'mainmenu'=>'takepos', 'leftmenu'=>'', 'url'=>'/takepos/takepos.php', - 'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position'=>1000+$r, - 'enabled'=>'$conf->takepos->enabled', // Define condition to show or hide menu entry. Use '$conf->takepos->enabled' if entry must be visible if module is enabled. - 'perms'=>'$user->rights->takepos->run', // Use 'perms'=>'$user->rights->takepos->level1->level2' if you want your menu with a permission rules + 'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000 + $r, + 'enabled'=>'$conf->takepos->enabled', // Define condition to show or hide menu entry. Use '$conf->takepos->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->takepos->run', // Use 'perms'=>'$user->rights->takepos->level1->level2' if you want your menu with a permission rules 'target'=>'takepos', - 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both /* END MODULEBUILDER TOPMENU */ diff --git a/htdocs/core/modules/modTicket.class.php b/htdocs/core/modules/modTicket.class.php index 8d7f16fcaf7..fbf560565ee 100644 --- a/htdocs/core/modules/modTicket.class.php +++ b/htdocs/core/modules/modTicket.class.php @@ -120,16 +120,16 @@ class modTicket extends DolibarrModules } $this->dictionaries = array( 'langs' => 'ticket', - 'tabname' => array(MAIN_DB_PREFIX . "c_ticket_type", MAIN_DB_PREFIX . "c_ticket_severity", MAIN_DB_PREFIX . "c_ticket_category"), - 'tablib' => array("TicketDictType", "TicketDictSeverity", "TicketDictCategory"), - 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticket_type as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticket_severity as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM ' . MAIN_DB_PREFIX . 'c_ticket_category as f'), - 'tabsqlsort' => array("pos ASC", "pos ASC", "pos ASC"), - 'tabfield' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), - 'tabfieldvalue' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), - 'tabfieldinsert' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), - 'tabrowid' => array("rowid", "rowid", "rowid"), - 'tabcond' => array($conf->ticket->enabled, $conf->ticket->enabled, $conf->ticket->enabled), - 'tabhelp' => array(array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1")), array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1")), array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1"))), + 'tabname' => array(MAIN_DB_PREFIX."c_ticket_type", MAIN_DB_PREFIX."c_ticket_severity", MAIN_DB_PREFIX."c_ticket_category", MAIN_DB_PREFIX."c_ticket_resolution"), + 'tablib' => array("TicketDictType", "TicketDictSeverity", "TicketDictCategory", "TicketDictResolution"), + 'tabsql' => array('SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM '.MAIN_DB_PREFIX.'c_ticket_type as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM '.MAIN_DB_PREFIX.'c_ticket_severity as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM '.MAIN_DB_PREFIX.'c_ticket_category as f', 'SELECT f.rowid as rowid, f.code, f.pos, f.label, f.active, f.use_default FROM '.MAIN_DB_PREFIX.'c_ticket_resolution as f'), + 'tabsqlsort' => array("pos ASC", "pos ASC", "pos ASC", "pos ASC"), + 'tabfield' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabfieldvalue' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabfieldinsert' => array("pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default", "pos,code,label,use_default"), + 'tabrowid' => array("rowid", "rowid", "rowid", "rowid"), + 'tabcond' => array($conf->ticket->enabled, $conf->ticket->enabled, $conf->ticket->enabled, $conf->ticket->enabled), + 'tabhelp' => array(array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1")), array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1")), array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1")), array('code'=>$langs->trans("EnterAnyCode"), 'use_default'=>$langs->trans("Enter0or1"))), ); // Boxes diff --git a/htdocs/core/modules/modUser.class.php b/htdocs/core/modules/modUser.class.php index 6e5924945c9..ca1a8d22209 100644 --- a/htdocs/core/modules/modUser.class.php +++ b/htdocs/core/modules/modUser.class.php @@ -25,7 +25,7 @@ * \brief Fichier de description et activation du module Utilisateur */ -include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; /** * Class to describe and enable module User @@ -45,7 +45,7 @@ class modUser extends DolibarrModules $this->db = $db; $this->numero = 0; - $this->family = "hr"; // Family for module (or "base" if core module) + $this->family = "hr"; // Family for module (or "base" if core module) $this->module_position = '05'; // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) $this->name = preg_replace('/^mod/i', '', get_class($this)); @@ -55,7 +55,7 @@ class modUser extends DolibarrModules $this->version = 'dolibarr'; $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); - $this->picto='group'; + $this->picto = 'group'; // Data directories to create when module is enabled $this->dirs = array("/users/temp"); @@ -64,28 +64,28 @@ class modUser extends DolibarrModules $this->config_page_url = array("user.php"); // Dependencies - $this->hidden = false; // A condition to hide module - $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled - $this->requiredby = array(); // List of module ids to disable if this one is disabled - $this->conflictwith = array(); // List of module class names as string this module is in conflict with - $this->phpmin = array(5,4); // Minimum version of PHP required by module - $this->langfiles = array("main","users","companies","members","salaries","hrm"); - $this->always_enabled = true; // Can't be disabled + $this->hidden = false; // A condition to hide module + $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled + $this->requiredby = array(); // List of module ids to disable if this one is disabled + $this->conflictwith = array(); // List of module class names as string this module is in conflict with + $this->phpmin = array(5, 4); // Minimum version of PHP required by module + $this->langfiles = array("main", "users", "companies", "members", "salaries", "hrm"); + $this->always_enabled = true; // Can't be disabled // Constants $this->const = array(); // Boxes $this->boxes = array( - 0=>array('file'=>'box_lastlogin.php','enabledbydefaulton'=>'Home'), - 1=>array('file'=>'box_birthdays.php','enabledbydefaulton'=>'Home') + 0=>array('file'=>'box_lastlogin.php', 'enabledbydefaulton'=>'Home'), + 1=>array('file'=>'box_birthdays.php', 'enabledbydefaulton'=>'Home') ); // Permissions $this->rights = array(); $this->rights_class = 'user'; - $this->rights_admin_allowed = 1; // Admin is always granted of permission (even when module is disabled) - $r=0; + $this->rights_admin_allowed = 1; // Admin is always granted of permission (even when module is disabled) + $r = 0; $r++; $this->rights[$r][0] = 251; @@ -140,7 +140,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Consulter ses propres permissions'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'self_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'self_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'readperms'; $r++; @@ -164,7 +164,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Modifier ses propres permissions'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'self_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'self_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'writeperms'; $r++; @@ -172,7 +172,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Consulter les groupes'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'read'; $r++; @@ -180,7 +180,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Consulter les permissions des groupes'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'readperms'; $r++; @@ -188,7 +188,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Creer/modifier les groupes et leurs permissions'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'write'; $r++; @@ -196,7 +196,7 @@ class modUser extends DolibarrModules $this->rights[$r][1] = 'Supprimer ou desactiver les groupes'; $this->rights[$r][2] = 'd'; $this->rights[$r][3] = 0; - $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on + $this->rights[$r][4] = 'group_advance'; // Visible if option MAIN_USE_ADVANCED_PERMS is on $this->rights[$r][5] = 'delete'; $r++; @@ -209,118 +209,118 @@ class modUser extends DolibarrModules // Menus - $this->menu = 1; // This module add menu entries. They are coded into menu manager. + $this->menu = 1; // This module add menu entries. They are coded into menu manager. // Exports - $r=0; + $r = 0; $r++; - $this->export_code[$r]=$this->rights_class.'_'.$r; - $this->export_label[$r]='List of users and attributes'; - $this->export_permission[$r]=array(array("user","user","export")); - $this->export_fields_array[$r]=array( - 'u.rowid'=>"Id",'u.login'=>"Login",'u.lastname'=>"Lastname",'u.firstname'=>"Firstname",'u.employee'=>"Employee",'u.job'=>"PostOrFunction",'u.gender'=>"Gender", + $this->export_code[$r] = $this->rights_class.'_'.$r; + $this->export_label[$r] = 'List of users and attributes'; + $this->export_permission[$r] = array(array("user", "user", "export")); + $this->export_fields_array[$r] = array( + 'u.rowid'=>"Id", 'u.login'=>"Login", 'u.lastname'=>"Lastname", 'u.firstname'=>"Firstname", 'u.employee'=>"Employee", 'u.job'=>"PostOrFunction", 'u.gender'=>"Gender", 'u.accountancy_code'=>"UserAccountancyCode", - 'u.address'=>"Address",'u.zip'=>"Zip",'u.town'=>"Town", - 'u.office_phone'=>'Phone','u.user_mobile'=>"Mobile",'u.office_fax'=>'Fax', - 'u.email'=>"Email",'u.note'=>"Note",'u.signature'=>'Signature', - 'u.fk_user'=>'HierarchicalResponsible','u.thm'=>'THM','u.tjm'=>'TJM','u.weeklyhours'=>'WeeklyHours', - 'u.dateemployment'=>'DateEmployment','u.salary'=>'Salary','u.color'=>'Color','u.api_key'=>'ApiKey', + 'u.address'=>"Address", 'u.zip'=>"Zip", 'u.town'=>"Town", + 'u.office_phone'=>'Phone', 'u.user_mobile'=>"Mobile", 'u.office_fax'=>'Fax', + 'u.email'=>"Email", 'u.note'=>"Note", 'u.signature'=>'Signature', + 'u.fk_user'=>'HierarchicalResponsible', 'u.thm'=>'THM', 'u.tjm'=>'TJM', 'u.weeklyhours'=>'WeeklyHours', + 'u.dateemployment'=>'DateEmployment', 'u.salary'=>'Salary', 'u.color'=>'Color', 'u.api_key'=>'ApiKey', 'u.birth'=>'BirthdayDate', - 'u.datec'=>"DateCreation",'u.tms'=>"DateLastModification", - 'u.admin'=>"Administrator",'u.statut'=>'Status','u.datelastlogin'=>'LastConnexion','u.datepreviouslogin'=>'PreviousConnexion', - 'u.fk_socpeople'=>"IdContact",'u.fk_soc'=>"IdCompany",'u.fk_member'=>"MemberId" + 'u.datec'=>"DateCreation", 'u.tms'=>"DateLastModification", + 'u.admin'=>"Administrator", 'u.statut'=>'Status', 'u.datelastlogin'=>'LastConnexion', 'u.datepreviouslogin'=>'PreviousConnexion', + 'u.fk_socpeople'=>"IdContact", 'u.fk_soc'=>"IdCompany", 'u.fk_member'=>"MemberId" ); - $this->export_TypeFields_array[$r]=array( - 'u.rowid'=>'Numeric', 'u.login'=>"Text",'u.lastname'=>"Text",'u.firstname'=>"Text",'u.employee'=>'Boolean','u.job'=>'Text', + $this->export_TypeFields_array[$r] = array( + 'u.rowid'=>'Numeric', 'u.login'=>"Text", 'u.lastname'=>"Text", 'u.firstname'=>"Text", 'u.employee'=>'Boolean', 'u.job'=>'Text', 'u.accountancy_code'=>'Text', - 'u.address'=>"Text",'u.zip'=>"Text",'u.town'=>"Text", - 'u.office_phone'=>'Text','u.user_mobile'=>'Text','u.office_fax'=>'Text', - 'u.email'=>'Text','u.datec'=>"Date",'u.tms'=>"Date",'u.admin'=>"Boolean",'u.statut'=>'Status','u.note'=>"Text",'u.datelastlogin'=>'Date', + 'u.address'=>"Text", 'u.zip'=>"Text", 'u.town'=>"Text", + 'u.office_phone'=>'Text', 'u.user_mobile'=>'Text', 'u.office_fax'=>'Text', + 'u.email'=>'Text', 'u.datec'=>"Date", 'u.tms'=>"Date", 'u.admin'=>"Boolean", 'u.statut'=>'Status', 'u.note'=>"Text", 'u.datelastlogin'=>'Date', 'u.fk_user'=>"List:user:login", 'u.birth'=>'Date', - 'u.datepreviouslogin'=>'Date','u.fk_soc'=>"List:societe:nom:rowid",'u.fk_member'=>"List:adherent:firstname" + 'u.datepreviouslogin'=>'Date', 'u.fk_soc'=>"List:societe:nom:rowid", 'u.fk_member'=>"List:adherent:firstname" ); - $this->export_entities_array[$r]=array( - 'u.rowid'=>"user",'u.login'=>"user",'u.lastname'=>"user",'u.firstname'=>"user",'u.employee'=>'user','u.job'=>'user','u.gender'=>'user', + $this->export_entities_array[$r] = array( + 'u.rowid'=>"user", 'u.login'=>"user", 'u.lastname'=>"user", 'u.firstname'=>"user", 'u.employee'=>'user', 'u.job'=>'user', 'u.gender'=>'user', 'u.accountancy_code'=>'user', - 'u.address'=>"user",'u.zip'=>"user",'u.town'=>"user", - 'u.office_phone'=>'user','u.user_mobile'=>'user','u.office_fax'=>'user', - 'u.email'=>'user','u.note'=>"user",'u.signature'=>'user', - 'u.fk_user'=>'user','u.thm'=>'user','u.tjm'=>'user','u.weeklyhours'=>'user', - 'u.dateemployment'=>'user','u.salary'=>'user','u.color'=>'user','u.api_key'=>'user', + 'u.address'=>"user", 'u.zip'=>"user", 'u.town'=>"user", + 'u.office_phone'=>'user', 'u.user_mobile'=>'user', 'u.office_fax'=>'user', + 'u.email'=>'user', 'u.note'=>"user", 'u.signature'=>'user', + 'u.fk_user'=>'user', 'u.thm'=>'user', 'u.tjm'=>'user', 'u.weeklyhours'=>'user', + 'u.dateemployment'=>'user', 'u.salary'=>'user', 'u.color'=>'user', 'u.api_key'=>'user', 'u.birth'=>'user', - 'u.datec'=>"user",'u.tms'=>"user", - 'u.admin'=>"user",'u.statut'=>'user','u.datelastlogin'=>'user','u.datepreviouslogin'=>'user', - 'u.fk_socpeople'=>"contact",'u.fk_soc'=>"company",'u.fk_member'=>"member" + 'u.datec'=>"user", 'u.tms'=>"user", + 'u.admin'=>"user", 'u.statut'=>'user', 'u.datelastlogin'=>'user', 'u.datepreviouslogin'=>'user', + 'u.fk_socpeople'=>"contact", 'u.fk_soc'=>"company", 'u.fk_member'=>"member" ); if (empty($conf->adherent->enabled)) { unset($this->export_fields_array[$r]['u.fk_member']); unset($this->export_entities_array[$r]['u.fk_member']); } - $this->export_sql_start[$r]='SELECT DISTINCT '; - $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'user as u'; - $this->export_sql_end[$r] .=' WHERE u.entity IN ('.getEntity('user').')'; + $this->export_sql_start[$r] = 'SELECT DISTINCT '; + $this->export_sql_end[$r] = ' FROM '.MAIN_DB_PREFIX.'user as u'; + $this->export_sql_end[$r] .= ' WHERE u.entity IN ('.getEntity('user').')'; // Imports - $r=0; + $r = 0; // Import list of users attributes $r++; - $this->import_code[$r]=$this->rights_class.'_'.$r; - $this->import_label[$r]='ImportDataset_user_1'; - $this->import_icon[$r]='user'; - $this->import_entities_array[$r]=array(); // We define here only fields that use another icon that the one defined into import_icon - $this->import_tables_array[$r]=array('u'=>MAIN_DB_PREFIX.'user','extra'=>MAIN_DB_PREFIX.'user_extrafields'); // List of tables to insert into (insert done in same order) - $this->import_fields_array[$r]=array( - 'u.login'=>"Login*",'u.lastname'=>"Name*",'u.firstname'=>"Firstname",'u.employee'=>"Employee*",'u.job'=>"PostOrFunction",'u.gender'=>"Gender", + $this->import_code[$r] = $this->rights_class.'_'.$r; + $this->import_label[$r] = 'ImportDataset_user_1'; + $this->import_icon[$r] = 'user'; + $this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon + $this->import_tables_array[$r] = array('u'=>MAIN_DB_PREFIX.'user', 'extra'=>MAIN_DB_PREFIX.'user_extrafields'); // List of tables to insert into (insert done in same order) + $this->import_fields_array[$r] = array( + 'u.login'=>"Login*", 'u.lastname'=>"Name*", 'u.firstname'=>"Firstname", 'u.employee'=>"Employee*", 'u.job'=>"PostOrFunction", 'u.gender'=>"Gender", 'u.accountancy_code'=>"UserAccountancyCode", - 'u.pass_crypted'=>"Password",'u.admin'=>"Administrator",'u.fk_soc'=>"Company*",'u.address'=>"Address",'u.zip'=>"Zip",'u.town'=>"Town", - 'u.fk_state'=>"StateId",'u.fk_country'=>"CountryCode", - 'u.office_phone'=>"Phone",'u.user_mobile'=>"Mobile",'u.office_fax'=>"Fax", - 'u.email'=>"Email",'u.note'=>"Note",'u.signature'=>'Signature', - 'u.fk_user'=>'HierarchicalResponsible','u.thm'=>'THM','u.tjm'=>'TJM','u.weeklyhours'=>'WeeklyHours', - 'u.dateemployment'=>'DateEmployment','u.salary'=>'Salary','u.color'=>'Color','u.api_key'=>'ApiKey', + 'u.pass_crypted'=>"Password", 'u.admin'=>"Administrator", 'u.fk_soc'=>"Company*", 'u.address'=>"Address", 'u.zip'=>"Zip", 'u.town'=>"Town", + 'u.fk_state'=>"StateId", 'u.fk_country'=>"CountryCode", + 'u.office_phone'=>"Phone", 'u.user_mobile'=>"Mobile", 'u.office_fax'=>"Fax", + 'u.email'=>"Email", 'u.note'=>"Note", 'u.signature'=>'Signature', + 'u.fk_user'=>'HierarchicalResponsible', 'u.thm'=>'THM', 'u.tjm'=>'TJM', 'u.weeklyhours'=>'WeeklyHours', + 'u.dateemployment'=>'DateEmployment', 'u.salary'=>'Salary', 'u.color'=>'Color', 'u.api_key'=>'ApiKey', 'u.birth'=>'BirthdayDate', 'u.datec'=>"DateCreation", 'u.statut'=>'Status' ); // Add extra fields - $sql="SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'user' AND entity IN (0,".$conf->entity.")"; - $resql=$this->db->query($sql); + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'user' AND entity IN (0,".$conf->entity.")"; + $resql = $this->db->query($sql); if ($resql) // This can fail when class is used on old database (during migration for example) { - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $fieldname='extra.'.$obj->name; - $fieldlabel=ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname]=$fieldlabel.($obj->fieldrequired?'*':''); + $fieldname = 'extra.'.$obj->name; + $fieldlabel = ucfirst($obj->label); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); } } // End add extra fields - $this->import_fieldshidden_array[$r]=array('u.fk_user_creat'=>'user->id','extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'user'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent) - $this->import_convertvalue_array[$r]=array( - 'u.fk_state'=>array('rule'=>'fetchidfromcodeid','classfile'=>'/core/class/cstate.class.php','class'=>'Cstate','method'=>'fetch','dict'=>'DictionaryState'), - 'u.fk_country'=>array('rule'=>'fetchidfromcodeid','classfile'=>'/core/class/ccountry.class.php','class'=>'Ccountry','method'=>'fetch','dict'=>'DictionaryCountry'), + $this->import_fieldshidden_array[$r] = array('u.fk_user_creat'=>'user->id', 'extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'user'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent) + $this->import_convertvalue_array[$r] = array( + 'u.fk_state'=>array('rule'=>'fetchidfromcodeid', 'classfile'=>'/core/class/cstate.class.php', 'class'=>'Cstate', 'method'=>'fetch', 'dict'=>'DictionaryState'), + 'u.fk_country'=>array('rule'=>'fetchidfromcodeid', 'classfile'=>'/core/class/ccountry.class.php', 'class'=>'Ccountry', 'method'=>'fetch', 'dict'=>'DictionaryCountry'), 'u.salary'=>array('rule'=>'numeric') ); //$this->import_convertvalue_array[$r]=array('s.fk_soc'=>array('rule'=>'lastrowid',table='t'); - $this->import_regex_array[$r]=array( + $this->import_regex_array[$r] = array( 'u.employee'=>'^[0|1]', 'u.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]( [0-9][0-9]:[0-9][0-9]:[0-9][0-9])?$', 'u.dateemployment'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$', 'u.birth'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$' ); - $this->import_examplevalues_array[$r]=array( + $this->import_examplevalues_array[$r] = array( 'u.lastname'=>"Doe", 'u.firstname'=>'John', 'u.login'=>'jdoe', 'u.employee'=>'0 or 1', 'u.fk_soc'=>'0 (internal user) or company name (external user)', 'u.datec'=>dol_print_date(dol_now(), '%Y-%m-%d'), 'u.address'=>"61 jump street", - 'u.zip'=>"123456",'u.town'=>"Big town",'u.fk_country'=>'US, FR, DE...','u.office_phone'=>"0101010101",'u.office_fax'=>"0101010102", - 'u.email'=>"test@mycompany.com",'u.salary'=>"10000",'u.note'=>"This is an example of note for record",'u.datec'=>"2015-01-01 or 2015-01-01 12:30:00", + 'u.zip'=>"123456", 'u.town'=>"Big town", 'u.fk_country'=>'US, FR, DE...', 'u.office_phone'=>"0101010101", 'u.office_fax'=>"0101010102", + 'u.email'=>"test@mycompany.com", 'u.salary'=>"10000", 'u.note'=>"This is an example of note for record", 'u.datec'=>"2015-01-01 or 2015-01-01 12:30:00", 'u.statut'=>"0 (closed) or 1 (active)", ); - $this->import_updatekeys_array[$r]=array('u.lastname'=>'Lastname','u.firstname'=>'Firstname','u.login'=>'Login'); + $this->import_updatekeys_array[$r] = array('u.lastname'=>'Lastname', 'u.firstname'=>'Firstname', 'u.login'=>'Login'); } diff --git a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php index b955da102ab..fde5f08d318 100644 --- a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php +++ b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php @@ -2,7 +2,7 @@ /* Copyright (C) 2010-2012 Laurent Destailleur * Copyright (C) 2012 Juanjo Menent * Copyright (C) 2016 Charlie Benke - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -115,7 +115,7 @@ class doc_generic_proposal_odt extends ModelePDFPropales $form = new Form($this->db); $texte = $this->description.".
\n"; - $texte .= ''; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= ''; @@ -205,7 +205,11 @@ class doc_generic_proposal_odt extends ModelePDFPropales $texte .= '
'; } } - + // Add input to upload a new template file. + $texte .= '
'.$langs->trans("UploadNewTemplate").' '; + $texte .= ''; + $texte .= ''; + $texte .= '
'; $texte .= '
'; diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index 222858750a7..9ed7a065cc1 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -58,7 +58,7 @@ class pdf_azur extends ModelePDFPropales public $description; /** - * @var string Save the name of generated file as the main doc when generating a doc with this template + * @var string Save the name of generated file as the main doc when generating a doc with this template */ public $update_main_doc_field; @@ -116,7 +116,7 @@ class pdf_azur extends ModelePDFPropales /** * Issuer - * @var Societe object that emits + * @var Societe Object that emits */ public $emetteur; @@ -160,8 +160,6 @@ class pdf_azur extends ModelePDFPropales $this->option_freetext = 1; // Support add of a personalised text $this->option_draft_watermark = 1; // Support add of a watermark on drafts - $this->franchise = !$mysoc->tva_assuj; - // Get source company $this->emetteur = $mysoc; if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined @@ -876,13 +874,13 @@ class pdf_azur extends ModelePDFPropales protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); diff --git a/htdocs/core/modules/propale/doc/pdf_cyan.modules.php b/htdocs/core/modules/propale/doc/pdf_cyan.modules.php index db9b5a3818d..af04a52e21f 100644 --- a/htdocs/core/modules/propale/doc/pdf_cyan.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_cyan.modules.php @@ -57,7 +57,7 @@ class pdf_cyan extends ModelePDFPropales public $description; /** - * @var int Save the name of generated file as the main doc when generating a doc with this template + * @var string Save the name of generated file as the main doc when generating a doc with this template */ public $update_main_doc_field; @@ -76,7 +76,7 @@ class pdf_cyan extends ModelePDFPropales * Dolibarr version of the loaded document * @var string */ - public $version = 'development'; + public $version = 'dolibarr'; /** * @var int page_largeur @@ -115,7 +115,7 @@ class pdf_cyan extends ModelePDFPropales /** * Issuer - * @var Societe + * @var Societe Object that emits */ public $emetteur; @@ -135,47 +135,45 @@ class pdf_cyan extends ModelePDFPropales $this->db = $db; $this->name = "cyan"; $this->description = $langs->trans('DocModelCyanDescription'); - $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template // Dimension page $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Display logo - $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION - $this->option_modereg = 1; // Display payment mode - $this->option_condreg = 1; // Display payment terms - $this->option_codeproduitservice = 1; // Display product-service code - $this->option_multilang = 1; // Available in several languages - $this->option_escompte = 0; // Displays if there has been a discount - $this->option_credit_note = 0; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 0; // Displays if there has been a discount + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; + $this->posxdesc = $this->marge_gauche + 1; $this->tabTitleHeight = 5; // default height - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -193,52 +191,63 @@ class pdf_cyan extends ModelePDFPropales public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$mysoc,$db,$hookmanager,$nblines; + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Translations + // Load traductions files required by page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + } + $nblines = count($object->lines); - $hidetop=0; - if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){ - $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; } // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); + $realpatharray = array(); $this->atleastonephoto = false; - if (! empty($conf->global->MAIN_GENERATE_PROPOSALS_WITH_PICTURE)) + if (!empty($conf->global->MAIN_GENERATE_PROPOSALS_WITH_PICTURE)) { $objphoto = new Product($this->db); - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto->fetch($object->lines[$i]->fk_product); //var_dump($objphoto->ref);exit; - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; - $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; } else { - $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; // default - $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/"; // alternative + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative } $arephoto = false; foreach ($pdir as $midir) { - if (! $arephoto) + if (!$arephoto) { - $dir = $conf->product->dir_output.'/'.$midir; + if ($conf->product->entity != $objphoto->entity) { + $dir = $conf->product->multidir_output[$objphoto->entity].'/'.$midir; //Check repertories of current entities + } else { + $dir = $conf->product->dir_output.'/'.$midir; //Check repertory of the current product + } foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { @@ -324,14 +333,14 @@ class pdf_cyan extends ModelePDFPropales } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -384,40 +393,42 @@ class pdf_cyan extends ModelePDFPropales $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } } // Affiche notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } - if (! empty($conf->global->MAIN_ADD_CREATOR_IN_NOTE) && $object->user_author_id > 0) + if (!empty($conf->global->MAIN_ADD_CREATOR_IN_NOTE) && $object->user_author_id > 0) { - $tmpuser=new User($this->db); + $tmpuser = new User($this->db); $tmpuser->fetch($object->user_author_id); - $notetoshow.='Affaire suivi par '.$tmpuser->getFullName($langs); - if ($tmpuser->email) $notetoshow.=', Mail: '.$tmpuser->email; - if ($tmpuser->office_phone) $notetoshow.=', Tel: '.$tmpuser->office_phone; + $notetoshow .= $langs->trans("CaseFollowedBy").' '.$tmpuser->getFullName($langs); + if ($tmpuser->email) $notetoshow .= ', Mail: '.$tmpuser->email; + if ($tmpuser->office_phone) $notetoshow .= ', Tel: '.$tmpuser->office_phone; } + $tab_height = $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforsignature - $heightforfooter; + $pagenb = $pdf->getPage(); if ($notetoshow) { @@ -529,7 +540,6 @@ class pdf_cyan extends ModelePDFPropales $posyafter = $tab_top_newpage; } } - $tab_height = $tab_height - $height_note; $tab_top = $posyafter + 6; } @@ -551,35 +561,35 @@ class pdf_cyan extends ModelePDFPropales $nexY = $tab_top + $this->tabTitleHeight + 2; // Loop on each lines - $pageposbeforeprintlines=$pdf->getPage(); + $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; - if($this->getColumnStatus('photo')) + if ($this->getColumnStatus('photo')) { // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot))) // If photo too high, we moved completely on new page + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposbefore+1); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; @@ -593,43 +603,42 @@ class pdf_cyan extends ModelePDFPropales if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } } // Description of product line - if($this->getColumnStatus('desc')) + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot))) // There is no space left for total+free text + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -641,22 +650,22 @@ class pdf_cyan extends ModelePDFPropales { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description or photo were moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // VAT Rate if ($this->getColumnStatus('vat')) @@ -718,59 +727,59 @@ class pdf_cyan extends ModelePDFPropales 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails ); - $reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; - if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage; + if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -867,41 +876,41 @@ class pdf_cyan extends ModelePDFPropales $product = new Product($this->db); $product->fetch($line->fk_product); - if ($product->entity!=$conf->entity) { - $entity_product_file=$product->entity; + if ($product->entity != $conf->entity) { + $entity_product_file = $product->entity; } else { - $entity_product_file=$conf->entity; + $entity_product_file = $conf->entity; } // If PDF is selected and file is not empty if (count($filetomerge->lines) > 0) { foreach ($filetomerge->lines as $linefile) { - if (! empty($linefile->id) && ! empty($linefile->file_name)) { - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($linefile->id) && !empty($linefile->file_name)) { + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - if (! empty($conf->product->enabled)) { - $filetomerge_dir = $conf->product->multidir_output[$entity_product_file] . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos"; - } elseif (! empty($conf->service->enabled)) { - $filetomerge_dir = $conf->service->multidir_output[$entity_product_file] . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos"; + if (!empty($conf->product->enabled)) { + $filetomerge_dir = $conf->product->multidir_output[$entity_product_file].'/'.get_exdir($product->id, 2, 0, 0, $product, 'product').$product->id."/photos"; + } elseif (!empty($conf->service->enabled)) { + $filetomerge_dir = $conf->service->multidir_output[$entity_product_file].'/'.get_exdir($product->id, 2, 0, 0, $product, 'product').$product->id."/photos"; } } else { - if (! empty($conf->product->enabled)) { - $filetomerge_dir = $conf->product->multidir_output[$entity_product_file] . '/' . get_exdir(0, 0, 0, 0, $product, 'product') . dol_sanitizeFileName($product->ref); - } elseif (! empty($conf->service->enabled)) { - $filetomerge_dir = $conf->service->multidir_output[$entity_product_file] . '/' . get_exdir(0, 0, 0, 0, $product, 'product') . dol_sanitizeFileName($product->ref); + if (!empty($conf->product->enabled)) { + $filetomerge_dir = $conf->product->multidir_output[$entity_product_file].'/'.get_exdir(0, 0, 0, 0, $product, 'product').dol_sanitizeFileName($product->ref); + } elseif (!empty($conf->service->enabled)) { + $filetomerge_dir = $conf->service->multidir_output[$entity_product_file].'/'.get_exdir(0, 0, 0, 0, $product, 'product').dol_sanitizeFileName($product->ref); } } - dol_syslog(get_class($this) . ':: upload_dir=' . $filetomerge_dir, LOG_DEBUG); + dol_syslog(get_class($this).':: upload_dir='.$filetomerge_dir, LOG_DEBUG); - $infile = $filetomerge_dir . '/' . $linefile->file_name; + $infile = $filetomerge_dir.'/'.$linefile->file_name; if (file_exists($infile) && is_readable($infile)) { $pagecount = $pdf->setSourceFile($infile); - for($i = 1; $i <= $pagecount; $i ++) { + for ($i = 1; $i <= $pagecount; $i++) { $tplIdx = $pdf->importPage($i); - if ($tplIdx!==false) { + if ($tplIdx !== false) { $s = $pdf->getTemplatesize($tplIdx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); $pdf->useTemplate($tplIdx); @@ -923,31 +932,31 @@ class pdf_cyan extends ModelePDFPropales //Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "PROP_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "PROP_OUTPUTDIR"); return 0; } } @@ -972,17 +981,17 @@ class pdf_cyan extends ModelePDFPropales * @param Object $object Object to show * @param int $posy Y * @param Translate $outputlangs Langs object - * @return void + * @return int Pos y */ public function drawInfoTable(&$pdf, $object, $posy, $outputlangs) { - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('', '', $default_font_size - 1); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); @@ -1157,6 +1166,7 @@ class pdf_cyan extends ModelePDFPropales protected function drawTotalTable(&$pdf, $object, $deja_regle, $posy, $outputlangs) { global $conf, $mysoc; + $default_font_size = pdf_getPDFFontSize($outputlangs); $tab2_top = $posy; @@ -1174,12 +1184,19 @@ class pdf_cyan extends ModelePDFPropales $useborder = 0; $index = 0; + $outputlangsbis = null; + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + } + // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalHT") : ''), 0, 'L', 1); - $total_ht = ($conf->multicurrency->enabled && $object->mylticurrency_tx != 1 ? $object->multicurrency_total_ht : $object->total_ht); + $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); $pdf->SetXY($col2x, $tab2_top + 0); $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (!empty($object->remise) ? $object->remise : 0), 0, $outputlangs), 0, 'R', 1); @@ -1201,28 +1218,29 @@ class pdf_cyan extends ModelePDFPropales //Local tax 1 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1233,13 +1251,13 @@ class pdf_cyan extends ModelePDFPropales //Local tax 2 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; @@ -1248,15 +1266,16 @@ class pdf_cyan extends ModelePDFPropales $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1280,7 +1299,8 @@ class pdf_cyan extends ModelePDFPropales $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalVAT", $mysoc->country_code) : ''); + $totalvat .= ' '; $totalvat .= vatrate($tvakey, 1).$tvacompl; $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); @@ -1292,11 +1312,11 @@ class pdf_cyan extends ModelePDFPropales //Local tax 1 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1305,16 +1325,17 @@ class pdf_cyan extends ModelePDFPropales $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : ''); + $totalvat .= ' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); } @@ -1324,11 +1345,11 @@ class pdf_cyan extends ModelePDFPropales //Local tax 2 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { // retrieve global local tax if ($tvakey != 0) // On affiche pas taux 0 @@ -1338,16 +1359,17 @@ class pdf_cyan extends ModelePDFPropales $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : ''); + $totalvat .= ' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1361,7 +1383,7 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalTTC") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($total_ttc, 0, $outputlangs), $useborder, 'R', 1); @@ -1370,6 +1392,7 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetTextColor(0, 0, 0); + $resteapayer = 0; /* $resteapayer = $object->total_ttc - $deja_regle; if (! empty($object->paye)) $resteapayer=0; @@ -1380,7 +1403,7 @@ class pdf_cyan extends ModelePDFPropales $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("AlreadyPaid") : ''), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle, 0, $outputlangs), 0, 'R', 0); @@ -1405,7 +1428,7 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("RemainderToPay") : ''), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); @@ -1450,24 +1473,25 @@ class pdf_cyan extends ModelePDFPropales if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter - + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - if (empty($hidetop)){ - $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -1485,10 +1509,8 @@ class pdf_cyan extends ModelePDFPropales { global $conf, $langs; - $outputlangs->load("main"); - $outputlangs->load("bills"); - $outputlangs->load("propal"); - $outputlangs->load("companies"); + // Load traductions files required by page + $outputlangs->loadLangs(array("main", "propal", "companies", "bills")); $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1503,8 +1525,8 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); @@ -1514,7 +1536,7 @@ class pdf_cyan extends ModelePDFPropales if ($this->emetteur->logo) { $logodir = $conf->mycompany->dir_output; - if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; @@ -1524,8 +1546,8 @@ class pdf_cyan extends ModelePDFPropales } if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { diff --git a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php index cafacc6ac57..2a7e0cf287f 100644 --- a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php +++ b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php @@ -1,7 +1,7 @@ * Copyright (C) 2016 Charlie Benke - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-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 @@ -100,7 +100,7 @@ class doc_generic_odt extends ModeleThirdPartyDoc $form = new Form($this->db); $texte = $this->description.".
\n"; - $texte .= ''; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= ''; @@ -160,7 +160,11 @@ class doc_generic_odt extends ModeleThirdPartyDoc } $texte .= ''; } - + // Add input to upload a new template file. + $texte .= '
'.$langs->trans("UploadNewTemplate").' '; + $texte .= ''; + $texte .= ''; + $texte .= '
'; $texte .= '
'; diff --git a/htdocs/core/modules/supplier_invoice/pdf/index.html b/htdocs/core/modules/supplier_invoice/doc/index.html similarity index 100% rename from htdocs/core/modules/supplier_invoice/pdf/index.html rename to htdocs/core/modules/supplier_invoice/doc/index.html diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php similarity index 99% rename from htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php rename to htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php index 26329ac889f..a484343b1c0 100644 --- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php @@ -20,7 +20,7 @@ */ /** - * \file htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php + * \file htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php * \ingroup fournisseur * \brief Class file to generate the supplier invoices with the canelle model */ @@ -152,8 +152,6 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $this->option_codeproduitservice = 1; // Affiche code produit-service $this->option_multilang = 1; // Dispo en plusieurs langues - $this->franchise = !$mysoc->tva_assuj; - // Define column position $this->posxdesc = $this->marge_gauche + 1; $this->posxtva = 112; @@ -430,7 +428,6 @@ class pdf_canelle extends ModelePDFSuppliersInvoices else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; diff --git a/htdocs/core/modules/supplier_order/pdf/doc_generic_supplier_order_odt.modules.php b/htdocs/core/modules/supplier_order/doc/doc_generic_supplier_order_odt.modules.php similarity index 99% rename from htdocs/core/modules/supplier_order/pdf/doc_generic_supplier_order_odt.modules.php rename to htdocs/core/modules/supplier_order/doc/doc_generic_supplier_order_odt.modules.php index e3c46904c1f..c71fe8f59ec 100644 --- a/htdocs/core/modules/supplier_order/pdf/doc_generic_supplier_order_odt.modules.php +++ b/htdocs/core/modules/supplier_order/doc/doc_generic_supplier_order_odt.modules.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/core/modules/supplier_order/pdf/doc_generic_supplier_order_odt.modules.php + * \file htdocs/core/modules/supplier_order/doc/doc_generic_supplier_order_odt.modules.php * \ingroup commande * \brief File of class to build ODT documents for supplier orders */ diff --git a/htdocs/core/modules/supplier_order/pdf/index.html b/htdocs/core/modules/supplier_order/doc/index.html similarity index 100% rename from htdocs/core/modules/supplier_order/pdf/index.html rename to htdocs/core/modules/supplier_order/doc/index.html diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_cornas.modules.php b/htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php similarity index 83% rename from htdocs/core/modules/supplier_order/pdf/pdf_cornas.modules.php rename to htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php index 6d3fe584eb3..1c266ae89b6 100644 --- a/htdocs/core/modules/supplier_order/pdf/pdf_cornas.modules.php +++ b/htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/core/modules/supplier_order/pdf/pdf_cornas.modules.php + * \file htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php * \ingroup fournisseur * \brief File of class to generate suppliers orders from cornas model */ @@ -71,7 +71,7 @@ class pdf_cornas extends ModelePDFSuppliersOrders * Dolibarr version of the loaded document * @var string */ - public $version = 'development'; + public $version = 'dolibarr'; /** * @var int page_largeur @@ -153,8 +153,6 @@ class pdf_cornas extends ModelePDFSuppliersOrders $this->option_freetext = 1; // Support add of a personalised text $this->option_draft_watermark = 1; // Support add of a watermark on drafts - $this->franchise = !$mysoc->tva_assuj; - // Get source company $this->emetteur = $mysoc; if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined @@ -185,57 +183,64 @@ class pdf_cornas extends ModelePDFSuppliersOrders public function write_file($object, $outputlangs = '', $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$hookmanager,$mysoc,$nblines; + global $user, $langs, $conf, $hookmanager, $mysoc, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load translation files required by the page $outputlangs->loadLangs(array("main", "orders", "companies", "bills", "dict", "products")); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "orders", "companies", "bills", "dict", "products")); + } + $nblines = count($object->lines); - $hidetop=0; - if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){ - $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; } // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); - if (! empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE)) + $realpatharray = array(); + if (!empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE)) { - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto = new Product($this->db); $objphoto->fetch($object->lines[$i]->fk_product); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/"; + $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/"; $dir = $conf->product->dir_output.'/'.$pdir; } else { - $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; $dir = $conf->product->dir_output.'/'.$pdir; } - $realpath=''; + $realpath = ''; foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { - $filename=$obj['photo']; + $filename = $obj['photo']; //if ($obj['photo_vignette']) $filename='thumbs/'.$obj['photo_vignette']; $realpath = $dir.$filename; break; } - if ($realpath) $realpatharray[$i]=$realpath; + if ($realpath) $realpatharray[$i] = $realpath; } } - if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; + if (count($realpatharray) == 0) $this->posxpicture = $this->posxtva; if ($conf->fournisseur->commande->dir_output) { @@ -274,24 +279,24 @@ class pdf_cornas extends ModelePDFSuppliersOrders if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $nblines = count($object->lines); - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $heightforinfotot = 50; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $heightforinfotot = 50; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -328,8 +333,6 @@ class pdf_cornas extends ModelePDFSuppliersOrders } } - - // New page $pdf->AddPage(); if (!empty($tplidx)) $pdf->useTemplate($tplidx); @@ -351,28 +354,28 @@ class pdf_cornas extends ModelePDFSuppliersOrders $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } } // Affiche notes - $notetoshow=empty($object->note_public)?'':$object->note_public; + $notetoshow = empty($object->note_public) ? '' : $object->note_public; $pagenb = $pdf->getPage(); if ($notetoshow) { - $tab_width = $this->page_largeur-$this->marge_gauche-$this->marge_droite; + $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; $pageposbeforenote = $pagenb; - $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object); $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); @@ -494,33 +497,33 @@ class pdf_cornas extends ModelePDFSuppliersOrders $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); // Loop on each lines - $pageposbeforeprintlines=$pdf->getPage(); + $pageposbeforeprintlines = $pdf->getPage(); $pagenb = $pageposbeforeprintlines; - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; // We start with Photo of product line - if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) // If photo too high, we moved completely on new page + if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposbefore+1); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; @@ -533,69 +536,68 @@ class pdf_cornas extends ModelePDFSuppliersOrders if (!empty($imglinesize['width']) && !empty($imglinesize['height'])) { - $curX = $this->posxpicture-1; - $pdf->Image($realpatharray[$i], $curX + (($this->posxtva-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $curX = $this->posxpicture - 1; + $pdf->Image($realpatharray[$i], $curX + (($this->posxtva - $this->posxpicture - $imglinesize['width']) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } // Description of product line - $curX = $this->posxdesc-1; - $showpricebeforepagebreak=1; + $curX = $this->posxdesc - 1; + $showpricebeforepagebreak = 1; - if($this->getColumnStatus('desc')) + if ($this->getColumnStatus('desc')) { $pdf->startTransaction(); pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - - // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) - $showpricebeforepagebreak = 1; - else - $showpricebeforepagebreak = 0; + // Allows data in the first page if description is long enough to break in multiples pages + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + $showpricebeforepagebreak = 1; + else + $showpricebeforepagebreak = 0; } } else // No pagebreak { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // VAT Rate if ($this->getColumnStatus('vat')) @@ -648,7 +650,7 @@ class pdf_cornas extends ModelePDFSuppliersOrders } - $parameters=array( + $parameters = array( 'object' => $object, 'i' => $i, 'pdf' =>& $pdf, @@ -657,58 +659,58 @@ class pdf_cornas extends ModelePDFSuppliersOrders 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails ); - $reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if (! empty($object->remise_percent)) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if (! empty($object->remise_percent)) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if (! empty($object->remise_percent)) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if (!empty($object->remise_percent)) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if (!empty($object->remise_percent)) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if (!empty($object->remise_percent)) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; - if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage; + if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -781,31 +783,31 @@ class pdf_cornas extends ModelePDFSuppliersOrders // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); return 0; } } @@ -840,11 +842,11 @@ class pdf_cornas extends ModelePDFSuppliersOrders protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); @@ -865,11 +867,11 @@ class pdf_cornas extends ModelePDFSuppliersOrders $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_condition_paiement=$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code)!=('PaymentCondition'.$object->cond_reglement_code)?$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code):$outputlangs->convToOutputCharset($object->cond_reglement); - $lib_condition_paiement=str_replace('\n', "\n", $lib_condition_paiement); + $lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement); + $lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement); $pdf->MultiCell(80, 4, $lib_condition_paiement, 0, 'L'); - $posy=$pdf->GetY()+3; + $posy = $pdf->GetY() + 3; } // Show payment mode @@ -1000,7 +1002,7 @@ class pdf_cornas extends ModelePDFSuppliersOrders //Local tax 1 foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; foreach ($localtax_rate as $tvakey => $tvaval) { @@ -1011,15 +1013,15 @@ class pdf_cornas extends ModelePDFSuppliersOrders $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1140,28 +1142,30 @@ class pdf_cornas extends ModelePDFSuppliersOrders if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter foreach ($this->cols as $colKey => $colDef) { - if(!$this->getColumnStatus($colKey)) continue; + if (!$this->getColumnStatus($colKey)) continue; // get title label - $colDef['title']['label'] = !empty($colDef['title']['label'])?$colDef['title']['label']:$outputlangs->transnoentities($colDef['title']['textkey']); + $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); // Add column separator - if(!empty($colDef['border-left'])){ + if (!empty($colDef['border-left'])) { $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); } @@ -1169,13 +1173,13 @@ class pdf_cornas extends ModelePDFSuppliersOrders { $pdf->SetXY($colDef['xStartPos'] + $colDef['title']['padding'][3], $tab_top + $colDef['title']['padding'][0]); - $textWidth = $colDef['width'] - $colDef['title']['padding'][3] -$colDef['title']['padding'][1]; + $textWidth = $colDef['width'] - $colDef['title']['padding'][3] - $colDef['title']['padding'][1]; $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); } } - if (empty($hidetop)){ - $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5); // line takes a position y in 2nd parameter and 4th parameter + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); // line takes a position y in 2nd parameter and 4th parameter } } @@ -1211,19 +1215,19 @@ class pdf_cornas extends ModelePDFSuppliersOrders $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posx=$this->page_largeur-$this->marge_droite-100; - $posy=$this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; + $posy = $this->marge_haute; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -1235,91 +1239,91 @@ class pdf_cornas extends ModelePDFSuppliersOrders } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } $pdf->SetFont('', 'B', $default_font_size + 3); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $title=$outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref); + $title = $outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref); $pdf->MultiCell(100, 3, $title, '', 'R'); - $posy+=1; + $posy += 1; if ($object->ref_supplier) { - $posy+=4; + $posy += 4; $pdf->SetFont('', 'B', $default_font_size); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : " . $outputlangs->convToOutputCharset($object->ref_supplier), '', 'R'); - $posy+=1; + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : ".$outputlangs->convToOutputCharset($object->ref_supplier), '', 'R'); + $posy += 1; } - $pdf->SetFont('', '', $default_font_size -1); + $pdf->SetFont('', '', $default_font_size - 1); - if (! empty($conf->global->PDF_SHOW_PROJECT)) + if (!empty($conf->global->PDF_SHOW_PROJECT)) { $object->fetch_projet(); - if (! empty($object->project->ref)) + if (!empty($object->project->ref)) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $langs->load("projects"); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : " . (empty($object->project->ref)?'':$object->projet->ref), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : ".(empty($object->project->ref) ? '' : $object->projet->ref), '', 'R'); } } - if (! empty($object->date_commande)) + if (!empty($object->date_commande)) { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : " . dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R'); } else { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(255, 0, 0); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderToProcess"), '', 'R'); } $pdf->SetTextColor(0, 0, 60); - $usehourmin='day'; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour'; - if (! empty($object->date_livraison)) + $usehourmin = 'day'; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour'; + if (!empty($object->date_livraison)) { - $posy+=4; - $pdf->SetXY($posx-90, $posy); - $pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : " . dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R'); + $posy += 4; + $pdf->SetXY($posx - 90, $posy); + $pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R'); } if ($object->thirdparty->code_fournisseur) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); } // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { - $usertmp=new User($this->db); + $usertmp = new User($this->db); $usertmp->fetch($arrayidcontact[0]); - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell(100, 3, $langs->trans("BuyerName")." : ".$usertmp->getFullName($langs), '', 'R'); } } - $posy+=1; + $posy += 1; $pdf->SetTextColor(0, 0, 60); $top_shift = 0; @@ -1374,9 +1378,9 @@ class pdf_cornas extends ModelePDFSuppliersOrders - // If BILLING contact defined on order, we use it + // If CUSTOMER contact defined on order, we use it. Note: Even if this is a supplier object, the code for external contat that follow order is 'CUSTOMER' $usecontact = false; - $arrayidcontact = $object->getIdContact('external', 'BILLING'); + $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); if (count($arrayidcontact) > 0) { $usecontact = true; @@ -1671,10 +1675,10 @@ class pdf_cornas extends ModelePDFSuppliersOrders uasort($this->cols, array($this, 'columnSort')); // Positionning - $curX = $this->page_largeur-$this->marge_droite; // start from right + $curX = $this->page_largeur - $this->marge_droite; // start from right // Array width - $arrayWidth = $this->page_largeur-$this->marge_droite-$this->marge_gauche; + $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; // Count flexible column $totalDefinedColWidth = 0; @@ -1823,16 +1827,16 @@ class pdf_cornas extends ModelePDFSuppliersOrders { global $hookmanager; - $parameters=array( + $parameters = array( 'curY' =>& $curY, 'columnText' => $columnText, 'colKey' => $colKey ); - $reshook=$hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook + $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; + if (empty($columnText)) return; $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position $colDef = $this->cols[$colKey]; $pdf->MultiCell($this->getColumnContentWidth($colKey), 2, $columnText, '', $colDef['content']['align']); diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php similarity index 62% rename from htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php rename to htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php index 5bad5b6be24..e4cb8f53e66 100644 --- a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php +++ b/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php + * \file htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php * \ingroup fournisseur * \brief File of class to generate suppliers orders from muscadet model */ @@ -129,72 +129,70 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $this->db = $db; $this->name = "muscadet"; - $this->description = $langs->trans('SuppliersCommandModel'); + $this->description = $langs->trans('SuppliersCommandModelMuscadet'); // Page size for A4 format $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION - $this->option_modereg = 1; // Affiche mode reglement - $this->option_condreg = 1; // Affiche conditions reglement - $this->option_codeproduitservice = 1; // Affiche code produit-service - $this->option_multilang = 1; // Dispo en plusieurs langues - $this->option_escompte = 0; // Affiche si il y a eu escompte - $this->option_credit_note = 0; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; // Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Affiche logo + $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION + $this->option_modereg = 1; // Affiche mode reglement + $this->option_condreg = 1; // Affiche conditions reglement + $this->option_codeproduitservice = 1; // Affiche code produit-service + $this->option_multilang = 1; // Dispo en plusieurs langues + $this->option_escompte = 0; // Affiche si il y a eu escompte + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; - $this->posxdiscount=162; - $this->postotalht=174; + $this->posxdesc = $this->marge_gauche + 1; + $this->posxdiscount = 162; + $this->postotalht = 174; if ($conf->global->PRODUCT_USE_UNITS) { - $this->posxtva=95; - $this->posxup=114; - $this->posxqty=132; - $this->posxunit=147; + $this->posxtva = 95; + $this->posxup = 114; + $this->posxqty = 132; + $this->posxunit = 147; } else { - $this->posxtva=110; - $this->posxup=126; - $this->posxqty=145; - $this->posxunit=162; + $this->posxtva = 110; + $this->posxup = 126; + $this->posxqty = 145; + $this->posxunit = 162; } - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxup = $this->posxtva; // posxtva is picture position reference - $this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxup = $this->posxtva; // posxtva is picture position reference + $this->posxpicture = $this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images if ($this->page_largeur < 210) // To work with US executive format { - $this->posxpicture-=20; - $this->posxtva-=20; - $this->posxup-=20; - $this->posxqty-=20; - $this->posxunit-=20; - $this->posxdiscount-=20; - $this->postotalht-=20; + $this->posxpicture -= 20; + $this->posxtva -= 20; + $this->posxup -= 20; + $this->posxqty -= 20; + $this->posxunit -= 20; + $this->posxdiscount -= 20; + $this->postotalht -= 20; } - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } @@ -213,11 +211,11 @@ class pdf_muscadet extends ModelePDFSuppliersOrders public function write_file($object, $outputlangs = '', $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$hookmanager,$mysoc,$nblines; + global $user, $langs, $conf, $hookmanager, $mysoc, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load translation files required by the page $outputlangs->loadLangs(array("main", "orders", "companies", "bills", "dict", "products")); @@ -225,40 +223,40 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $nblines = count($object->lines); // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); - if (! empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE)) + $realpatharray = array(); + if (!empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE)) { - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto = new Product($this->db); $objphoto->fetch($object->lines[$i]->fk_product); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/"; + $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/"; $dir = $conf->product->dir_output.'/'.$pdir; } else { - $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; $dir = $conf->product->dir_output.'/'.$pdir; } - $realpath=''; + $realpath = ''; foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { - $filename=$obj['photo']; + $filename = $obj['photo']; //if ($obj['photo_vignette']) $filename='thumbs/'.$obj['photo_vignette']; $realpath = $dir.$filename; break; } - if ($realpath) $realpatharray[$i]=$realpath; + if ($realpath) $realpatharray[$i] = $realpath; } } - if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; + if (count($realpatharray) == 0) $this->posxpicture = $this->posxtva; if ($conf->fournisseur->commande->dir_output) { @@ -274,22 +272,22 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if ($object->specimen) { $dir = $conf->fournisseur->commande->dir_output; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); $objectrefsupplier = dol_sanitizeFileName($object->ref_supplier); - $dir = $conf->fournisseur->commande->dir_output . '/'. $objectref; - $file = $dir . "/" . $objectref . ".pdf"; - if (! empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir . "/" . $objectref . ($objectrefsupplier?"_".$objectrefsupplier:"").".pdf"; + $dir = $conf->fournisseur->commande->dir_output.'/'.$objectref; + $file = $dir."/".$objectref.".pdf"; + if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir."/".$objectref.($objectrefsupplier ? "_".$objectrefsupplier : "").".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -297,24 +295,24 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $nblines = count($object->lines); - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $heightforinfotot = 50; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $heightforinfotot = 50; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -324,14 +322,14 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -339,12 +337,12 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // Positionne $this->atleastonediscount si on a au moins une remise - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if ($object->lines[$i]->remise_percent) { @@ -354,26 +352,26 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if (empty($this->atleastonediscount)) { $delta = ($this->postotalht - $this->posxdiscount); - $this->posxpicture+=$delta; - $this->posxtva+=$delta; - $this->posxup+=$delta; - $this->posxqty+=$delta; - $this->posxunit+=$delta; - $this->posxdiscount+=$delta; + $this->posxpicture += $delta; + $this->posxtva += $delta; + $this->posxup += $delta; + $this->posxqty += $delta; + $this->posxunit += $delta; + $this->posxdiscount += $delta; // post of fields after are not modified, stay at same position } // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); - $tab_top = 90+$top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42+$top_shift:10); + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); // Incoterm if ($conf->incoterm->enabled) @@ -384,33 +382,33 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); - $height_incoterms=$nexY-$tab_top; + $height_incoterms = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } } // Affiche notes - if (! empty($object->note_public)) + if (!empty($object->note_public)) { $tab_top -= 2; $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($object->note_public), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($object->note_public), 0, 1); $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } $iniY = $tab_top + 7; @@ -418,36 +416,36 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $nexY = $tab_top + 7; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; // We start with Photo of product line - if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) // If photo too high, we moved completely on new page + if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposbefore+1); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -455,49 +453,48 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if (!empty($imglinesize['width']) && !empty($imglinesize['height'])) { - $curX = $this->posxpicture-1; - $pdf->Image($realpatharray[$i], $curX + (($this->posxtva-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $curX = $this->posxpicture - 1; + $pdf->Image($realpatharray[$i], $curX + (($this->posxtva - $this->posxpicture - $imglinesize['width']) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } // Description of product line - $curX = $this->posxdesc-1; - $showpricebeforepagebreak=1; + $curX = $this->posxdesc - 1; + $showpricebeforepagebreak = 1; $pdf->startTransaction(); if ($posYAfterImage > 0) { - $descWidth = $this->posxpicture-$curX; + $descWidth = $this->posxpicture - $curX; } else { - $descWidth = $this->posxtva-$curX; + $descWidth = $this->posxtva - $curX; } pdf_writelinedesc($pdf, $object, $i, $outputlangs, $descWidth, 3, $curX, $curY, $hideref, $hidedesc, 1); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $descWidth, 3, $curX, $curY, $hideref, $hidedesc, 1); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; @@ -511,42 +508,42 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // VAT Rate if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva-1, 3, $vat_rate, 0, 'R'); + $pdf->MultiCell($this->posxup - $this->posxtva - 1, 3, $vat_rate, 0, 'R'); } // Unit price before discount $up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxup, $curY); - $pdf->MultiCell($this->posxqty-$this->posxup-0.8, 3, $up_excl_tax, 0, 'R', 0); + $pdf->MultiCell($this->posxqty - $this->posxup - 0.8, 3, $up_excl_tax, 0, 'R', 0); // Quantity $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxqty, $curY); - $pdf->MultiCell($this->posxunit-$this->posxqty-0.8, 4, $qty, 0, 'R'); // Enough for 6 chars + $pdf->MultiCell($this->posxunit - $this->posxqty - 0.8, 4, $qty, 0, 'R'); // Enough for 6 chars // Unit - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { $unit = pdf_getlineunit($object, $i, $outputlangs, $hidedetails, $hookmanager); $pdf->SetXY($this->posxunit, $curY); - $pdf->MultiCell($this->posxdiscount-$this->posxunit-0.8, 4, $unit, 0, 'L'); + $pdf->MultiCell($this->posxdiscount - $this->posxunit - 0.8, 4, $unit, 0, 'L'); } // Discount on line @@ -554,63 +551,63 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if ($object->lines[$i]->remise_percent) { $remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails); - $pdf->MultiCell($this->postotalht-$this->posxdiscount-1, 3, $remise_percent, 0, 'R'); + $pdf->MultiCell($this->postotalht - $this->posxdiscount - 1, 3, $remise_percent, 0, 'R'); } // Total HT line $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs); $pdf->SetXY($this->postotalht, $curY); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 3, $total_excl_tax, 0, 'R', 0); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $total_excl_tax, 0, 'R', 0); // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if (! empty($object->remise_percent)) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if (! empty($object->remise_percent)) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if (! empty($object->remise_percent)) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if (!empty($object->remise_percent)) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if (!empty($object->remise_percent)) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if (!empty($object->remise_percent)) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; - if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage; + if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -627,10 +624,10 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -643,7 +640,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -653,24 +650,24 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if ($pagenb == 1) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0, $object->multicurrency_code); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Affiche zone infos - $posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); // Affiche zone totaux - $posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); // Affiche zone versements if ($deja_regle || $amount_credit_notes_included || $amount_deposits_included) { - $posy=$this->_tableau_versements($pdf, $object, $posy, $outputlangs); + $posy = $this->_tableau_versements($pdf, $object, $posy, $outputlangs); } // Pied de page @@ -683,31 +680,31 @@ class pdf_muscadet extends ModelePDFSuppliersOrders // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); return 0; } } @@ -742,20 +739,20 @@ class pdf_muscadet extends ModelePDFSuppliersOrders protected function _tableau_info(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); // If France, show VAT mention if not applicable - if ($this->emetteur->country_code == 'FR' && $this->franchise == 1) + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { $pdf->SetFont('', 'B', $default_font_size - 2); $pdf->SetXY($this->marge_gauche, $posy); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("VATIsNotUsedForInvoice"), 0, 'L', 0); - $posy=$pdf->GetY()+4; + $posy = $pdf->GetY() + 4; } - $posxval=52; + $posxval = 52; // Show payments conditions if (!empty($object->cond_reglement_code) || $object->cond_reglement) @@ -767,11 +764,11 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_condition_paiement=$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code)!=('PaymentCondition'.$object->cond_reglement_code)?$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code):$outputlangs->convToOutputCharset($object->cond_reglement); - $lib_condition_paiement=str_replace('\n', "\n", $lib_condition_paiement); + $lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement); + $lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement); $pdf->MultiCell(80, 4, $lib_condition_paiement, 0, 'L'); - $posy=$pdf->GetY()+3; + $posy = $pdf->GetY() + 3; } // Show payment mode @@ -784,10 +781,10 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_mode_reg=$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code)!=('PaymentType'.$object->mode_reglement_code)?$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code):$outputlangs->convToOutputCharset($object->mode_reglement); + $lib_mode_reg = $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) != ('PaymentType'.$object->mode_reglement_code) ? $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) : $outputlangs->convToOutputCharset($object->mode_reglement); $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } @@ -809,7 +806,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders protected function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs) { // phpcs:enable - global $conf,$mysoc; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -821,27 +818,27 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $col1x = 120; $col2x = 170; if ($this->page_largeur < 210) // To work with US executive format { - $col2x-=20; + $col2x -= 20; } $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); - $useborder=0; + $useborder = 0; $index = 0; // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); $pdf->SetXY($col2x, $tab2_top + 0); - $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (! empty($object->remise)?$object->remise:0)), 0, 'R', 1); + $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (!empty($object->remise) ? $object->remise : 0)), 0, 'R', 1); // Show VAT by rates and total $pdf->SetFillColor(248, 248, 248); - $this->atleastoneratenotnull=0; - foreach($this->tva as $tvakey => $tvaval) + $this->atleastoneratenotnull = 0; + foreach ($this->tva as $tvakey => $tvaval) { if ($tvakey > 0) // On affiche pas taux 0 { @@ -850,47 +847,47 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; - $totalvat.=vatrate($tvakey, 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat .= vatrate($tvakey, 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval), 0, 'R', 1); } } - if (! $this->atleastoneratenotnull) // If no vat at all + if (!$this->atleastoneratenotnull) // If no vat at all { $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_tva), 0, 'R', 1); // Total LocalTax1 - if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on' && $object->total_localtax1>0) + if (!empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION == 'localtax1on' && $object->total_localtax1 > 0) { $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_localtax1), $useborder, 'R', 1); } // Total LocalTax2 - if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on' && $object->total_localtax2>0) + if (!empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION == 'localtax2on' && $object->total_localtax2 > 0) { $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_localtax2), $useborder, 'R', 1); } @@ -900,11 +897,11 @@ class pdf_muscadet extends ModelePDFSuppliersOrders //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ //Local tax 1 - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -913,15 +910,15 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -932,11 +929,11 @@ class pdf_muscadet extends ModelePDFSuppliersOrders //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ //Local tax 2 - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -945,15 +942,15 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval), 0, 'R', 1); @@ -967,7 +964,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); $total_ttc = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ttc : $object->total_ttc; $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); @@ -975,13 +972,13 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetFont('', '', $default_font_size - 1); $pdf->SetTextColor(0, 0, 0); - $creditnoteamount=0; - $depositsamount=0; + $creditnoteamount = 0; + $depositsamount = 0; //$creditnoteamount=$object->getSumCreditNotesUsed(); //$depositsamount=$object->getSumDepositsUsed(); //print "x".$creditnoteamount."-".$depositsamount;exit; $resteapayer = price2num($total_ttc - $deja_regle - $creditnoteamount - $depositsamount, 'MT'); - if (! empty($object->paye)) $resteapayer=0; + if (!empty($object->paye)) $resteapayer = 0; if ($deja_regle > 0) { @@ -989,7 +986,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle), 0, 'R', 0); @@ -997,7 +994,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer), $useborder, 'R', 1); @@ -1029,8 +1026,8 @@ class pdf_muscadet extends ModelePDFSuppliersOrders global $conf; // Force to disable hidetop and hidebottom - $hidebottom=0; - if ($hidetop) $hidetop=-1; + $hidebottom = 0; + if ($hidetop) $hidetop = -1; $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1042,24 +1039,24 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5); // line takes a position y in 2nd parameter and 4th parameter + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); // line takes a position y in 2nd parameter and 4th parameter - $pdf->SetXY($this->posxdesc-1, $tab_top+1); + $pdf->SetXY($this->posxdesc - 1, $tab_top + 1); $pdf->MultiCell(108, 2, $outputlangs->transnoentities("Designation"), '', 'L'); } @@ -1068,26 +1065,26 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->line($this->posxtva, $tab_top, $this->posxtva, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxtva-3, $tab_top+1); - $pdf->MultiCell($this->posxup-$this->posxtva+3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); + $pdf->SetXY($this->posxtva - 3, $tab_top + 1); + $pdf->MultiCell($this->posxup - $this->posxtva + 3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); } } $pdf->line($this->posxup, $tab_top, $this->posxup, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxup-1, $tab_top+1); - $pdf->MultiCell($this->posxqty-$this->posxup-1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); + $pdf->SetXY($this->posxup - 1, $tab_top + 1); + $pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); } - $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height); + $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxqty-1, $tab_top+1); - $pdf->MultiCell($this->posxunit-$this->posxqty-1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); + $pdf->SetXY($this->posxqty - 1, $tab_top + 1); + $pdf->MultiCell($this->posxunit - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); } - if($conf->global->PRODUCT_USE_UNITS) { + if ($conf->global->PRODUCT_USE_UNITS) { $pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height); if (empty($hidetop)) { $pdf->SetXY($this->posxunit - 1, $tab_top + 1); @@ -1095,13 +1092,13 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } } - $pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height); + $pdf->line($this->posxdiscount - 1, $tab_top, $this->posxdiscount - 1, $tab_top + $tab_height); if (empty($hidetop)) { if ($this->atleastonediscount) { - $pdf->SetXY($this->posxdiscount-1, $tab_top+1); - $pdf->MultiCell($this->postotalht-$this->posxdiscount+1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); + $pdf->SetXY($this->posxdiscount - 1, $tab_top + 1); + $pdf->MultiCell($this->postotalht - $this->posxdiscount + 1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); } } @@ -1111,7 +1108,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } if (empty($hidetop)) { - $pdf->SetXY($this->postotalht-1, $tab_top+1); + $pdf->SetXY($this->postotalht - 1, $tab_top + 1); $pdf->MultiCell(30, 2, $outputlangs->transnoentities("TotalHTShort"), '', 'C'); } } @@ -1148,19 +1145,19 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posx=$this->page_largeur-$this->marge_droite-100; - $posy=$this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; + $posy = $this->marge_haute; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -1172,91 +1169,91 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } $pdf->SetFont('', 'B', $default_font_size + 3); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $title=$outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref); + $title = $outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref); $pdf->MultiCell(100, 3, $title, '', 'R'); - $posy+=1; + $posy += 1; if ($object->ref_supplier) { - $posy+=4; + $posy += 4; $pdf->SetFont('', 'B', $default_font_size); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : " . $outputlangs->convToOutputCharset($object->ref_supplier), '', 'R'); - $posy+=1; + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : ".$outputlangs->convToOutputCharset($object->ref_supplier), '', 'R'); + $posy += 1; } - $pdf->SetFont('', '', $default_font_size -1); + $pdf->SetFont('', '', $default_font_size - 1); - if (! empty($conf->global->PDF_SHOW_PROJECT)) + if (!empty($conf->global->PDF_SHOW_PROJECT)) { $object->fetch_projet(); - if (! empty($object->project->ref)) + if (!empty($object->project->ref)) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $langs->load("projects"); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : " . (empty($object->project->ref)?'':$object->projet->ref), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : ".(empty($object->project->ref) ? '' : $object->projet->ref), '', 'R'); } } - if (! empty($object->date_commande)) + if (!empty($object->date_commande)) { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : " . dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R'); } else { - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(255, 0, 0); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderToProcess"), '', 'R'); } $pdf->SetTextColor(0, 0, 60); - $usehourmin='day'; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour'; - if (! empty($object->date_livraison)) + $usehourmin = 'day'; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour'; + if (!empty($object->date_livraison)) { - $posy+=4; - $pdf->SetXY($posx-90, $posy); - $pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : " . dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R'); + $posy += 4; + $pdf->SetXY($posx - 90, $posy); + $pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R'); } if ($object->thirdparty->code_fournisseur) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); } // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { - $usertmp=new User($this->db); + $usertmp = new User($this->db); $usertmp->fetch($arrayidcontact[0]); - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell(100, 3, $langs->trans("BuyerName")." : ".$usertmp->getFullName($langs), '', 'R'); } } - $posy+=1; + $posy += 1; $pdf->SetTextColor(0, 0, 60); $top_shift = 0; @@ -1271,27 +1268,27 @@ class pdf_muscadet extends ModelePDFSuppliersOrders if ($showaddress) { // Sender properties - $carac_emetteur=''; + $carac_emetteur = ''; // Add internal contact of proposal if defined - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { $object->fetch_user($arrayidcontact[0]); - $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; + $carac_emetteur .= ($carac_emetteur ? "\n" : '').$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender - $posy=42+$top_shift; - $posx=$this->marge_gauche; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80; - $hautcadre=40; + $posy = 42 + $top_shift; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + $hautcadre = 40; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom").":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); @@ -1299,24 +1296,24 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdf->SetTextColor(0, 0, 60); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); // If CUSTOMER contact defined on order, we use it. Note: Even if this is a supplier object, the code for external contat that follow order is 'CUSTOMER' - $usecontact=false; - $arrayidcontact=$object->getIdContact('external', 'CUSTOMER'); + $usecontact = false; + $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); if (count($arrayidcontact) > 0) { - $usecontact=true; - $result=$object->fetch_contact($arrayidcontact[0]); + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); } //Recipient name @@ -1327,26 +1324,26 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $thirdparty = $object->thirdparty; } - $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs); + $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact?$object->contact:''), $usecontact, 'target', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object); // Show recipient - $widthrecbox=100; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=42+$top_shift; - $posx=$this->page_largeur-$this->marge_droite-$widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = 42 + $top_shift; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); @@ -1354,7 +1351,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } @@ -1374,7 +1371,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) { global $conf; - $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; return pdf_pagefoot($pdf, $outputlangs, 'SUPPLIER_ORDER_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); } } diff --git a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php index 836d7c04072..0ad8b391faf 100644 --- a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php +++ b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php @@ -130,49 +130,47 @@ class pdf_standard extends ModelePDFSuppliersPayments // Page size for A4 format $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_multilang = 1; // Dispo en plusieurs langues - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Affiche logo + $this->option_multilang = 1; // Dispo en plusieurs langues // Define column position - $this->posxdate=$this->marge_gauche+1; - $this->posxreffacturefourn=30; - $this->posxreffacture=65; - $this->posxtype=100; - $this->posxtotalht=80; - $this->posxtva=90; - $this->posxtotalttc=180; + $this->posxdate = $this->marge_gauche + 1; + $this->posxreffacturefourn = 30; + $this->posxreffacture = 65; + $this->posxtype = 100; + $this->posxtotalht = 80; + $this->posxtva = 90; + $this->posxtotalttc = 180; //if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup; if ($this->page_largeur < 210) // To work with US executive format { - $this->posxreffacturefourn-=20; - $this->posxreffacture-=20; - $this->posxtype-=20; - $this->posxtotalht-=20; - $this->posxtva-=20; - $this->posxtotalttc-=20; + $this->posxreffacturefourn -= 20; + $this->posxreffacture -= 20; + $this->posxtype -= 20; + $this->posxtotalht -= 20; + $this->posxtva -= 20; + $this->posxtotalttc -= 20; } - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; // Recupere emetteur - $this->emetteur=$mysoc; - if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default if not defined + $this->emetteur = $mysoc; + if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined } @@ -193,9 +191,9 @@ class pdf_standard extends ModelePDFSuppliersPayments // phpcs:enable global $user, $langs, $conf, $mysoc, $hookmanager; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load translation files required by the page $outputlangs->loadLangs(array("main", "suppliers", "companies", "bills", "dict", "products")); @@ -213,12 +211,12 @@ class pdf_standard extends ModelePDFSuppliersPayments $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf,'.MAIN_DB_PREFIX.'facture_fourn as f,'.MAIN_DB_PREFIX.'societe as s'; $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid'; $sql .= ' AND pf.fk_paiementfourn = '.$object->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql) > 0) { - while($objp = $this->db->fetch_object($resql)) { + while ($objp = $this->db->fetch_object($resql)) { $objp->type = $outputlangs->trans('SupplierInvoice'); $object->lines[] = $objp; } @@ -231,22 +229,22 @@ class pdf_standard extends ModelePDFSuppliersPayments if ($object->specimen) { $dir = $conf->fournisseur->payment->dir_output; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); $objectrefsupplier = dol_sanitizeFileName($object->ref_supplier); $dir = $conf->fournisseur->payment->dir_output.'/'.$objectref; - $file = $dir . "/" . $objectref . ".pdf"; - if (! empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir . "/" . $objectref . ($objectrefsupplier?"_".$objectrefsupplier:"").".pdf"; + $file = $dir."/".$objectref.".pdf"; + if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir."/".$objectref.($objectrefsupplier ? "_".$objectrefsupplier : "").".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -254,24 +252,24 @@ class pdf_standard extends ModelePDFSuppliersPayments if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $nblines = count($object->lines); - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $heightforinfotot = 50; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $heightforinfotot = 50; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -281,14 +279,14 @@ class pdf_standard extends ModelePDFSuppliersPayments } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -296,78 +294,77 @@ class pdf_standard extends ModelePDFSuppliersPayments $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); $tab_top = 90; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10); + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10); $tab_height = 130; $tab_height_newpage = 150; // Incoterm $height_incoterms = 0; - $height_note=0; + $height_note = 0; $iniY = $tab_top + 7; $curY = $tab_top + 7; $nexY = $tab_top + 7; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); // Description of product line - $curX = $this->posxdate-1; - $showpricebeforepagebreak=1; + $curX = $this->posxdate - 1; + $showpricebeforepagebreak = 1; $pdf->startTransaction(); //pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,3,$curX,$curY,$hideref,$hidedesc,1); - $pdf->writeHTMLCell($this->posxtva-$curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true); - $pageposafter=$pdf->getPage(); + $pdf->writeHTMLCell($this->posxtva - $curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. //pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,4,$curX,$curY,$hideref,$hidedesc,1); - $pdf->writeHTMLCell($this->posxtva-$curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true); - $posyafter=$pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + $pdf->writeHTMLCell($this->posxtva - $curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -379,54 +376,54 @@ class pdf_standard extends ModelePDFSuppliersPayments } $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description is moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // ref fourn $pdf->SetXY($this->posxreffacturefourn, $curY); - $pdf->MultiCell($this->posxreffacturefourn-$this->posxup-0.8, 3, $object->lines[$i]->ref_supplier, 0, 'L', 0); + $pdf->MultiCell($this->posxreffacturefourn - $this->posxup - 0.8, 3, $object->lines[$i]->ref_supplier, 0, 'L', 0); // ref facture fourn $pdf->SetXY($this->posxreffacture, $curY); - $pdf->MultiCell($this->posxreffacture-$this->posxup-0.8, 3, $object->lines[$i]->ref, 0, 'L', 0); + $pdf->MultiCell($this->posxreffacture - $this->posxup - 0.8, 3, $object->lines[$i]->ref, 0, 'L', 0); // type $pdf->SetXY($this->posxtype, $curY); - $pdf->MultiCell($this->posxtype-$this->posxup-0.8, 3, $object->lines[$i]->type, 0, 'L', 0); + $pdf->MultiCell($this->posxtype - $this->posxup - 0.8, 3, $object->lines[$i]->type, 0, 'L', 0); // Total ht $pdf->SetXY($this->posxtotalht, $curY); - $pdf->MultiCell($this->posxtotalht-$this->posxup-0.8, 3, price($object->lines[$i]->total_ht), 0, 'R', 0); + $pdf->MultiCell($this->posxtotalht - $this->posxup - 0.8, 3, price($object->lines[$i]->total_ht), 0, 'R', 0); // Total tva $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxtva-$this->posxup-0.8, 3, price($object->lines[$i]->total_tva), 0, 'R', 0); + $pdf->MultiCell($this->posxtva - $this->posxup - 0.8, 3, price($object->lines[$i]->total_tva), 0, 'R', 0); // Total TTC line $pdf->SetXY($this->posxtotalttc, $curY); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxtotalttc, 3, price($object->lines[$i]->total_ttc), 0, 'R', 0); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxtotalttc, 3, price($object->lines[$i]->total_ttc), 0, 'R', 0); // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -443,10 +440,10 @@ class pdf_standard extends ModelePDFSuppliersPayments $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -459,7 +456,7 @@ class pdf_standard extends ModelePDFSuppliersPayments $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -469,16 +466,16 @@ class pdf_standard extends ModelePDFSuppliersPayments if ($pagenb == 1) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Affiche zone cheèque - $posy=$this->_tableau_cheque($pdf, $object, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_cheque($pdf, $object, $bottomlasttab, $outputlangs); // Affiche zone totaux //$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); @@ -493,31 +490,31 @@ class pdf_standard extends ModelePDFSuppliersPayments // Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR"); return 0; } } @@ -536,7 +533,7 @@ class pdf_standard extends ModelePDFSuppliersPayments protected function _tableau_cheque(&$pdf, $object, $posy, $outputlangs) { // phpcs:enable - global $conf,$mysoc; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -568,7 +565,7 @@ class pdf_standard extends ModelePDFSuppliersPayments $pdf->MultiCell(150, 4, $object->thirdparty->nom, 0, 'L', 1); $pdf->SetXY($this->page_largeur - $this->marge_droite - 30, $posy); - $pdf->MultiCell(35, 4, str_pad(price($object->montant). ' '.$currency, 18, '*', STR_PAD_LEFT), 0, 'R', 1); + $pdf->MultiCell(35, 4, str_pad(price($object->montant).' '.$currency, 18, '*', STR_PAD_LEFT), 0, 'R', 1); $posy += 10; @@ -598,11 +595,11 @@ class pdf_standard extends ModelePDFSuppliersPayments */ protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '') { - global $conf,$mysoc; + global $conf, $mysoc; // Force to disable hidetop and hidebottom - $hidebottom=0; - if ($hidetop) $hidetop=-1; + $hidebottom = 0; + if ($hidetop) $hidetop = -1; $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -612,7 +609,7 @@ class pdf_standard extends ModelePDFSuppliersPayments $pdf->SetFont('', '', $default_font_size - 2); $titre = strtoupper($mysoc->town).', le '.date("d").' '.$outputlangs->transnoentitiesnoconv(date("F")).' '.date("Y"); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3) - 60, $tab_top-6); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3) - 60, $tab_top - 6); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); @@ -652,19 +649,19 @@ class pdf_standard extends ModelePDFSuppliersPayments $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$mysoc->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$mysoc->logo; if ($mysoc->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -676,7 +673,7 @@ class pdf_standard extends ModelePDFSuppliersPayments } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } /* @@ -746,15 +743,15 @@ class pdf_standard extends ModelePDFSuppliersPayments $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty); // Show payer - $posy=42; - $posx=$this->marge_gauche; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80; - $hautcadre=40; + $posy = 42; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + $hautcadre = 40; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("PayedBy").":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); @@ -762,39 +759,39 @@ class pdf_standard extends ModelePDFSuppliersPayments $pdf->SetTextColor(0, 0, 60); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); // Payed $thirdparty = $object->thirdparty; - $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs); + $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $mysoc, ((!empty($object->contact))?$object->contact:null), $usecontact, 'target', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $mysoc, ((!empty($object->contact)) ? $object->contact : null), $usecontact, 'target', $object); // Show recipient - $widthrecbox=90; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=42; - $posx=$this->page_largeur-$this->marge_droite-$widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = 90; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = 42; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("PayedTo").":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); @@ -802,7 +799,7 @@ class pdf_standard extends ModelePDFSuppliersPayments // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } } @@ -820,7 +817,7 @@ class pdf_standard extends ModelePDFSuppliersPayments protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) { global $conf; - $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; return pdf_pagefoot($pdf, $outputlangs, 'SUPPLIER_INVOICE_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); } } diff --git a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php index 6b57a81af5a..afaf4987e04 100644 --- a/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php +++ b/htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php @@ -130,68 +130,66 @@ class pdf_aurore extends ModelePDFSupplierProposal // Page size for A4 format $this->type = 'pdf'; - $formatarray=pdf_getFormat(); + $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION - $this->option_modereg = 1; // Affiche mode reglement - $this->option_condreg = 1; // Affiche conditions reglement - $this->option_codeproduitservice = 1; // Affiche code produit-service - $this->option_multilang = 1; // Dispo en plusieurs langues - $this->option_escompte = 1; // Affiche si il y a eu escompte - $this->option_credit_note = 1; // Support credit notes - $this->option_freetext = 1; // Support add of a personalised text - $this->option_draft_watermark = 1; //Support add of a watermark on drafts - - $this->franchise=!$mysoc->tva_assuj; + $this->option_logo = 1; // Affiche logo + $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION + $this->option_modereg = 1; // Affiche mode reglement + $this->option_condreg = 1; // Affiche conditions reglement + $this->option_codeproduitservice = 1; // Affiche code produit-service + $this->option_multilang = 1; // Dispo en plusieurs langues + $this->option_escompte = 1; // Affiche si il y a eu escompte + $this->option_credit_note = 1; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; //Support add of a watermark on drafts // Get source company - $this->emetteur=$mysoc; - if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2); // By default, if was not defined + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc=$this->marge_gauche+1; - $this->posxdiscount=162; - $this->postotalht=174; + $this->posxdesc = $this->marge_gauche + 1; + $this->posxdiscount = 162; + $this->postotalht = 174; if ($conf->global->PRODUCT_USE_UNITS) { - $this->posxtva=101; - $this->posxup=118; - $this->posxqty=135; - $this->posxunit=151; + $this->posxtva = 101; + $this->posxup = 118; + $this->posxqty = 135; + $this->posxunit = 151; } else { - $this->posxtva=102; - $this->posxup=126; - $this->posxqty=145; - $this->posxunit=162; + $this->posxtva = 102; + $this->posxup = 126; + $this->posxqty = 145; + $this->posxunit = 162; } - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || ! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxup=$this->posxtva; - $this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || !empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxup = $this->posxtva; + $this->posxpicture = $this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images if ($this->page_largeur < 210) // To work with US executive format { - $this->posxpicture-=20; - $this->posxtva-=20; - $this->posxup-=20; - $this->posxqty-=20; - $this->posxunit-=20; - $this->posxdiscount-=20; - $this->postotalht-=20; + $this->posxpicture -= 20; + $this->posxtva -= 20; + $this->posxup -= 20; + $this->posxqty -= 20; + $this->posxunit -= 20; + $this->posxdiscount -= 20; + $this->postotalht -= 20; } - $this->tva=array(); - $this->localtax1=array(); - $this->localtax2=array(); - $this->atleastoneratenotnull=0; - $this->atleastonediscount=0; + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -209,11 +207,11 @@ class pdf_aurore extends ModelePDFSupplierProposal public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { // phpcs:enable - global $user,$langs,$conf,$mysoc,$db,$hookmanager,$nblines; + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - if (! is_object($outputlangs)) $outputlangs=$langs; + if (!is_object($outputlangs)) $outputlangs = $langs; // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; // Load traductions files required by page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "supplier_proposal")); @@ -221,40 +219,40 @@ class pdf_aurore extends ModelePDFSupplierProposal $nblines = count($object->lines); // Loop on each lines to detect if there is at least one image to show - $realpatharray=array(); - if (! empty($conf->global->MAIN_GENERATE_SUPPLIER_PROPOSAL_WITH_PICTURE)) + $realpatharray = array(); + if (!empty($conf->global->MAIN_GENERATE_SUPPLIER_PROPOSAL_WITH_PICTURE)) { - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if (empty($object->lines[$i]->fk_product)) continue; $objphoto = new Product($this->db); $objphoto->fetch($object->lines[$i]->fk_product); - if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/"; + $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/"; $dir = $conf->product->dir_output.'/'.$pdir; } else { - $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/'; + $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; $dir = $conf->product->dir_output.'/'.$pdir; } - $realpath=''; + $realpath = ''; foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { - $filename=$obj['photo']; + $filename = $obj['photo']; //if ($obj['photo_vignette']) $filename='thumbs/'.$obj['photo_vignette']; $realpath = $dir.$filename; break; } - if ($realpath) $realpatharray[$i]=$realpath; + if ($realpath) $realpatharray[$i] = $realpath; } } - if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; + if (count($realpatharray) == 0) $this->posxpicture = $this->posxtva; if ($conf->supplier_proposal->dir_output) { @@ -266,20 +264,20 @@ class pdf_aurore extends ModelePDFSupplierProposal if ($object->specimen) { $dir = $conf->supplier_proposal->dir_output; - $file = $dir . "/SPECIMEN.pdf"; + $file = $dir."/SPECIMEN.pdf"; } else { $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->supplier_proposal->dir_output . "/" . $objectref; - $file = $dir . "/" . $objectref . ".pdf"; + $dir = $conf->supplier_proposal->dir_output."/".$objectref; + $file = $dir."/".$objectref.".pdf"; } - if (! file_exists($dir)) + if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir); + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return 0; } } @@ -287,23 +285,23 @@ class pdf_aurore extends ModelePDFSupplierProposal if (file_exists($dir)) { // Add pdfgeneration hook - if (! is_object($hookmanager)) + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Create pdf instance - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $heightforinfotot = 50; // Height reserved to output the info and total part - $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) - if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6; + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $heightforinfotot = 50; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; $pdf->SetAutoPageBreak(1, 0); if (class_exists('TCPDF')) @@ -313,14 +311,14 @@ class pdf_aurore extends ModelePDFSupplierProposal } $pdf->SetFont(pdf_getPDFFont($outputlangs)); // Set path to the background PDF File - if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $tplidx = $pdf->importPage(1); } $pdf->Open(); - $pagenb=0; + $pagenb = 0; $pdf->SetDrawColor(128, 128, 128); $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); @@ -328,12 +326,12 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("CommercialAsk")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right // Positionne $this->atleastonediscount si on a au moins une remise - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { if ($object->lines[$i]->remise_percent) { @@ -343,59 +341,59 @@ class pdf_aurore extends ModelePDFSupplierProposal if (empty($this->atleastonediscount)) { $delta = ($this->postotalht - $this->posxdiscount); - $this->posxpicture+=$delta; - $this->posxtva+=$delta; - $this->posxup+=$delta; - $this->posxqty+=$delta; - $this->posxunit+=$delta; - $this->posxdiscount+=$delta; + $this->posxpicture += $delta; + $this->posxtva += $delta; + $this->posxup += $delta; + $this->posxqty += $delta; + $this->posxunit += $delta; + $this->posxdiscount += $delta; // post of fields after are not modified, stay at same position } // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); - $tab_top = 90+$top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42+$top_shift:10); + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); // Affiche notes - $notetoshow=empty($object->note_public)?'':$object->note_public; - if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { // Get first sale rep if (is_object($object->thirdparty)) { - $salereparray=$object->thirdparty->getSalesRepresentatives($user); - $salerepobj=new User($this->db); + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); $salerepobj->fetch($salereparray[0]['id']); - if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); } } if ($notetoshow) { $tab_top -= 2; - $substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); complete_substitutions_array($substitutionarray, $outputlangs, $object); $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($notetoshow), 0, 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($notetoshow), 0, 1); $nexY = $pdf->GetY(); - $height_note=$nexY-$tab_top; + $height_note = $nexY - $tab_top; // Rect takes a length in 3rd parameter $pdf->SetDrawColor(192, 192, 192); - $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); - $tab_top = $nexY+6; + $tab_top = $nexY + 6; } $iniY = $tab_top + 7; @@ -403,36 +401,36 @@ class pdf_aurore extends ModelePDFSupplierProposal $nexY = $tab_top + 7; // Loop on each lines - for ($i = 0 ; $i < $nblines ; $i++) + for ($i = 0; $i < $nblines; $i++) { $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore=$pdf->getPage(); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak=1; - $posYAfterImage=0; - $posYAfterDescription=0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; // We start with Photo of product line - if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) // If photo too high, we moved completely on new page + if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposbefore+1); + $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -440,54 +438,53 @@ class pdf_aurore extends ModelePDFSupplierProposal if (!empty($imglinesize['width']) && !empty($imglinesize['height'])) { - $curX = $this->posxpicture-1; - $pdf->Image($realpatharray[$i], $curX + (($this->posxtva-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + $curX = $this->posxpicture - 1; + $pdf->Image($realpatharray[$i], $curX + (($this->posxtva - $this->posxpicture - $imglinesize['width']) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage=$curY+$imglinesize['height']; + $posYAfterImage = $curY + $imglinesize['height']; } // Description of product line - $curX = $this->posxdesc-1; + $curX = $this->posxdesc - 1; $pdf->startTransaction(); if ($posYAfterImage > 0) { - $descWidth = $this->posxpicture-$curX; + $descWidth = $this->posxpicture - $curX; } else { - $descWidth = $this->posxtva-$curX; + $descWidth = $this->posxtva - $curX; } pdf_writelinedesc($pdf, $object, $i, $outputlangs, $descWidth, 3, $curX, $curY, $hideref, $hidedesc, 1); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); if ($pageposafter > $pageposbefore) // There is a pagebreak { $pdf->rollbackTransaction(true); - $pageposafter=$pageposbefore; + $pageposafter = $pageposbefore; //print $pageposafter.'-'.$pageposbefore;exit; - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. pdf_writelinedesc($pdf, $object, $i, $outputlangs, $descWidth, 3, $curX, $curY, $hideref, $hidedesc); - $pageposafter=$pdf->getPage(); - $posyafter=$pdf->GetY(); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) // There is no space left for total+free text + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text { - if ($i == ($nblines-1)) // No more lines, and no space left to show total, so we create a new page + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page { $pdf->AddPage('', '', true); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $pdf->setPage($pageposafter+1); + $pdf->setPage($pageposafter + 1); } } else { // We found a page break - // Allows data in the first page if description is long enough to break in multiples pages - if(!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; @@ -497,21 +494,21 @@ class pdf_aurore extends ModelePDFSupplierProposal { $pdf->commitTransaction(); } - $posYAfterDescription=$pdf->GetY(); + $posYAfterDescription = $pdf->GetY(); $nexY = $pdf->GetY(); - $pageposafter=$pdf->getPage(); + $pageposafter = $pdf->getPage(); $pdf->setPage($pageposbefore); $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. // We suppose that a too long description or photo were moved completely on next page if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut // VAT Rate /* @@ -532,14 +529,14 @@ class pdf_aurore extends ModelePDFSupplierProposal // Quantity $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); $pdf->SetXY($this->posxqty, $curY); - $pdf->MultiCell($this->posxunit-$this->posxqty-0.8, 4, $qty, 0, 'R'); // Enough for 6 chars + $pdf->MultiCell($this->posxunit - $this->posxqty - 0.8, 4, $qty, 0, 'R'); // Enough for 6 chars // Unit - if($conf->global->PRODUCT_USE_UNITS) + if ($conf->global->PRODUCT_USE_UNITS) { $unit = pdf_getlineunit($object, $i, $outputlangs, $hidedetails, $hookmanager); $pdf->SetXY($this->posxunit, $curY); - $pdf->MultiCell($this->posxdiscount-$this->posxunit-0.8, 4, $unit, 0, 'L'); + $pdf->MultiCell($this->posxdiscount - $this->posxunit - 0.8, 4, $unit, 0, 'L'); } // Discount on line @@ -559,54 +556,54 @@ class pdf_aurore extends ModelePDFSupplierProposal */ // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva; - else $tvaligne=$object->lines[$i]->total_tva; + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; - $localtax1ligne=$object->lines[$i]->total_localtax1; - $localtax2ligne=$object->lines[$i]->total_localtax2; - $localtax1_rate=$object->lines[$i]->localtax1_tx; - $localtax2_rate=$object->lines[$i]->localtax2_tx; - $localtax1_type=$object->lines[$i]->localtax1_type; - $localtax2_type=$object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100; - if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate=(string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; // Retrieve type from database for backward compatibility with old records - if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined - && (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax { - $localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtax1_type = $localtaxtmp_array[0]; $localtax2_type = $localtaxtmp_array[2]; } // retrieve global local tax if ($localtax1_type && $localtax1ligne != 0) - $this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne; + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; if ($localtax2_type && $localtax2ligne != 0) - $this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne; + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*'; - if (! isset($this->tva[$vatrate])) $this->tva[$vatrate]=0; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $this->tva[$vatrate] += $tvaligne; - if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage; + if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage; // Add line - if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80))); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1); + $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1); $pdf->SetLineStyle(array('dash'=>0)); } - $nexY+=2; // Add space between lines + $nexY += 2; // Add space between lines // Detect if some page were added automatically and output _tableau for past pages while ($pagenb < $pageposafter) @@ -623,10 +620,10 @@ class pdf_aurore extends ModelePDFSupplierProposal $this->_pagefoot($pdf, $object, $outputlangs, 1); $pagenb++; $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } - if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak) + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if ($pagenb == 1) { @@ -639,7 +636,7 @@ class pdf_aurore extends ModelePDFSupplierProposal $this->_pagefoot($pdf, $object, $outputlangs, 1); // New page $pdf->AddPage(); - if (! empty($tplidx)) $pdf->useTemplate($tplidx); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); $pagenb++; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); } @@ -649,16 +646,16 @@ class pdf_aurore extends ModelePDFSupplierProposal if ($pagenb == 1) { $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } else { $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0); - $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } // Affiche zone infos - $posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); + $posy = $this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs); // Affiche zone totaux //$posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs); @@ -681,31 +678,31 @@ class pdf_aurore extends ModelePDFSupplierProposal //Add pdfgeneration hook $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = $hookmanager->error; $this->errors = $hookmanager->errors; } - if (! empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; // No error + return 1; // No error } else { - $this->error=$langs->trans("ErrorCanNotCreateDir", $dir); + $this->error = $langs->trans("ErrorCanNotCreateDir", $dir); return 0; } } else { - $this->error=$langs->trans("ErrorConstantNotDefined", "SUPPLIER_PROPOSAL_OUTPUTDIR"); + $this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_PROPOSAL_OUTPUTDIR"); return 0; } } @@ -745,10 +742,10 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetFont('', '', $default_font_size - 1); - $posxval=52; + $posxval = 52; // Show shipping date - if (! empty($object->date_livraison)) + if (!empty($object->date_livraison)) { $outputlangs->load("sendings"); $pdf->SetFont('', 'B', $default_font_size - 2); @@ -757,10 +754,10 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->MultiCell(80, 4, $titre, 0, 'L'); $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $dlp=dol_print_date($object->date_livraison, "daytext", false, $outputlangs, true); + $dlp = dol_print_date($object->date_livraison, "daytext", false, $outputlangs, true); $pdf->MultiCell(80, 4, $dlp, 0, 'L'); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; } else { $outputlangs->load("sendings"); @@ -773,7 +770,7 @@ class pdf_aurore extends ModelePDFSupplierProposal //$dlp=dol_print_date($object->date_livraison,"daytext",false,$outputlangs,true); $pdf->MultiCell(80, 4, $dlp, 0, 'L'); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; } /* PHFAVRE elseif ($object->availability_code || $object->availability) // Show availability conditions @@ -802,14 +799,14 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetFont('', '', $default_font_size - 2); $pdf->SetXY($posxval, $posy); - $lib_condition_paiement=$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code)!=('PaymentCondition'.$object->cond_reglement_code)?$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code):$outputlangs->convToOutputCharset($object->cond_reglement_doc); - $lib_condition_paiement=str_replace('\n', "\n", $lib_condition_paiement); + $lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement_doc); + $lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement); $pdf->MultiCell(80, 4, $lib_condition_paiement, 0, 'L'); - $posy=$pdf->GetY()+3; + $posy = $pdf->GetY() + 3; } - if (! empty($conf->global->SUPPLIER_PROPOSAL_PDF_SHOW_PAYMENTTERMMODE)) + if (!empty($conf->global->SUPPLIER_PROPOSAL_PDF_SHOW_PAYMENTTERMMODE)) { // Show payment mode if ($object->mode_reglement_code @@ -817,24 +814,24 @@ class pdf_aurore extends ModelePDFSupplierProposal && $object->mode_reglement_code != 'VIR') { $pdf->SetFont('', 'B', $default_font_size - 2); - $pdf->SetXY($this->marge_gauche, $posy-2); + $pdf->SetXY($this->marge_gauche, $posy - 2); $titre = $outputlangs->transnoentities("PaymentMode").':'; $pdf->MultiCell(80, 5, $titre, 0, 'L'); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posxval, $posy-2); - $lib_mode_reg=$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code)!=('PaymentType'.$object->mode_reglement_code)?$outputlangs->transnoentities("PaymentType".$object->mode_reglement_code):$outputlangs->convToOutputCharset($object->mode_reglement); + $pdf->SetXY($posxval, $posy - 2); + $lib_mode_reg = $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) != ('PaymentType'.$object->mode_reglement_code) ? $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) : $outputlangs->convToOutputCharset($object->mode_reglement); $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } // Show payment mode CHQ if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'CHQ') { // Si mode reglement non force ou si force a CHQ - if (! empty($conf->global->FACTURE_CHQ_NUMBER)) + if (!empty($conf->global->FACTURE_CHQ_NUMBER)) { - $diffsizetitle=(empty($conf->global->PDF_DIFFSIZE_TITLE)?3:$conf->global->PDF_DIFFSIZE_TITLE); + $diffsizetitle = (empty($conf->global->PDF_DIFFSIZE_TITLE) ? 3 : $conf->global->PDF_DIFFSIZE_TITLE); if ($conf->global->FACTURE_CHQ_NUMBER > 0) { @@ -844,14 +841,14 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', 'B', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $account->proprio), 0, 'L', 0); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', '', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($account->owner_address), 0, 'L', 0); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } } if ($conf->global->FACTURE_CHQ_NUMBER == -1) @@ -859,14 +856,14 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', 'B', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $this->emetteur->name), 0, 'L', 0); - $posy=$pdf->GetY()+1; + $posy = $pdf->GetY() + 1; if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { $pdf->SetXY($this->marge_gauche, $posy); $pdf->SetFont('', '', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($this->emetteur->getFullAddress()), 0, 'L', 0); - $posy=$pdf->GetY()+2; + $posy = $pdf->GetY() + 2; } } } @@ -875,18 +872,18 @@ class pdf_aurore extends ModelePDFSupplierProposal // If payment mode not forced or forced to VIR, show payment with BAN if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'VIR') { - if (! empty($object->fk_bank) || ! empty($conf->global->FACTURE_RIB_NUMBER)) + if (!empty($object->fk_bank) || !empty($conf->global->FACTURE_RIB_NUMBER)) { - $bankid=(empty($object->fk_bank)?$conf->global->FACTURE_RIB_NUMBER:$object->fk_bank); + $bankid = (empty($object->fk_bank) ? $conf->global->FACTURE_RIB_NUMBER : $object->fk_bank); $account = new Account($this->db); $account->fetch($bankid); - $curx=$this->marge_gauche; - $cury=$posy; + $curx = $this->marge_gauche; + $cury = $posy; - $posy=pdf_bank($pdf, $outputlangs, $curx, $cury, $account, 0, $default_font_size); + $posy = pdf_bank($pdf, $outputlangs, $curx, $cury, $account, 0, $default_font_size); - $posy+=2; + $posy += 2; } } } @@ -909,7 +906,7 @@ class pdf_aurore extends ModelePDFSupplierProposal protected function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs) { // phpcs:enable - global $conf,$mysoc; + global $conf, $mysoc; $default_font_size = pdf_getPDFFontSize($outputlangs); $tab2_top = $posy; @@ -920,29 +917,29 @@ class pdf_aurore extends ModelePDFSupplierProposal $col1x = 120; $col2x = 170; if ($this->page_largeur < 210) // To work with US executive format { - $col2x-=20; + $col2x -= 20; } $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); - $useborder=0; + $useborder = 0; $index = 0; // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT"), 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + 0); - $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_ht + (! empty($object->remise)?$object->remise:0), 0, $outputlangs), 0, 'R', 1); + $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_ht + (!empty($object->remise) ? $object->remise : 0), 0, $outputlangs), 0, 'R', 1); // Show VAT by rates and total $pdf->SetFillColor(248, 248, 248); - $this->atleastoneratenotnull=0; + $this->atleastoneratenotnull = 0; if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) { - $tvaisnull=((! empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); - if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) + $tvaisnull = ((!empty($this->tva) && count($this->tva) == 1 && isset($this->tva['0.000']) && is_float($this->tva['0.000'])) ? true : false); + if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_IFNULL) && $tvaisnull) { // Nothing to do } @@ -951,28 +948,28 @@ class pdf_aurore extends ModelePDFSupplierProposal //Local tax 1 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -983,13 +980,13 @@ class pdf_aurore extends ModelePDFSupplierProposal //Local tax 2 before VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('1','3','5'))) continue; + if (in_array((string) $localtax_type, array('1', '3', '5'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { - if ($tvakey!=0) // On affiche pas taux 0 + if ($tvakey != 0) // On affiche pas taux 0 { //$this->atleastoneratenotnull++; @@ -998,15 +995,15 @@ class pdf_aurore extends ModelePDFSupplierProposal $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1015,7 +1012,7 @@ class pdf_aurore extends ModelePDFSupplierProposal } //} // VAT - foreach($this->tva as $tvakey => $tvaval) + foreach ($this->tva as $tvakey => $tvaval) { if ($tvakey > 0) // On affiche pas taux 0 { @@ -1024,15 +1021,15 @@ class pdf_aurore extends ModelePDFSupplierProposal $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } - $totalvat =$outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; - $totalvat.=vatrate($tvakey, 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).' '; + $totalvat .= vatrate($tvakey, 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1042,11 +1039,11 @@ class pdf_aurore extends ModelePDFSupplierProposal //Local tax 1 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on') //{ - foreach($this->localtax1 as $localtax_type => $localtax_rate) + foreach ($this->localtax1 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { if ($tvakey != 0) // On affiche pas taux 0 { @@ -1055,16 +1052,16 @@ class pdf_aurore extends ModelePDFSupplierProposal $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); } @@ -1074,11 +1071,11 @@ class pdf_aurore extends ModelePDFSupplierProposal //Local tax 2 after VAT //if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on') //{ - foreach($this->localtax2 as $localtax_type => $localtax_rate) + foreach ($this->localtax2 as $localtax_type => $localtax_rate) { - if (in_array((string) $localtax_type, array('2','4','6'))) continue; + if (in_array((string) $localtax_type, array('2', '4', '6'))) continue; - foreach($localtax_rate as $tvakey => $tvaval) + foreach ($localtax_rate as $tvakey => $tvaval) { // retrieve global local tax if ($tvakey != 0) // On affiche pas taux 0 @@ -1088,16 +1085,16 @@ class pdf_aurore extends ModelePDFSupplierProposal $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $tvacompl=''; + $tvacompl = ''; if (preg_match('/\*/', $tvakey)) { - $tvakey=str_replace('*', '', $tvakey); + $tvakey = str_replace('*', '', $tvakey); $tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")"; } $totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).' '; - $totalvat.=vatrate(abs($tvakey), 1).$tvacompl; - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1); + $totalvat .= vatrate(abs($tvakey), 1).$tvacompl; + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1); @@ -1111,7 +1108,7 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalTTC"), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($object->total_ttc, 0, $outputlangs), $useborder, 'R', 1); @@ -1130,7 +1127,7 @@ class pdf_aurore extends ModelePDFSupplierProposal $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid"), 0, 'L', 0); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle, 0, $outputlangs), 0, 'R', 0); @@ -1155,7 +1152,7 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetTextColor(0, 0, 60); $pdf->SetFillColor(224, 224, 224); $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); - $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay"), $useborder, 'L', 1); $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); @@ -1187,8 +1184,8 @@ class pdf_aurore extends ModelePDFSupplierProposal global $conf; // Force to disable hidetop and hidebottom - $hidebottom=0; - if ($hidetop) $hidetop=-1; + $hidebottom = 0; + if ($hidetop) $hidetop = -1; $currency = !empty($currency) ? $currency : $conf->currency; $default_font_size = pdf_getPDFFontSize($outputlangs); @@ -1200,24 +1197,24 @@ class pdf_aurore extends ModelePDFSupplierProposal if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); - $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; - if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); } $pdf->SetDrawColor(128, 128, 128); $pdf->SetFont('', '', $default_font_size - 1); // Output Rect - $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5); // line takes a position y in 2nd parameter and 4th parameter + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); // line takes a position y in 2nd parameter and 4th parameter - $pdf->SetXY($this->posxdesc-1, $tab_top+1); + $pdf->SetXY($this->posxdesc - 1, $tab_top + 1); $pdf->MultiCell(108, 2, $outputlangs->transnoentities("Designation"), '', 'L'); } @@ -1227,26 +1224,26 @@ class pdf_aurore extends ModelePDFSupplierProposal //$pdf->line($this->posxtva-2, $tab_top, $this->posxtva-2, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxtva-5, $tab_top+1); - $pdf->MultiCell($this->posxup-$this->posxtva+3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); + $pdf->SetXY($this->posxtva - 5, $tab_top + 1); + $pdf->MultiCell($this->posxup - $this->posxtva + 3, 2, $outputlangs->transnoentities("VAT"), '', 'C'); } } - $pdf->line($this->posxup-3, $tab_top, $this->posxup-3, $tab_top + $tab_height); + $pdf->line($this->posxup - 3, $tab_top, $this->posxup - 3, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxup-1, $tab_top+1); - $pdf->MultiCell($this->posxqty-$this->posxup-1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); + $pdf->SetXY($this->posxup - 1, $tab_top + 1); + $pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); } - $pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height); + $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height); if (empty($hidetop)) { - $pdf->SetXY($this->posxqty-1, $tab_top+1); - $pdf->MultiCell($this->posxunit-$this->posxqty-1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); + $pdf->SetXY($this->posxqty - 1, $tab_top + 1); + $pdf->MultiCell($this->posxunit - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C'); } - if($conf->global->PRODUCT_USE_UNITS) { + if ($conf->global->PRODUCT_USE_UNITS) { $pdf->line($this->posxunit - 1, $tab_top, $this->posxunit - 1, $tab_top + $tab_height); if (empty($hidetop)) { $pdf->SetXY($this->posxunit - 1, $tab_top + 1); @@ -1254,13 +1251,13 @@ class pdf_aurore extends ModelePDFSupplierProposal } } - $pdf->line($this->posxdiscount-1, $tab_top, $this->posxdiscount-1, $tab_top + $tab_height); + $pdf->line($this->posxdiscount - 1, $tab_top, $this->posxdiscount - 1, $tab_top + $tab_height); if (empty($hidetop)) { if ($this->atleastonediscount) { - $pdf->SetXY($this->posxdiscount-1, $tab_top+1); - $pdf->MultiCell($this->postotalht-$this->posxdiscount+1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); + $pdf->SetXY($this->posxdiscount - 1, $tab_top + 1); + $pdf->MultiCell($this->postotalht - $this->posxdiscount + 1, 2, $outputlangs->transnoentities("ReductionShort"), '', 'C'); } } if ($this->atleastonediscount) @@ -1269,7 +1266,7 @@ class pdf_aurore extends ModelePDFSupplierProposal } if (empty($hidetop)) { - $pdf->SetXY($this->postotalht-1, $tab_top+1); + $pdf->SetXY($this->postotalht - 1, $tab_top + 1); $pdf->MultiCell(30, 2, $outputlangs->transnoentities("TotalHT"), '', 'C'); } } @@ -1296,7 +1293,7 @@ class pdf_aurore extends ModelePDFSupplierProposal pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); // Show Draft Watermark - if($object->statut==0 && (! empty($conf->global->SUPPLIER_PROPOSAL_DRAFT_WATERMARK)) ) + if ($object->statut == 0 && (!empty($conf->global->SUPPLIER_PROPOSAL_DRAFT_WATERMARK))) { pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->SUPPLIER_PROPOSAL_DRAFT_WATERMARK); } @@ -1304,19 +1301,19 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); - $posy=$this->marge_haute; - $posx=$this->page_largeur-$this->marge_droite-100; + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; $pdf->SetXY($this->marge_gauche, $posy); // Logo - $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; if ($this->emetteur->logo) { if (is_readable($logo)) { - $height=pdf_getHeightForLogo($logo); - $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { @@ -1328,32 +1325,32 @@ class pdf_aurore extends ModelePDFSupplierProposal } else { - $text=$this->emetteur->name; + $text = $this->emetteur->name; $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } $pdf->SetFont('', 'B', $default_font_size + 3); $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $title=$outputlangs->transnoentities("CommercialAsk"); + $title = $outputlangs->transnoentities("CommercialAsk"); $pdf->MultiCell(100, 4, $title, '', 'R'); $pdf->SetFont('', 'B', $default_font_size); - $posy+=5; + $posy += 5; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : " . $outputlangs->convToOutputCharset($object->ref), '', 'R'); + $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref), '', 'R'); - $posy+=1; + $posy += 1; $pdf->SetFont('', '', $default_font_size - 2); if ($object->ref_client) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : " . $outputlangs->convToOutputCharset($object->ref_client), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } /* PHFAVRE $posy+=4; @@ -1364,28 +1361,28 @@ class pdf_aurore extends ModelePDFSupplierProposal if ($object->thirdparty->code_fournisseur) { - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R'); } // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { - $usertmp=new User($this->db); + $usertmp = new User($this->db); $usertmp->fetch($arrayidcontact[0]); - $posy+=4; + $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $pdf->MultiCell(100, 3, $langs->trans("BuyerName")." : ".$usertmp->getFullName($langs), '', 'R'); } } - $posy+=2; + $posy += 2; $top_shift = 0; // Show list of linked objects @@ -1399,28 +1396,28 @@ class pdf_aurore extends ModelePDFSupplierProposal if ($showaddress) { // Sender properties - $carac_emetteur=''; + $carac_emetteur = ''; // Add internal contact of proposal if defined - $arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL'); + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); if (count($arrayidcontact) > 0) { $object->fetch_user($arrayidcontact[0]); - $labelbeforecontactname=($outputlangs->transnoentities("FromContactName")!='FromContactName'?$outputlangs->transnoentities("FromContactName"):$outputlangs->transnoentities("Name")); - $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$labelbeforecontactname.": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; + $labelbeforecontactname = ($outputlangs->transnoentities("FromContactName") != 'FromContactName' ? $outputlangs->transnoentities("FromContactName") : $outputlangs->transnoentities("Name")); + $carac_emetteur .= ($carac_emetteur ? "\n" : '').$labelbeforecontactname.": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n"; } $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); // Show sender - $posy=42+$top_shift; - $posx=$this->marge_gauche; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80; - $hautcadre=40; + $posy = 42 + $top_shift; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + $hautcadre = 40; // Show sender frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx, $posy-5); + $pdf->SetXY($posx, $posy - 5); $pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom").":", 0, 'L'); $pdf->SetXY($posx, $posy); $pdf->SetFillColor(230, 230, 230); @@ -1428,63 +1425,63 @@ class pdf_aurore extends ModelePDFSupplierProposal $pdf->SetTextColor(0, 0, 60); // Show sender name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L'); - $posy=$pdf->getY(); + $posy = $pdf->getY(); // Show sender information - $pdf->SetXY($posx+2, $posy); + $pdf->SetXY($posx + 2, $posy); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L'); // If CUSTOMER contact defined, we use it - $usecontact=false; - $arrayidcontact=$object->getIdContact('external', 'CUSTOMER'); + $usecontact = false; + $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); if (count($arrayidcontact) > 0) { - $usecontact=true; - $result=$object->fetch_contact($arrayidcontact[0]); + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name - if (! empty($usecontact)) + if (!empty($usecontact)) { // On peut utiliser le nom de la societe du contact - if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socname = $object->contact->socname; + if (!empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socname = $object->contact->socname; else $socname = $object->thirdparty->name; - $carac_client_name=$outputlangs->convToOutputCharset($socname); + $carac_client_name = $outputlangs->convToOutputCharset($socname); } else { - $carac_client_name=$outputlangs->convToOutputCharset($object->thirdparty->name); + $carac_client_name = $outputlangs->convToOutputCharset($object->thirdparty->name); } - $carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact?$object->contact:''), $usecontact, 'target', $object); + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object); // Show recipient - $widthrecbox=100; - if ($this->page_largeur < 210) $widthrecbox=84; // To work with US executive format - $posy=42+$top_shift; - $posx=$this->page_largeur-$this->marge_droite-$widthrecbox; - if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche; + $widthrecbox = 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = 42 + $top_shift; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; // Show recipient frame $pdf->SetTextColor(0, 0, 0); $pdf->SetFont('', '', $default_font_size - 2); - $pdf->SetXY($posx+2, $posy-5); + $pdf->SetXY($posx + 2, $posy - 5); $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":", 0, 'L'); $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); // Show recipient name - $pdf->SetXY($posx+2, $posy+3); + $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); // Show recipient information $pdf->SetFont('', '', $default_font_size - 1); - $pdf->SetXY($posx+2, $posy+4+(dol_nboflines_bis($carac_client_name, 50)*4)); + $pdf->SetXY($posx + 2, $posy + 4 + (dol_nboflines_bis($carac_client_name, 50) * 4)); $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); } @@ -1505,7 +1502,7 @@ class pdf_aurore extends ModelePDFSupplierProposal protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) { global $conf; - $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; return pdf_pagefoot($pdf, $outputlangs, 'SUPPLIER_PROPOSAL_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); } } diff --git a/htdocs/core/tpl/massactions_pre.tpl.php b/htdocs/core/tpl/massactions_pre.tpl.php index a0c627ac049..492590c65e4 100644 --- a/htdocs/core/tpl/massactions_pre.tpl.php +++ b/htdocs/core/tpl/massactions_pre.tpl.php @@ -45,7 +45,7 @@ if ($massaction == 'presend') $listofselectedthirdparties = array(); $listofselectedref = array(); - if (! GETPOST('cancel', 'alpha')) + if (!GETPOST('cancel', 'alpha')) { foreach ($arrayofselected as $toselectid) { @@ -66,25 +66,25 @@ if ($massaction == 'presend') print ''; - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); dol_fiche_head(null, '', ''); // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->withform = -1; - $formmail->fromtype = (GETPOST('fromtype') ? GETPOST('fromtype') : (! empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user')); + $formmail->fromtype = (GETPOST('fromtype') ? GETPOST('fromtype') : (!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user')); if ($formmail->fromtype === 'user') { $formmail->fromid = $user->id; } $formmail->trackid = $trackid; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set + if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { - include DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; + include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $formmail->frommail = dolAddEmailTrackId($formmail->frommail, $trackid); } $formmail->withfrom = 1; @@ -112,10 +112,10 @@ if ($massaction == 'presend') $formmail->withtoreadonly = 1; } - $formmail->withoptiononeemailperrecipient = ((count($listofselectedref) == 1 && count(reset($listofselectedref)) == 1) || empty($liste)) ? 0 : ((GETPOST('oneemailperrecipient')=='on')?1:-1); + $formmail->withoptiononeemailperrecipient = ((count($listofselectedref) == 1 && count(reset($listofselectedref)) == 1) || empty($liste)) ? 0 : ((GETPOST('oneemailperrecipient') == 'on') ? 1 : -1); - $formmail->withto = empty($liste)?(GETPOST('sendto', 'alpha')?GETPOST('sendto', 'alpha'):array()):$liste; - $formmail->withtofree = empty($liste)?1:0; + $formmail->withto = empty($liste) ? (GETPOST('sendto', 'alpha') ?GETPOST('sendto', 'alpha') : array()) : $liste; + $formmail->withtofree = empty($liste) ? 1 : 0; $formmail->withtocc = 1; $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; $formmail->withtopic = $langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); @@ -134,8 +134,8 @@ if ($massaction == 'presend') $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $object); $substitutionarray['__EMAIL__'] = $sendto; - $substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '' : ''; - $substitutionarray['__PERSONALIZED__'] = ''; // deprecated + $substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '' : ''; + $substitutionarray['__PERSONALIZED__'] = ''; // deprecated $substitutionarray['__CONTACTCIVNAME__'] = ''; $parameters = array( @@ -152,11 +152,11 @@ if ($massaction == 'presend') $formmail->param['models_id'] = GETPOST('modelmailselected', 'int'); $formmail->param['id'] = join(',', $arrayofselected); // $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - if (! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && count($listofselectedthirdparties) > $conf->global->MAILING_LIMIT_SENDBYWEB) + if (!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && count($listofselectedthirdparties) > $conf->global->MAILING_LIMIT_SENDBYWEB) { $langs->load("errors"); - print img_warning() . ' ' . $langs->trans('WarningNumberOfRecipientIsRestrictedInMassAction', $conf->global->MAILING_LIMIT_SENDBYWEB); - print ' - ' . $langs->trans("GoBack") . ''; + print img_warning().' '.$langs->trans('WarningNumberOfRecipientIsRestrictedInMassAction', $conf->global->MAILING_LIMIT_SENDBYWEB); + print ' - '.$langs->trans("GoBack").''; $arrayofmassactions = array(); } else @@ -166,3 +166,15 @@ if ($massaction == 'presend') dol_fiche_end(); } +// Allow Pre-Mass-Action hook (eg for confirmation dialog) +$parameters = array( + 'toselect' => $toselect, + 'uploaddir' => $uploaddir +); + +$reshook = $hookmanager->executeHooks('doPreMassActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} else { + print $hookmanager->resPrint; +} diff --git a/htdocs/cron/class/cronjob.class.php b/htdocs/cron/class/cronjob.class.php index 5cde792bbb5..82a898a8ddf 100644 --- a/htdocs/cron/class/cronjob.class.php +++ b/htdocs/cron/class/cronjob.class.php @@ -1308,7 +1308,7 @@ class Cronjob extends CommonObject public function LibStatut($status, $mode = 0, $processing = 0, $lastresult = 0) { // phpcs:enable - $this->labelStatus = array(); // Force reset o array because label depends on other fields + $this->labelStatus = array(); // Force reset o array because label depends on other fields $this->labelStatusShort = array(); if (empty($this->labelStatus) || empty($this->labelStatusShort)) diff --git a/htdocs/dav/dav.class.php b/htdocs/dav/dav.class.php index 7bb598135f3..145da542976 100644 --- a/htdocs/dav/dav.class.php +++ b/htdocs/dav/dav.class.php @@ -175,7 +175,7 @@ class CdavLib $caldata.="LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n"; $caldata.="DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n"; if($obj->sourceuid=='') - $caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n"; + $caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.constant('CDAV_URI_KEY')."\n"; else $caldata.="UID:".$obj->sourceuid."\n"; $caldata.="SUMMARY:".$obj->label."\n"; @@ -277,7 +277,7 @@ class CdavLib { $calevents[] = array( 'calendardata' => $calendardata, - 'uri' => $obj->id.'-ev-'.CDAV_URI_KEY, + 'uri' => $obj->id.'-ev-'.constant('CDAV_URI_KEY'), 'lastmodified' => strtotime($obj->lastupd), 'etag' => '"'.md5($calendardata).'"', 'calendarid' => $calendarId, @@ -289,7 +289,7 @@ class CdavLib { $calevents[] = array( // 'calendardata' => $calendardata, not necessary because etag+size are present - 'uri' => $obj->id.'-ev-'.CDAV_URI_KEY, + 'uri' => $obj->id.'-ev-'.constant('CDAV_URI_KEY'), 'lastmodified' => strtotime($obj->lastupd), 'etag' => '"'.md5($calendardata).'"', 'calendarid' => $calendarId, diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index 7c400c0fbb7..f7ff3565e10 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -59,6 +59,10 @@ $search_state = trim(GETPOST("search_state")); $search_country = GETPOST("search_country", 'int'); $search_type_thirdparty = GETPOST("search_type_thirdparty", 'int'); $search_billed = GETPOST("search_billed", 'int'); +$search_datedelivery_start = dol_mktime(0, 0, 0, GETPOST('search_datedelivery_startmonth', 'int'), GETPOST('search_datedelivery_startday', 'int'), GETPOST('search_datedelivery_startyear', 'int')); +$search_datedelivery_end = dol_mktime(23, 59, 59, GETPOST('search_datedelivery_endmonth', 'int'), GETPOST('search_datedelivery_endday', 'int'), GETPOST('search_datedelivery_endyear', 'int')); +$search_datereceipt_start = dol_mktime(0, 0, 0, GETPOST('search_datereceipt_startmonth', 'int'), GETPOST('search_datereceipt_startday', 'int'), GETPOST('search_datereceipt_startyear', 'int')); +$search_datereceipt_end = dol_mktime(23, 59, 59, GETPOST('search_datereceipt_endmonth', 'int'), GETPOST('search_datereceipt_endday', 'int'), GETPOST('search_datereceipt_endyear', 'int')); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $optioncss = GETPOST('optioncss', 'alpha'); @@ -156,6 +160,10 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_country = ''; $search_type_thirdparty = ''; $search_billed = ''; + $search_datedelivery_start = ''; + $search_datedelivery_end = ''; + $search_datereceipt_start = ''; + $search_datereceipt_end = ''; $viewstatut = ''; $toselect = ''; $search_array_options = array(); @@ -234,6 +242,10 @@ if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$search_type_thirdp if ($search_ref_exp) $sql .= natural_search('e.ref', $search_ref_exp); if ($search_ref_liv) $sql .= natural_search('l.ref', $search_ref_liv); if ($search_company) $sql .= natural_search('s.nom', $search_company); +if ($search_datedelivery_start) $sql .= " AND e.date_delivery >= '".$db->idate($search_datedelivery_start)."'"; +if ($search_datedelivery_end) $sql .= " AND e.date_delivery <= '".$db->idate($search_datedelivery_end)."'"; +if ($search_datereceipt_start) $sql .= " AND l.date_delivery >= '".$db->idate($search_datereceipt_start)."'"; +if ($search_datereceipt_end) $sql .= " AND l.date_delivery <= '".$db->idate($search_datereceipt_end)."'"; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields @@ -280,6 +292,10 @@ if ($resql) if ($search_company) $param .= "&search_company=".urlencode($search_company); if ($search_town) $param .= '&search_town='.urlencode($search_town); if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); + if ($search_datedelivery_start) $param .= '&search_datedelivery_start='.urlencode($search_datedelivery_start); + if ($search_datedelivery_end) $param .= '&search_datedelivery_end='.urlencode($search_datedelivery_end); + if ($search_datereceipt_start) $param .= '&search_datereceipt_start='.urlencode($search_datereceipt_start); + if ($search_datereceipt_end) $param .= '&search_datereceipt_end='.urlencode($search_datereceipt_end); if ($viewstatut != '') $param .= '&viewstatut='.urlencode($viewstatut); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields @@ -391,7 +407,16 @@ if ($resql) // Date delivery planned if (!empty($arrayfields['e.date_delivery']['checked'])) { - print ' '; + print '
'; + print $langs->trans('From').' '; + print $form->selectDate($search_delivery_start ? $search_delivery_start : -1, 'search_delivery_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to').' '; + print $form->selectDate($search_delivery_end ? $search_delivery_end : -1, 'search_delivery_end', 0, 0, 1); + print '
'; + print '
 '; + print '
'; + print $langs->trans('From').' '; + print $form->selectDate($search_receipt_start ? $search_receipt_start : -1, 'search_receipt_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to').' '; + print $form->selectDate($search_receipt_end ? $search_receipt_end : -1, 'search_receipt_end', 0, 0, 1); + print '
'; + print '
'.$obj->type.$keyModel.''.str_replace(',', ' , ', $obj->field).''.str_replace(',', ' , ', $filter['field']).''.str_replace(',', ' , ', $filter['value']).'
'.$langs->trans("SuppliersCategoriesShort").''; - print $form->showCategories($object->id, 'supplier', 1); + print $form->showCategories($object->id, Categorie::TYPE_SUPPLIER, 1); print "
'.$langs->trans("Description").''.$langs->trans("Warehouse").''.$langs->trans("Warehouse"); + + // Select warehouse to force it everywhere + if (count($listwarehouses)>1) + { + print '
'.$langs->trans("ForceTo").' '.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, 1, 0, 0, '', 0, 0, $disabled); + } + elseif (count($listwarehouses)==1) + { + print '
'.$langs->trans("ForceTo").' '.$form->selectarray('fk_default_warehouse', $listwarehouses, $fk_default_warehouse, 0, 0, 0, '', 0, 0, $disabled); + } + + print '
'.price($objp->pamount).'
'; - $sql = "SELECT s.nom, s.rowid as socid, f.ref_supplier, f.amount, f.datef as df,"; + $sql = "SELECT s.nom, s.rowid as socid, f.ref_supplier, f.datef as df,"; $sql .= " f.paye as paye, f.fk_statut as statut, f.rowid as facid,"; $sql .= " u.login, u.rowid as userid"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_fourn as f,".MAIN_DB_PREFIX."user as u"; diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index 9cc287cd28a..bf78cfeafc9 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -40,23 +40,23 @@ require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Get parameters -$action=GETPOST('action', 'aZ09'); -$cancel=GETPOST('cancel', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref', 'alpha'); -$fuserid = (GETPOST('fuserid', 'int')?GETPOST('fuserid', 'int'):$user->id); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$fuserid = (GETPOST('fuserid', 'int') ?GETPOST('fuserid', 'int') : $user->id); // Load translation files required by the page -$langs->loadLangs(array("holiday","mails")); +$langs->loadLangs(array("holiday", "mails")); -$now=dol_now(); +$now = dol_now(); $childids = $user->getAllChildIds(1); $morefilter = 'AND employee = 1'; -if (! empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; +if (!empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; $error = 0; @@ -90,7 +90,7 @@ if (!empty($user->rights->holiday->delete)) $candelete = 1; if ($object->statut == Holiday::STATUS_DRAFT && $user->rights->holiday->write && in_array($object->fk_user, $childids)) $candelete = 1; // Protection if external user -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'holiday', $object->id, 'holiday'); @@ -1287,8 +1287,8 @@ else $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")); + 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 ''; diff --git a/htdocs/index.php b/htdocs/index.php index 250a0c1736b..110de972f2b 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -80,7 +80,7 @@ llxHeader('', $title); $resultboxes = FormOther::getBoxesArea($user, "0"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) -print load_fiche_titre($langs->trans("HomeArea"), $resultboxes['selectboxlist'], 'home'); +print load_fiche_titre($langs->trans("HomeArea"), $resultboxes['selectboxlist'], 'home', 0, '', 'titleforhome'); if (!empty($conf->global->MAIN_MOTD)) { @@ -268,6 +268,7 @@ if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS)) DOL_URL_ROOT.'/societe/list.php?type=f&mainmenu=companies', DOL_URL_ROOT.'/contact/list.php?mainmenu=companies', DOL_URL_ROOT.'/adherents/list.php?statut=1&mainmenu=members', + DOL_URL_ROOT.'/adherents/list.php?statut=-1&mainmenu=members', DOL_URL_ROOT.'/product/list.php?type=0&mainmenu=products', DOL_URL_ROOT.'/product/list.php?type=1&mainmenu=products', DOL_URL_ROOT.'/comm/propal/list.php?mainmenu=commercial&leftmenu=propals', @@ -284,7 +285,7 @@ if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS)) DOL_URL_ROOT.'/don/list.php?leftmenu=donations' ); // Translation lang files - $langfile=array( + $langfile = array( "users", "companies", "prospects", @@ -358,89 +359,89 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { $dashboardlines = array(); // Do not include sections without management permission - require_once DOL_DOCUMENT_ROOT . '/core/class/workboardresponse.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; // Number of actions to do (late) if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->read) { - include_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; + include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $board = new ActionComm($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of project opened if (!empty($conf->projet->enabled) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $board = new Project($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of tasks to do (late) if (!empty($conf->projet->enabled) && empty($conf->global->PROJECT_HIDE_TASKS) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php'; + include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $board = new Task($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of commercial proposals opened (expired) if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { - include_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $board = new Propal($db); - $dashboardlines[$board->element . '_opened'] = $board->load_board($user, "opened"); + $dashboardlines[$board->element.'_opened'] = $board->load_board($user, "opened"); // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[$board->element . '_signed'] = $board->load_board($user, "signed"); + $dashboardlines[$board->element.'_signed'] = $board->load_board($user, "signed"); } // Number of commercial proposals opened (expired) if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { - include_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php'; + include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; $board = new SupplierProposal($db); - $dashboardlines[$board->element . '_opened'] = $board->load_board($user, "opened"); + $dashboardlines[$board->element.'_opened'] = $board->load_board($user, "opened"); // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[$board->element . '_signed'] = $board->load_board($user, "signed"); + $dashboardlines[$board->element.'_signed'] = $board->load_board($user, "signed"); } // Number of customer orders a deal if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { - include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $board = new Commande($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of suppliers orders a deal if (!empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->lire) { - include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php'; + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $board = new CommandeFournisseur($db); - $dashboardlines[$board->element . '_opened'] = $board->load_board($user, "opened"); - $dashboardlines[$board->element . '_awaiting'] = $board->load_board($user, 'awaiting'); + $dashboardlines[$board->element.'_opened'] = $board->load_board($user, "opened"); + $dashboardlines[$board->element.'_awaiting'] = $board->load_board($user, 'awaiting'); } // Number of services enabled (delayed) if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php'; + include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $board = new Contrat($db); - $dashboardlines[$board->element . '_inactive'] = $board->load_board($user, "inactive"); + $dashboardlines[$board->element.'_inactive'] = $board->load_board($user, "inactive"); // Number of active services (expired) - $dashboardlines[$board->element . '_active'] = $board->load_board($user, "active"); + $dashboardlines[$board->element.'_active'] = $board->load_board($user, "active"); } // Number of invoices customers (has paid) if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { - include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $board = new Facture($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of supplier invoices (has paid) if (!empty($conf->supplier_invoice->enabled) && !empty($user->rights->fournisseur->facture->lire)) { - include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $board = new FactureFournisseur($db); $dashboardlines[$board->element] = $board->load_board($user); } // Number of transactions to conciliate if (!empty($conf->banque->enabled) && $user->rights->banque->lire && !$user->socid) { - include_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $board = new Account($db); - $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate + $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate if ($nb > 0) { $dashboardlines[$board->element] = $board->load_board($user); } @@ -448,35 +449,36 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { // Number of cheque to send if (!empty($conf->banque->enabled) && $user->rights->banque->lire && !$user->socid && empty($conf->global->BANK_DISABLE_CHECK_DEPOSIT)) { - include_once DOL_DOCUMENT_ROOT . '/compta/paiement/cheque/class/remisecheque.class.php'; + include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; $board = new RemiseCheque($db); $dashboardlines['RemiseCheque'] = $board->load_board($user); } // Number of foundation members if (!empty($conf->adherent->enabled) && $user->rights->adherent->lire && !$user->socid) { - include_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php'; + include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $board = new Adherent($db); - $dashboardlines['Adherent'] = $board->load_board($user); + $dashboardlines[$board->element.'_shift'] = $board->load_board($user, 'shift'); + $dashboardlines[$board->element.'_expired'] = $board->load_board($user, 'expired'); } // Number of expense reports to approve if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->approve) { - include_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $board = new ExpenseReport($db); $dashboardlines['ExpenseReport'] = $board->load_board($user, 'toapprove'); } // Number of expense reports to pay if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->to_paid) { - include_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $board = new ExpenseReport($db); $dashboardlines['ExpenseReport'] = $board->load_board($user, 'topay'); } // Number of holidays to approve if (!empty($conf->holiday->enabled) && $user->rights->holiday->approve) { - include_once DOL_DOCUMENT_ROOT . '/holiday/class/holiday.class.php'; + include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $board = new Holiday($db); $dashboardlines['Holiday'] = $board->load_board($user); } @@ -563,7 +565,7 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) { 'groupName' => 'Members', 'globalStatsKey' => 'members', 'stats' => - array('Adherent'), + array('member_shift', 'member_expired'), ), 'ExpenseReport' => array( @@ -875,23 +877,23 @@ print '
'; * Show boxes */ -$boxlist.='
'; +$boxlist .= '
'; -$boxlist.='
'; -if(!empty($nbworkboardcount)) +$boxlist .= '
'; +if (!empty($nbworkboardcount)) { - $boxlist.=$boxwork; + $boxlist .= $boxwork; } -$boxlist.=$resultboxes['boxlista']; +$boxlist .= $resultboxes['boxlista']; -$boxlist.= '
'; +$boxlist .= '
'; if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS)) { // Remove allready present info in new dash board - if(!empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD) && is_array($boxstatItems) && count($boxstatItems) > 0){ + if (!empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD) && is_array($boxstatItems) && count($boxstatItems) > 0) { foreach ($boxstatItems as $boxstatItemKey => $boxstatItemHtml) { if (in_array($boxstatItemKey, $globalStatInTopOpenedDashBoard)) { unset($boxstatItems[$boxstatItemKey]); diff --git a/htdocs/install/check.php b/htdocs/install/check.php index 6b6cfb2911d..6fb01d5329c 100644 --- a/htdocs/install/check.php +++ b/htdocs/install/check.php @@ -127,7 +127,7 @@ if (!function_exists("imagecreate")) { $langs->load("errors"); print 'Error '.$langs->trans("ErrorPHPDoesNotSupportGD")."
\n"; - // $checksok=0; // If ko, just warning. So check must still be 1 (otherwise no way to install) + // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) } else { @@ -140,7 +140,7 @@ if (!function_exists("curl_init")) { $langs->load("errors"); print 'Error '.$langs->trans("ErrorPHPDoesNotSupportCurl")."
\n"; - // $checksok=0; // If ko, just warning. So check must still be 1 (otherwise no way to install) + // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) } else { @@ -163,7 +163,7 @@ if (!function_exists("utf8_encode")) { $langs->load("errors"); print 'Error '.$langs->trans("ErrorPHPDoesNotSupportUTF8")."
\n"; - // $checksok=0; // If ko, just warning. So check must still be 1 (otherwise no way to install) + // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) } else { @@ -178,7 +178,7 @@ if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@loc { $langs->load("errors"); print 'Error '.$langs->trans("ErrorPHPDoesNotSupportIntl")."
\n"; - // $checksok=0; // If ko, just warning. So check must still be 1 (otherwise no way to install) + // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) } else { @@ -186,6 +186,16 @@ if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@loc } } +if (!class_exists('ZipArchive')) +{ + $langs->load("errors"); + print 'Error '.$langs->trans("ErrorPHPDoesNotSupport", "ZIP")."
\n"; + // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install) +} +else +{ + print 'Ok '.$langs->trans("PHPSupport", "ZIP")."
\n"; +} // Check memory $memrequiredorig = '64M'; @@ -464,7 +474,8 @@ else array('from'=>'7.0.0', 'to'=>'8.0.0'), array('from'=>'8.0.0', 'to'=>'9.0.0'), array('from'=>'9.0.0', 'to'=>'10.0.0'), - array('from'=>'10.0.0', 'to'=>'11.0.0') + array('from'=>'10.0.0', 'to'=>'11.0.0'), + array('from'=>'11.0.0', 'to'=>'12.0.0') ); $count = 0; diff --git a/htdocs/install/default.css b/htdocs/install/default.css index 7a3bb7b3290..65d8e8021a8 100644 --- a/htdocs/install/default.css +++ b/htdocs/install/default.css @@ -16,6 +16,9 @@ */ +.opacitymedium { + opacity: 0.5; +} body { font-size:14px; @@ -50,10 +53,9 @@ div.titre { } span.titre { - font-size: 90%; font-weight: bold; background: #FFFFFF; - color: #444; + color: rgb(0,113,121); border: 1px solid #bbb; padding: 10px 10px 10px 10px; margin: 0 0 10px 10px; @@ -344,13 +346,14 @@ ul { .button { - background: #fcfcfc; - border: 1px solid #e0e0e0; + background: rgb(0,113,121); + color: #fff; + /* border: 1px solid #e0e0e0; */ padding: 0.3em 0.7em; margin: 0 0.5em; - -moz-border-radius: 5px 5px 5px 5px; - -webkit-border-radius: 5px 5px 5px 5px; - border-radius: 5px 5px 5px 5px; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; -moz-box-shadow: 2px 2px 3px #ddd; -webkit-box-shadow: 2px 2px 3px #ddd; box-shadow: 2px 2px 3px #ddd; @@ -360,7 +363,7 @@ a.button:hover { } .choiceselected { - background-color: #dfd; + background-color: #f4fcf4; background-repeat: repeat-x; background-position: top left; } diff --git a/htdocs/install/fileconf.php b/htdocs/install/fileconf.php index b800f5f6ad4..4770575774a 100644 --- a/htdocs/install/fileconf.php +++ b/htdocs/install/fileconf.php @@ -136,7 +136,7 @@ if (!empty($force_install_noedit)) { >
'; print ''; print ''; diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 4e1745413ce..89a9be45633 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -1345,7 +1345,7 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr { foreach ($arrayofcss as $cssfile) { - if (preg_match('/^http/i', $cssfile)) + if (preg_match('/^(http|\/\/)/i', $cssfile)) { $urltofile = $cssfile; } @@ -1497,7 +1497,7 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr print ''."\n"; foreach ($arrayofjs as $jsfile) { - if (preg_match('/^http/i', $jsfile)) + if (preg_match('/^(http|\/\/)/i', $jsfile)) { print ''."\n"; } diff --git a/htdocs/margin/agentMargins.php b/htdocs/margin/agentMargins.php index 4080822b9ef..852bf4934d5 100644 --- a/htdocs/margin/agentMargins.php +++ b/htdocs/margin/agentMargins.php @@ -74,6 +74,9 @@ if ($user->rights->margins->read->all) { } $result = restrictedArea($user, 'margins'); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new User($db); +$hookmanager->initHooks(array('marginagentlist')); /* * Actions @@ -205,8 +208,11 @@ if ($result) else // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + $moreforfilter = ''; + $i = 0; - print "
'.num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday).'trans("WithNoSlashAtTheEnd")."
"; + print ''.$langs->trans("WithNoSlashAtTheEnd")."
"; print $langs->trans("Examples").":
"; ?>
    @@ -167,7 +167,7 @@ if (!empty($force_install_noedit)) { >
trans("WithNoSlashAtTheEnd")."
"; + print ''.$langs->trans("WithNoSlashAtTheEnd")."
"; print $langs->trans("DirectoryRecommendation")."
"; print $langs->trans("Examples").":
"; ?> diff --git a/htdocs/install/mysql/data/llx_00_c_country.sql b/htdocs/install/mysql/data/llx_00_c_country.sql index f2a48da68fb..acb2c956fda 100644 --- a/htdocs/install/mysql/data/llx_00_c_country.sql +++ b/htdocs/install/mysql/data/llx_00_c_country.sql @@ -276,3 +276,6 @@ INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (24 INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (246,'MF','MAF','Saint-Martin',1,0); INSERT INTO llx_c_country (rowid,code,code_iso,label,active,favorite) VALUES (247,'XK','XKX','Kosovo',1,0); + +-- Set field eec +UPDATE llx_c_country SET eec = 1 WHERE code IN ('AT','BE','BG','CY','CZ','DE','DK','EE','ES','FI','FR','GB','GR','HR','NL','HU','IE','IM','IT','LT','LU','LV','MC','MT','PL','PT','RO','SE','SK','SI','UK'); diff --git a/htdocs/install/mysql/data/llx_10_c_regions.sql b/htdocs/install/mysql/data/llx_10_c_regions.sql index be485ddb6b1..bbb7af35bb7 100644 --- a/htdocs/install/mysql/data/llx_10_c_regions.sql +++ b/htdocs/install/mysql/data/llx_10_c_regions.sql @@ -45,25 +45,16 @@ insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 6,'97601',3,'Mayotte'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 11,'75056',1,'Île-de-France'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 21,'51108',0,'Champagne-Ardenne'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 22,'80021',0,'Picardie'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 23,'76540',0,'Haute-Normandie'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 24,'45234',2,'Centre'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 25,'14118',0,'Basse-Normandie'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 26,'21231',0,'Bourgogne'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 31,'59350',2,'Nord-Pas-de-Calais'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 41,'57463',0,'Lorraine'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 42,'67482',1,'Alsace'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 43,'25056',0,'Franche-Comté'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 24,'45234',2,'Centre-Val de Loire'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 27,'21231',0,'Bourgogne-Franche-Comté'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 28,'76540',0,'Normandie'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 32,'59350',4,'Hauts-de-France'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 44,'67482',2,'Grand Est'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 52,'44109',4,'Pays de la Loire'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 53,'35238',0,'Bretagne'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 54,'86194',2,'Poitou-Charentes'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 72,'33063',1,'Aquitaine'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 73,'31555',0,'Midi-Pyrénées'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 74,'87085',2,'Limousin'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 82,'69123',2,'Rhône-Alpes'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 83,'63113',1,'Auvergne'); -insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 91,'34172',2,'Languedoc-Roussillon'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 75,'33063',0,'Nouvelle-Aquitaine'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 76,'31355',1,'Occitanie'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 84,'69123',1,'Auvergne-Rhône-Alpes'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 93,'13055',0,'Provence-Alpes-Côte d''Azur'); insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values ( 1, 94,'2A004',0,'Corse'); diff --git a/htdocs/install/mysql/data/llx_20_c_departements.sql b/htdocs/install/mysql/data/llx_20_c_departements.sql index 7e9417b487b..46d9b4d712e 100644 --- a/htdocs/install/mysql/data/llx_20_c_departements.sql +++ b/htdocs/install/mysql/data/llx_20_c_departements.sql @@ -42,97 +42,97 @@ insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,no insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values ( 4,'974','97411',3,'REUNION','Réunion'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values ( 6,'976','97601',3,'MAYOTTE','Mayotte'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'01','01053',5,'AIN','Ain'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (22,'02','02408',5,'AISNE','Aisne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (83,'03','03190',5,'ALLIER','Allier'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'01','01053',5,'AIN','Ain'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (32,'02','02408',5,'AISNE','Aisne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'03','03190',5,'ALLIER','Allier'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'04','04070',4,'ALPES-DE-HAUTE-PROVENCE','Alpes-de-Haute-Provence'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'05','05061',4,'HAUTES-ALPES','Hautes-Alpes'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'06','06088',4,'ALPES-MARITIMES','Alpes-Maritimes'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'07','07186',5,'ARDECHE','Ardèche'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (21,'08','08105',4,'ARDENNES','Ardennes'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'09','09122',5,'ARIEGE','Ariège'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (21,'10','10387',5,'AUBE','Aube'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (91,'11','11069',5,'AUDE','Aude'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'12','12202',5,'AVEYRON','Aveyron'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'07','07186',5,'ARDECHE','Ardèche'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'08','08105',4,'ARDENNES','Ardennes'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'09','09122',5,'ARIEGE','Ariège'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'10','10387',5,'AUBE','Aube'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'11','11069',5,'AUDE','Aude'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'12','12202',5,'AVEYRON','Aveyron'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'13','13055',4,'BOUCHES-DU-RHONE','Bouches-du-Rhône'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (25,'14','14118',2,'CALVADOS','Calvados'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (83,'15','15014',2,'CANTAL','Cantal'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (54,'16','16015',3,'CHARENTE','Charente'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (54,'17','17300',3,'CHARENTE-MARITIME','Charente-Maritime'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (28,'14','14118',2,'CALVADOS','Calvados'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'15','15014',2,'CANTAL','Cantal'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'16','16015',3,'CHARENTE','Charente'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'17','17300',3,'CHARENTE-MARITIME','Charente-Maritime'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'18','18033',2,'CHER','Cher'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (74,'19','19272',3,'CORREZE','Corrèze'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'19','19272',3,'CORREZE','Corrèze'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (94,'2A','2A004',3,'CORSE-DU-SUD','Corse-du-Sud'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (94,'2B','2B033',3,'HAUTE-CORSE','Haute-Corse'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (26,'21','21231',3,'COTE-D OR','Côte-d Or'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'21','21231',3,'COTE-D OR','Côte-d Or'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (53,'22','22278',4,'COTES-D ARMOR','Côtes-d Armor'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (74,'23','23096',3,'CREUSE','Creuse'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (72,'24','24322',3,'DORDOGNE','Dordogne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (43,'25','25056',2,'DOUBS','Doubs'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'26','26362',3,'DROME','Drôme'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (23,'27','27229',5,'EURE','Eure'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'23','23096',3,'CREUSE','Creuse'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'24','24322',3,'DORDOGNE','Dordogne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'25','25056',2,'DOUBS','Doubs'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'26','26362',3,'DROME','Drôme'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (28,'27','27229',5,'EURE','Eure'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'28','28085',1,'EURE-ET-LOIR','Eure-et-Loir'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (53,'29','29232',2,'FINISTERE','Finistère'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (91,'30','30189',2,'GARD','Gard'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'31','31555',3,'HAUTE-GARONNE','Haute-Garonne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'32','32013',2,'GERS','Gers'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (72,'33','33063',3,'GIRONDE','Gironde'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (91,'34','34172',5,'HERAULT','Hérault'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'30','30189',2,'GARD','Gard'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'31','31555',3,'HAUTE-GARONNE','Haute-Garonne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'32','32013',2,'GERS','Gers'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'33','33063',3,'GIRONDE','Gironde'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'34','34172',5,'HERAULT','Hérault'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (53,'35','35238',1,'ILLE-ET-VILAINE','Ille-et-Vilaine'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'36','36044',5,'INDRE','Indre'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'37','37261',1,'INDRE-ET-LOIRE','Indre-et-Loire'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'38','38185',5,'ISERE','Isère'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (43,'39','39300',2,'JURA','Jura'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (72,'40','40192',4,'LANDES','Landes'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'38','38185',5,'ISERE','Isère'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'39','39300',2,'JURA','Jura'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'40','40192',4,'LANDES','Landes'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'41','41018',0,'LOIR-ET-CHER','Loir-et-Cher'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'42','42218',3,'LOIRE','Loire'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (83,'43','43157',3,'HAUTE-LOIRE','Haute-Loire'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'42','42218',3,'LOIRE','Loire'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'43','43157',3,'HAUTE-LOIRE','Haute-Loire'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (52,'44','44109',3,'LOIRE-ATLANTIQUE','Loire-Atlantique'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (24,'45','45234',2,'LOIRET','Loiret'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'46','46042',2,'LOT','Lot'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (72,'47','47001',0,'LOT-ET-GARONNE','Lot-et-Garonne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (91,'48','48095',3,'LOZERE','Lozère'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'46','46042',2,'LOT','Lot'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'47','47001',0,'LOT-ET-GARONNE','Lot-et-Garonne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'48','48095',3,'LOZERE','Lozère'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (52,'49','49007',0,'MAINE-ET-LOIRE','Maine-et-Loire'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (25,'50','50502',3,'MANCHE','Manche'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (21,'51','51108',3,'MARNE','Marne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (21,'52','52121',3,'HAUTE-MARNE','Haute-Marne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (28,'50','50502',3,'MANCHE','Manche'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'51','51108',3,'MARNE','Marne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'52','52121',3,'HAUTE-MARNE','Haute-Marne'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (52,'53','53130',3,'MAYENNE','Mayenne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (41,'54','54395',0,'MEURTHE-ET-MOSELLE','Meurthe-et-Moselle'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (41,'55','55029',3,'MEUSE','Meuse'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'54','54395',0,'MEURTHE-ET-MOSELLE','Meurthe-et-Moselle'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'55','55029',3,'MEUSE','Meuse'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (53,'56','56260',2,'MORBIHAN','Morbihan'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (41,'57','57463',3,'MOSELLE','Moselle'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (26,'58','58194',3,'NIEVRE','Nièvre'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (31,'59','59350',2,'NORD','Nord'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (22,'60','60057',5,'OISE','Oise'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (25,'61','61001',5,'ORNE','Orne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (31,'62','62041',2,'PAS-DE-CALAIS','Pas-de-Calais'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (83,'63','63113',2,'PUY-DE-DOME','Puy-de-Dôme'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (72,'64','64445',4,'PYRENEES-ATLANTIQUES','Pyrénées-Atlantiques'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'65','65440',4,'HAUTES-PYRENEES','Hautes-Pyrénées'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (91,'66','66136',4,'PYRENEES-ORIENTALES','Pyrénées-Orientales'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (42,'67','67482',2,'BAS-RHIN','Bas-Rhin'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (42,'68','68066',2,'HAUT-RHIN','Haut-Rhin'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'69','69123',2,'RHONE','Rhône'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (43,'70','70550',3,'HAUTE-SAONE','Haute-Saône'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (26,'71','71270',0,'SAONE-ET-LOIRE','Saône-et-Loire'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'57','57463',3,'MOSELLE','Moselle'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'58','58194',3,'NIEVRE','Nièvre'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (32,'59','59350',2,'NORD','Nord'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (32,'60','60057',5,'OISE','Oise'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (28,'61','61001',5,'ORNE','Orne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (32,'62','62041',2,'PAS-DE-CALAIS','Pas-de-Calais'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'63','63113',2,'PUY-DE-DOME','Puy-de-Dôme'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'64','64445',4,'PYRENEES-ATLANTIQUES','Pyrénées-Atlantiques'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'65','65440',4,'HAUTES-PYRENEES','Hautes-Pyrénées'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'66','66136',4,'PYRENEES-ORIENTALES','Pyrénées-Orientales'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'67','67482',2,'BAS-RHIN','Bas-Rhin'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'68','68066',2,'HAUT-RHIN','Haut-Rhin'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'69','69123',2,'RHONE','Rhône'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'70','70550',3,'HAUTE-SAONE','Haute-Saône'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'71','71270',0,'SAONE-ET-LOIRE','Saône-et-Loire'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (52,'72','72181',3,'SARTHE','Sarthe'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'73','73065',3,'SAVOIE','Savoie'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (82,'74','74010',3,'HAUTE-SAVOIE','Haute-Savoie'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'73','73065',3,'SAVOIE','Savoie'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (84,'74','74010',3,'HAUTE-SAVOIE','Haute-Savoie'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'75','75056',0,'PARIS','Paris'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (23,'76','76540',3,'SEINE-MARITIME','Seine-Maritime'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (28,'76','76540',3,'SEINE-MARITIME','Seine-Maritime'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'77','77288',0,'SEINE-ET-MARNE','Seine-et-Marne'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'78','78646',4,'YVELINES','Yvelines'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (54,'79','79191',4,'DEUX-SEVRES','Deux-Sèvres'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (22,'80','80021',3,'SOMME','Somme'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'81','81004',2,'TARN','Tarn'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (73,'82','82121',0,'TARN-ET-GARONNE','Tarn-et-Garonne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'79','79191',4,'DEUX-SEVRES','Deux-Sèvres'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (32,'80','80021',3,'SOMME','Somme'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'81','81004',2,'TARN','Tarn'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (76,'82','82121',0,'TARN-ET-GARONNE','Tarn-et-Garonne'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'83','83137',2,'VAR','Var'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (93,'84','84007',0,'VAUCLUSE','Vaucluse'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (52,'85','85191',3,'VENDEE','Vendée'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (54,'86','86194',3,'VIENNE','Vienne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (74,'87','87085',3,'HAUTE-VIENNE','Haute-Vienne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (41,'88','88160',4,'VOSGES','Vosges'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (26,'89','89024',5,'YONNE','Yonne'); -insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (43,'90','90010',0,'TERRITOIRE DE BELFORT','Territoire de Belfort'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'86','86194',3,'VIENNE','Vienne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (75,'87','87085',3,'HAUTE-VIENNE','Haute-Vienne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (44,'88','88160',4,'VOSGES','Vosges'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'89','89024',5,'YONNE','Yonne'); +insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (27,'90','90010',0,'TERRITOIRE DE BELFORT','Territoire de Belfort'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'91','91228',5,'ESSONNE','Essonne'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'92','92050',4,'HAUTS-DE-SEINE','Hauts-de-Seine'); insert into llx_c_departements (fk_region, code_departement,cheflieu,tncc,ncc,nom) values (11,'93','93008',3,'SEINE-SAINT-DENIS','Seine-Saint-Denis'); diff --git a/htdocs/install/mysql/data/llx_accounting_abc.sql b/htdocs/install/mysql/data/llx_accounting_abc.sql index 845b68e54a4..be87c743c38 100644 --- a/htdocs/install/mysql/data/llx_accounting_abc.sql +++ b/htdocs/install/mysql/data/llx_accounting_abc.sql @@ -45,6 +45,8 @@ INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUE INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 1, 'PCG99-BASE', 'The base accountancy french plan', 1); -- Description of chart of account FR PCG14-DEV INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 1, 'PCG14-DEV', 'The developed accountancy french plan 2014', 1); +-- Description of chart of account FR PCG18-ASSOC +INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 1, 'PCG18-ASSOC', 'French foundation chart of accounts 2018', 1); -- Description of chart of account BE PCMN-BASE INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 2, 'PCMN-BASE', 'The base accountancy belgium plan', 1); diff --git a/htdocs/install/mysql/data/llx_accounting_account_fr.sql b/htdocs/install/mysql/data/llx_accounting_account_fr.sql index 0052cf86446..8f64f5d108b 100644 --- a/htdocs/install/mysql/data/llx_accounting_account_fr.sql +++ b/htdocs/install/mysql/data/llx_accounting_account_fr.sql @@ -28,6 +28,7 @@ -- ID 0 - 438 -- ID 1501 - 5999 +-- ID 7000 - 7208 -- ADD 100000 to rowid # Do no remove this comment -- INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401,'PCG99-ABREGE','CAPIT', 'XXXXXX', '1', '0', 'Fonds propres, provisions pour risques et charges et dettes à plus d''un an', 1); @@ -1466,3 +1467,133 @@ INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 5964,'PCG14-DEV','INCOME','XXXXXX','791',5963,'Transferts de charges d''exploitation','1'); INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 5965,'PCG14-DEV','INCOME','XXXXXX','796',5963,'Transferts de charges financières','1'); INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 5966,'PCG14-DEV','INCOME','XXXXXX','797',5963,'Transferts de charges exceptionnelles','1'); + +-- +-- Descriptif des plans comptables FR PCG18-ASSOC +-- + +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7201,'PCG18-ASSOC','CAPIT', 'CAPITAL', '1', '0', 'Fonds propres, emprunts et dettes assimilésFonds propres, provisions pour risques et charges et dettes à plus d''un an', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7202,'PCG18-ASSOC','IMMO', 'XXXXXX', '2', '0', 'Frais d''établissement. Actifs immobilisés et créances à plus d''un an', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7203,'PCG18-ASSOC','STOCK', 'XXXXXX', '3', '0', 'Stock et commandes en cours d''exécution', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7204,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '4', '0', 'Créances et dettes à un an au plus', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7205,'PCG18-ASSOC','FINAN', 'XXXXXX', '5', '0', 'Placement de trésorerie et de valeurs disponibles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7206,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6', '0', 'Charges', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7207,'PCG18-ASSOC','INCOME', 'XXXXXX', '7', '0', 'Produits', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7208,'PCG18-ASSOC','SPECIAL', 'XXXXXX', '8', '0', 'Comptes spéciaux', 1); + +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7000,'PCG18-ASSOC','CAPIT', 'XXXXXX', '10', '7201', 'Fonds propres et réserves', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7001,'PCG18-ASSOC','CAPIT', 'XXXXXX', '102', '7000', 'Fonds propres sans droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7002,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1021', '7001', 'Première situation nette établie', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7003,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1022', '7001', 'Fonds statutaires (à subdiviser en fonction des statuts)', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7004,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1023', '7001', 'Dotations non consomptibles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7005,'PCG18-ASSOC','CAPIT', 'XXXXXX','10231', '7004', 'Dotations non consomptibles initiales', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7006,'PCG18-ASSOC','CAPIT', 'XXXXXX','10232', '7004', 'Dotations non consomptibles complémentaires', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7007,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1024', '7001', 'Autres fonds propres sans droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7008,'PCG18-ASSOC','CAPIT', 'XXXXXX', '103', '7000', 'Fonds propres avec droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7009,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1032', '7008', 'Fonds statutaires (à subdiviser en fonction des statuts)', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7010,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1034', '7008', 'Autres fonds propres avec droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7011,'PCG18-ASSOC','CAPIT', 'XXXXXX', '105', '7000', 'Ecarts de réévaluation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7012,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1051', '7011', 'Ecarts de réévaluation sur des biens sans droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7013,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1052', '7011', 'Ecarts de réévaluation sur des biens avec droit de reprise', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7014,'PCG18-ASSOC','CAPIT', 'XXXXXX', '106', '7000', 'Réserves', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7015,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1068', '7014', 'Réserves pour projet de l’entité', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7016,'PCG18-ASSOC','CAPIT', 'XXXXXX', '108', '7000', 'Dotations consomptibles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7017,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1081', '7016', 'Dotations consomptibles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7018,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1089', '7016', 'Dotations consomptibles inscrites au compte de résultat', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7019,'PCG18-ASSOC','CAPIT', 'XXXXXX', '15', '7201', 'Provisions', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7020,'PCG18-ASSOC','CAPIT', 'XXXXXX', '152', '7019', 'Provisions pour charges sur legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7021,'PCG18-ASSOC','CAPIT', 'XXXXXX', '16', '7201', 'Emprunts et dettes assimilées', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7022,'PCG18-ASSOC','CAPIT', 'XXXXXX', '163', '7021', 'Autres emprunts obligataires', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7023,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1631', '7022', 'Titres associatifs et assimilés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7024,'PCG18-ASSOC','CAPIT', 'XXXXXX', '19', '7201', 'Fonds dédiés ou reportés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7025,'PCG18-ASSOC','CAPIT', 'XXXXXX', '191', '7024', 'Fonds reportés liés aux legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7026,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1911', '7025', 'Legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7027,'PCG18-ASSOC','CAPIT', 'XXXXXX', '1912', '7025', 'Donations temporaires d’usufruit', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7028,'PCG18-ASSOC','CAPIT', 'XXXXXX', '194', '7024', 'Fonds dédiés sur subventions d’exploitation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7029,'PCG18-ASSOC','CAPIT', 'XXXXXX', '195', '7024', 'Fonds dédiés sur contributions financières d’autres organismes', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7030,'PCG18-ASSOC','CAPIT', 'XXXXXX', '196', '7024', 'Fonds dédiés sur ressources liées à la générosité du public', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7031,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '20', '7202', 'Immobilisations incorporelles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7032,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '204', '7031', 'Donations temporaires d’usufruit', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7033,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '24', '7202', 'Biens reçus par legs ou donations destinés à être cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7034,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '27', '7202', 'Autres immobilisations financières', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7035,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '2742', '7034', 'Prêts aux partenaires', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7036,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '28', '7202', 'Amortissements des immobilisations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7037,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '280', '7036', 'Amortissements des immobilisations incorporelles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7038,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '2804', '7037', 'Donations temporaires d’usufruit', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7039,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '29', '7202', 'Dépréciations des immobilisations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7040,'PCG18-ASSOC', 'IMMO', 'XXXXXX', '294', '7039', 'Dépréciationsdes biens reçus par legs ou donations destinés à être cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7041,'PCG18-ASSOC','THIRDPARTY','CUSTOMER', '41', '7204', 'Clients, adhérents, usagers et comptes rattachés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7042,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '45', '7204', 'Confédération, fédération, union, entités affiliées', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7043,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '455', '7042', 'Partenaires - comptes courants', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7044,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '46', '7204', 'Débiteurs et créditeurs divers', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7045,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '461', '7044', 'Créances reçues par legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7046,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '466', '7044', 'Dettes des legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7047,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '468', '7044', 'Divers – charges à payer et produits à recevoir', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7048,'PCG18-ASSOC','THIRDPARTY', 'XXXXXX', '4681', '7047', 'Frais des bénévoles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7049,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '62', '7206', 'Autres services extérieurs', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7050,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '622', '7049', 'Rémunérations d’intermédiaires et honoraires', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7051,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6226', '7050', 'Honoraires', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7052,'PCG18-ASSOC','EXPENSE', 'XXXXXX','62264', '7051', 'Honoraires sur legs ou donations destinés à être cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7053,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '65', '7206', 'Autres charges de gestion courante', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7054,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '653', '7053', 'Charges de la générosité du public', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7055,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6531', '7054', 'Autres charges sur legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7056,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '657', '7053', 'Aides financières', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7057,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '67', '7206', 'Charges exceptionnelles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7058,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '673', '7057', 'Apports ou affectations en numéraire', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7059,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '675', '7057', 'Valeurs comptables des éléments d’actifs cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7060,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6754', '7059', 'Immobilisations reçues par legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7061,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '68', '7206', 'Dotations aux amortissements, provisions et engagements', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7062,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6816', '7061', 'Dotations pour dépréciations des immobilisations incorporelles et corporelles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7063,'PCG18-ASSOC','EXPENSE', 'XXXXXX','68164', '7062', 'Dotations pour dépréciation d’actifs reçus par legs ou donations destinés à être cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7064,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '689', '7061', 'Reports en fonds dédiés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7065,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6891', '7064', 'Reports en fonds reportés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7066,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6894', '7064', 'Reports en fonds dédiés sur subventions d’exploitation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7067,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6895', '7064', 'Reports en fonds dédiés sur contributions financières d’autres organismes', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7068,'PCG18-ASSOC','EXPENSE', 'XXXXXX', '6896', '7064', 'Reports en fonds dédiés sur ressources liées à la générosité du public', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7069,'PCG18-ASSOC','INCOME', 'XXXXXX', '70', '7207', 'Ventes de produits fabriqués, prestations de services, marchandises', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7070,'PCG18-ASSOC','INCOME', 'SERVICE', '706', '7069', 'Ventes de prestations de services', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7071,'PCG18-ASSOC','INCOME', 'SERVICE', '7063', '7070', 'Parrainages', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7072,'PCG18-ASSOC','INCOME', 'PRODUCT', '707', '7069', 'Ventes de marchandises', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7073,'PCG18-ASSOC','INCOME', 'PRODUCT', '7073', '7073', 'Ventes de dons en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7074,'PCG18-ASSOC','INCOME', 'XXXXXX', '73', '7207', 'Concours publics', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7075,'PCG18-ASSOC','INCOME', 'XXXXXX', '75', '7207', 'Autres produits de gestion courante', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7076,'PCG18-ASSOC','INCOME', 'XXXXXX', '753', '7075', 'Versements des fondateurs ou consommation de la dotation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7077,'PCG18-ASSOC','INCOME', 'XXXXXX', '7531', '7076', 'Versements des fondateurs', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7078,'PCG18-ASSOC','INCOME', 'XXXXXX', '7532', '7076', 'Quotes-parts de dotation consomptible virée au compte de résultat', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7079,'PCG18-ASSOC','INCOME', 'XXXXXX', '754', '7075', 'Ressources liées à la générosité du public', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7080,'PCG18-ASSOC','INCOME', 'XXXXXX', '7541', '7079', 'Dons manuels', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7081,'PCG18-ASSOC','INCOME', 'XXXXXX','75411', '7080', 'Dons manuels', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7082,'PCG18-ASSOC','INCOME', 'XXXXXX','75412', '7080', 'Abandons de frais par les bénévoles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7083,'PCG18-ASSOC','INCOME', 'XXXXXX', '7542', '7079', 'Mécénats', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7084,'PCG18-ASSOC','INCOME', 'XXXXXX', '7543', '7079', 'Legs, donations et assurances-vie', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7085,'PCG18-ASSOC','INCOME', 'XXXXXX','75431', '7084', 'Assurances-vie', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7086,'PCG18-ASSOC','INCOME', 'XXXXXX','75432', '7084', 'Legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7087,'PCG18-ASSOC','INCOME', 'XXXXXX','75433', '7084', 'Autres produits sur legs ou donations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7088,'PCG18-ASSOC','INCOME', 'XXXXXX', '755', '7075', 'Contributions financières', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7089,'PCG18-ASSOC','INCOME', 'XXXXXX', '7551', '7088', 'Contributions financières d’autres organismes', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7090,'PCG18-ASSOC','INCOME', 'XXXXXX', '7552', '7088', 'Quotes-parts de générosité reçues', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7091,'PCG18-ASSOC','INCOME', 'XXXXXX', '756', '7075', 'Cotisations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7092,'PCG18-ASSOC','INCOME', 'XXXXXX', '7561', '7091', 'Cotisations sans contrepartie', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7093,'PCG18-ASSOC','INCOME', 'XXXXXX', '7562', '7091', 'Cotisations avec contrepartie', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7094,'PCG18-ASSOC','INCOME', 'XXXXXX', '757', '7075', 'Gains de change sur créances et dettes d’exploitation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7095,'PCG18-ASSOC','INCOME', 'XXXXXX', '77', '7207', 'Produits exceptionnels', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7096,'PCG18-ASSOC','INCOME', 'XXXXXX', '775', '7095', 'Produits des cessions d’éléments d’actifs', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7097,'PCG18-ASSOC','INCOME', 'XXXXXX', '7754', '7096', 'Immobilisations reçues en legs ou donations destinées à être cédées', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7098,'PCG18-ASSOC','INCOME', 'XXXXXX', '78', '7207', 'Reprises sur amortissements, dépréciations et provisions', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7099,'PCG18-ASSOC','INCOME', 'XXXXXX', '781', '7098', 'Reprises sur amortissements des immobilisations dépréciations et provisions (à inscrire dans les produits d’exploitation)', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7100,'PCG18-ASSOC','INCOME', 'XXXXXX', '7816', '7099', 'Reprises sur dépréciations des immobilisations incorporelles et corporelles', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7101,'PCG18-ASSOC','INCOME', 'XXXXXX','78164', '7100', 'Reprises sur dépréciations d’actifs reçus par legs ou donations destinés à être cédés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7102,'PCG18-ASSOC','INCOME', 'XXXXXX', '789', '7098', 'Utilisations de fonds reportés et de fonds dédiés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7103,'PCG18-ASSOC','INCOME', 'XXXXXX', '7891', '7102', 'Utilisations de fonds reportés', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7104,'PCG18-ASSOC','INCOME', 'XXXXXX', '7894', '7102', 'Utilisations des fonds dédiés sur subventions d’exploitation', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7105,'PCG18-ASSOC','INCOME', 'XXXXXX', '7895', '7102', 'Utilisations des fonds dédiés sur contributions financières d’autres organismes', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7106,'PCG18-ASSOC','INCOME', 'XXXXXX', '7896', '7102', 'Utilisations des fonds dédiés sur ressources liées à la générosité du public', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7107,'PCG18-ASSOC','INCOME', 'XXXXXX', '86', '7208', 'Emplois des contributions volontaires en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7108,'PCG18-ASSOC','INCOME', 'XXXXXX', '860', '7107', 'Secours en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7109,'PCG18-ASSOC','INCOME', 'XXXXXX', '861', '7107', 'Mises à disposition gratuite de biens', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7110,'PCG18-ASSOC','INCOME', 'XXXXXX', '862', '7107', 'Prestations', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7111,'PCG18-ASSOC','INCOME', 'XXXXXX', '864', '7107', 'Personnel bénévole', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7112,'PCG18-ASSOC','INCOME', 'XXXXXX', '87', '7208', 'Contributions volontaires en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7113,'PCG18-ASSOC','INCOME', 'XXXXXX', '870', '7112', 'Dons en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7114,'PCG18-ASSOC','INCOME', 'XXXXXX', '871', '7112', 'Prestations en nature', 1); +INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, active) VALUES (__ENTITY__, 7115,'PCG18-ASSOC','INCOME', 'XXXXXX', '875', '7112', 'Bénévolat', 1); \ No newline at end of file diff --git a/htdocs/install/mysql/data/llx_c_forme_juridique.sql b/htdocs/install/mysql/data/llx_c_forme_juridique.sql index d57c9a7081d..628d42d4144 100644 --- a/htdocs/install/mysql/data/llx_c_forme_juridique.sql +++ b/htdocs/install/mysql/data/llx_c_forme_juridique.sql @@ -127,7 +127,7 @@ insert into llx_c_forme_juridique (fk_pays, code, libelle) values (1,'99','Perso -- Belgium insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '200', 'Indépendant'); -insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '201', 'SPRL - Société à responsabilité limitée'); +insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '201', 'SRL - Société à responsabilité limitée'); insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '202', 'SA - Société Anonyme'); insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '203', 'SCRL - Société coopérative à responsabilité limitée'); insert into llx_c_forme_juridique (fk_pays, code, libelle) values (2, '204', 'ASBL - Association sans but Lucratif'); diff --git a/htdocs/install/mysql/data/llx_c_ticket_resolution.sql b/htdocs/install/mysql/data/llx_c_ticket_resolution.sql new file mode 100644 index 00000000000..2fa139b602d --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_ticket_resolution.sql @@ -0,0 +1,22 @@ +-- Copyright (C) 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 . +-- +-- +-- Contenu de la table llx_c_ticket_resolution +-- + +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('SOLVED', '10', 'Solved', 1, 0, NULL); +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('CANCELED', '50', 'Canceled', 1, 0, NULL); +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('OTHER', '90', 'Other', 1, 0, NULL); diff --git a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql index 9f3d092e846..179fdf80dcc 100644 --- a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql +++ b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql @@ -75,7 +75,7 @@ UPDATE llx_holiday SET ref = rowid WHERE ref IS NULL; -- VPGSQL8.2 ALTER TABLE llx_holiday ALTER COLUMN ref SET NOT NULL; ALTER TABLE llx_c_email_senderprofile MODIFY COLUMN active tinyint DEFAULT 1 NOT NULL; - + insert into llx_c_type_container (code,label,module,active) values ('menu', 'Menu', 'system', 1); INSERT INTO llx_c_ticket_type (code, pos, label, active, use_default, description) VALUES('HELP', '15', 'Request for functionnal help', 1, 0, NULL); @@ -534,22 +534,22 @@ ALTER TABLE llx_comment ADD COLUMN fk_user_modif integer DEFAULT NULL; CREATE TABLE llx_mrp_production( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - fk_mo integer NOT NULL, + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_mo integer NOT NULL, position integer NOT NULL DEFAULT 0, - fk_product integer NOT NULL, + fk_product integer NOT NULL, fk_warehouse integer, qty real NOT NULL DEFAULT 1, qty_frozen smallint DEFAULT 0, - disable_stock_change smallint DEFAULT 0, + disable_stock_change smallint DEFAULT 0, batch varchar(30), role varchar(10), -- 'toconsume' or 'toproduce' (initialized at MO creation), 'consumed' or 'produced' (added after MO validation) fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' fk_stock_movement integer, -- id of stock movement when movements are validated - date_creation datetime NOT NULL, - tms timestamp, - fk_user_creat integer NOT NULL, - fk_user_modif integer, + date_creation datetime NOT NULL, + tms timestamp, + fk_user_creat integer NOT NULL, + fk_user_modif integer, import_key varchar(14) ) ENGINE=innodb; ALTER TABLE llx_mrp_production MODIFY COLUMN qty real NOT NULL DEFAULT 1; @@ -568,3 +568,14 @@ ALTER TABLE llx_emailcollector_emailcollector ADD UNIQUE INDEX uk_emailcollector ALTER TABLE llx_website ADD COLUMN use_manifest integer; ALTER TABLE llx_facture_rec MODIFY COLUMN fk_cond_reglement integer NOT NULL DEFAULT 1; + +create table llx_commande_fournisseur_dispatch_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, -- object id + import_key varchar(14) -- import key +)ENGINE=innodb; + +ALTER TABLE llx_commande_fournisseur_dispatch_extrafields ADD INDEX idx_commande_fournisseur_dispatch_extrafields (fk_object); + diff --git a/htdocs/install/mysql/migration/11.0.0-12.0.0.sql b/htdocs/install/mysql/migration/11.0.0-12.0.0.sql new file mode 100644 index 00000000000..bce7725871a --- /dev/null +++ b/htdocs/install/mysql/migration/11.0.0-12.0.0.sql @@ -0,0 +1,161 @@ +-- +-- Be carefull to requests order. +-- This file must be loaded by calling /install/index.php page +-- when current version is 12.0.0 or higher. +-- +-- To restrict request to Mysql version x.y minimum use -- VMYSQLx.y +-- To restrict request to Pgsql version x.y minimum use -- VPGSQLx.y +-- To rename a table: ALTER TABLE llx_table RENAME TO llx_table_new; +-- To add a column: ALTER TABLE llx_table ADD COLUMN newcol varchar(60) NOT NULL DEFAULT '0' AFTER existingcol; +-- To rename a column: ALTER TABLE llx_table CHANGE COLUMN oldname newname varchar(60); +-- To drop a column: ALTER TABLE llx_table DROP COLUMN oldname; +-- To change type of field: ALTER TABLE llx_table MODIFY COLUMN name varchar(60); +-- To drop a foreign key: ALTER TABLE llx_table DROP FOREIGN KEY fk_name; +-- To create a unique index ALTER TABLE llx_table ADD UNIQUE INDEX uk_table_field (field); +-- To drop an index: -- VMYSQL4.1 DROP INDEX nomindex on llx_table +-- To drop an index: -- VPGSQL8.2 DROP INDEX nomindex +-- To make pk to be auto increment (mysql): -- VMYSQL4.3 ALTER TABLE llx_table CHANGE COLUMN rowid rowid INTEGER NOT NULL AUTO_INCREMENT; +-- To make pk to be auto increment (postgres): +-- -- VPGSQL8.2 CREATE SEQUENCE llx_table_rowid_seq OWNED BY llx_table.rowid; +-- -- VPGSQL8.2 ALTER TABLE llx_table ADD PRIMARY KEY (rowid); +-- -- VPGSQL8.2 ALTER TABLE llx_table ALTER COLUMN rowid SET DEFAULT nextval('llx_table_rowid_seq'); +-- -- VPGSQL8.2 SELECT setval('llx_table_rowid_seq', MAX(rowid)) FROM llx_table; +-- To set a field as NULL: -- VMYSQL4.3 ALTER TABLE llx_table MODIFY COLUMN name varchar(60) NULL; +-- To set a field as NULL: -- VPGSQL8.2 ALTER TABLE llx_table ALTER COLUMN name DROP NOT NULL; +-- To set a field as NOT NULL: -- VMYSQL4.3 ALTER TABLE llx_table MODIFY COLUMN name varchar(60) NOT NULL; +-- To set a field as NOT NULL: -- VPGSQL8.2 ALTER TABLE llx_table ALTER COLUMN name SET NOT NULL; +-- To set a field as default NULL: -- VPGSQL8.2 ALTER TABLE llx_table ALTER COLUMN name SET DEFAULT NULL; +-- Note: fields with type BLOB/TEXT can't have default value. + + +-- Missing in v11 + +create table llx_commande_fournisseur_dispatch_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, -- object id + import_key varchar(14) -- import key +)ENGINE=innodb; + +ALTER TABLE llx_commande_fournisseur_dispatch_extrafields ADD INDEX idx_commande_fournisseur_dispatch_extrafields (fk_object); + + + +-- For v12 + +ALTER TABLE llx_holiday_users DROP INDEX uk_holiday_users; +ALTER TABLE llx_holiday_users ADD UNIQUE INDEX uk_holiday_users(fk_user, fk_type); + +ALTER TABLE llx_ticket ADD COLUMN import_key varchar(14); + +--ALTER TABLE llx_facturerec DROP COLUMN vat_src_code; + + +-- Migration to the new regions (France) +UPDATE llx_c_regions set nom = 'Centre-Val de Loire' WHERE fk_pays = 1 AND code_region = 24; +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 27, '21231', 0, 'Bourgogne-Franche-Comté'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 28, '76540', 0, 'Normandie'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 32, '59350', 4, 'Hauts-de-France'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 44, '67482', 2, 'Grand Est'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 75, '33063', 0, 'Nouvelle-Aquitaine'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 76, '31355', 1, 'Occitanie'); +insert into llx_c_regions (fk_pays,code_region,cheflieu,tncc,nom) values (1, 84, '69123', 1, 'Auvergne-Rhône-Alpes'); + +UPDATE llx_c_departements set fk_region = 27 WHERE fk_region = 26 OR fk_region = 43; +UPDATE llx_c_departements set fk_region = 28 WHERE fk_region = 25 OR fk_region = 23; +UPDATE llx_c_departements set fk_region = 32 WHERE fk_region = 22 OR fk_region = 31; +UPDATE llx_c_departements set fk_region = 44 WHERE fk_region = 21 OR fk_region = 41 OR fk_region = 42; +UPDATE llx_c_departements set fk_region = 75 WHERE fk_region = 54 OR fk_region = 74 OR fk_region = 72; +UPDATE llx_c_departements set fk_region = 76 WHERE fk_region = 73 OR fk_region = 91; +UPDATE llx_c_departements set fk_region = 84 WHERE fk_region = 82 OR fk_region = 83; + +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 21; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 22; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 23; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 25; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 26; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 31; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 41; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 42; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 43; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 54; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 72; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 73; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 74; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 82; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 83; +DELETE FROM llx_c_regions WHERE fk_pays = 1 AND code_region = 91; + +ALTER TABLE llx_bookmark DROP INDEX uk_bookmark_url; +ALTER TABLE llx_bookmark DROP INDEX uk_bookmark_title; + +ALTER TABLE llx_bookmark MODIFY COLUMN url TEXT; + +ALTER TABLE llx_bookmark ADD UNIQUE uk_bookmark_title (fk_user, entity, title); + + +ALTER TABLE llx_societe_rib ADD COLUMN stripe_account varchar(128); + +create table llx_object_lang +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + fk_object integer DEFAULT 0 NOT NULL, + type_object varchar(32) NOT NULL, + property varchar(32) NOT NULL, + lang varchar(5) DEFAULT 0 NOT NULL, + value text, + import_key varchar(14) DEFAULT NULL +)ENGINE=innodb; + + +ALTER TABLE llx_object_lang ADD UNIQUE INDEX uk_object_lang (fk_object, type_object, property, lang); + + +CREATE TABLE llx_categorie_actioncomm +( + fk_categorie integer NOT NULL, + fk_actioncomm integer NOT NULL, + import_key varchar(14) +) ENGINE=innodb; + +ALTER TABLE llx_categorie_actioncomm ADD PRIMARY KEY pk_categorie_actioncomm (fk_categorie, fk_actioncomm); +ALTER TABLE llx_categorie_actioncomm ADD INDEX idx_categorie_actioncomm_fk_categorie (fk_categorie); +ALTER TABLE llx_categorie_actioncomm ADD INDEX idx_categorie_actioncomm_fk_actioncomm (fk_actioncomm); + +ALTER TABLE llx_categorie_actioncomm ADD CONSTRAINT fk_categorie_actioncomm_categorie_rowid FOREIGN KEY (fk_categorie) REFERENCES llx_categorie (rowid); +ALTER TABLE llx_categorie_actioncomm ADD CONSTRAINT fk_categorie_actioncomm_fk_actioncomm FOREIGN KEY (fk_actioncomm) REFERENCES llx_actioncomm (id); + + +ALTER TABLE llx_accounting_account ADD COLUMN labelshort varchar(255) DEFAULT NULL after label; + +ALTER TABLE llx_subscription ADD COLUMN fk_user_creat integer DEFAULT NULL; +ALTER TABLE llx_subscription ADD COLUMN fk_user_valid integer DEFAULT NULL; + +UPDATE llx_c_forme_juridique set libelle = 'SRL - Société à responsabilité limitée' WHERE code = '201'; + +ALTER TABLE llx_c_country ADD COLUMN eec integer; +UPDATE llx_c_country SET eec = 1 WHERE code IN ('AT','BE','BG','CY','CZ','DE','DK','EE','ES','FI','FR','GB','GR','HR','NL','HU','IE','IM','IT','LT','LU','LV','MC','MT','PL','PT','RO','SE','SK','SI','UK'); + +INSERT INTO llx_accounting_system (fk_country, pcg_version, label, active) VALUES ( 1, 'PCG18-ASSOC', 'French foundation chart of accounts 2018', 1); + + + +create table llx_c_ticket_resolution +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; + +ALTER TABLE llx_c_ticket_resolution ADD UNIQUE INDEX uk_code (code, entity); + +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('SOLVED', '10', 'Solved', 1, 0, NULL); +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('CANCELED', '50', 'Canceled', 1, 0, NULL); +INSERT INTO llx_c_ticket_resolution (code, pos, label, active, use_default, description) VALUES('OTHER', '90', 'Other', 1, 0, NULL); + diff --git a/htdocs/install/mysql/tables/llx_accounting_account.sql b/htdocs/install/mysql/tables/llx_accounting_account.sql index e06faab0f00..3dbe025dbd3 100644 --- a/htdocs/install/mysql/tables/llx_accounting_account.sql +++ b/htdocs/install/mysql/tables/llx_accounting_account.sql @@ -1,7 +1,7 @@ -- ============================================================================ -- Copyright (C) 2004-2006 Laurent Destailleur -- Copyright (C) 2014 Juanjo Menent --- Copyright (C) 2016 Alexandre Spangaro +-- Copyright (C) 2016-2020 Alexandre Spangaro -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by @@ -31,6 +31,7 @@ create table llx_accounting_account account_number varchar(32) NOT NULL, account_parent integer DEFAULT 0, -- Hierarchic parent. label varchar(255) NOT NULL, + labelshort varchar(255) DEFAULT NULL, fk_accounting_category integer DEFAULT 0, -- ID of personalized group for report fk_user_author integer DEFAULT NULL, fk_user_modif integer DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_bookmark.key.sql b/htdocs/install/mysql/tables/llx_bookmark.key.sql index f933939ceb7..2c0cac1922e 100644 --- a/htdocs/install/mysql/tables/llx_bookmark.key.sql +++ b/htdocs/install/mysql/tables/llx_bookmark.key.sql @@ -17,5 +17,4 @@ -- =================================================================== -ALTER TABLE llx_bookmark ADD UNIQUE uk_bookmark_url (fk_user, url); -ALTER TABLE llx_bookmark ADD UNIQUE uk_bookmark_title (fk_user, title); +ALTER TABLE llx_bookmark ADD UNIQUE uk_bookmark_title (fk_user, entity, title); diff --git a/htdocs/install/mysql/tables/llx_bookmark.sql b/htdocs/install/mysql/tables/llx_bookmark.sql index 1c11525528c..6a76ed38343 100644 --- a/htdocs/install/mysql/tables/llx_bookmark.sql +++ b/htdocs/install/mysql/tables/llx_bookmark.sql @@ -21,7 +21,7 @@ create table llx_bookmark rowid integer AUTO_INCREMENT PRIMARY KEY, fk_user integer NOT NULL, dateb datetime, - url varchar(255) NOT NULL, + url TEXT, target varchar(16), title varchar(64), favicon varchar(24), diff --git a/htdocs/install/mysql/tables/llx_c_country.sql b/htdocs/install/mysql/tables/llx_c_country.sql index 0a2cff4bc30..7f7ba0d4113 100644 --- a/htdocs/install/mysql/tables/llx_c_country.sql +++ b/htdocs/install/mysql/tables/llx_c_country.sql @@ -24,6 +24,7 @@ create table llx_c_country code varchar(2) NOT NULL, code_iso varchar(3) , label varchar(50) NOT NULL, + eec integer , active tinyint DEFAULT 1 NOT NULL, favorite tinyint DEFAULT 0 NOT NULL )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_ticket_resolution.key.sql b/htdocs/install/mysql/tables/llx_c_ticket_resolution.key.sql new file mode 100644 index 00000000000..ac3690b70bb --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticket_resolution.key.sql @@ -0,0 +1,18 @@ +-- 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 +-- the Free Software Foundation; either version 2 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 . +-- +-- + +ALTER TABLE llx_c_ticket_resolution ADD UNIQUE INDEX uk_code (code, entity); diff --git a/htdocs/install/mysql/tables/llx_c_ticket_resolution.sql b/htdocs/install/mysql/tables/llx_c_ticket_resolution.sql new file mode 100644 index 00000000000..2f6d0d1d3da --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_ticket_resolution.sql @@ -0,0 +1,28 @@ +-- 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 +-- the Free Software Foundation; either version 2 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 . +-- +-- + +create table llx_c_ticket_resolution +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1, + code varchar(32) NOT NULL, + pos varchar(32) NOT NULL, + label varchar(128) NOT NULL, + active integer DEFAULT 1, + use_default integer DEFAULT 1, + description varchar(255) +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_categorie_actioncomm.key.sql b/htdocs/install/mysql/tables/llx_categorie_actioncomm.key.sql new file mode 100644 index 00000000000..30357eb87bc --- /dev/null +++ b/htdocs/install/mysql/tables/llx_categorie_actioncomm.key.sql @@ -0,0 +1,25 @@ +-- ============================================================================ +-- Copyright (C) 2016 Charlie Benke +-- Copyright (C) 2016-2019 Frédéric France +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- ============================================================================ + +ALTER TABLE llx_categorie_actioncomm ADD PRIMARY KEY pk_categorie_actioncomm (fk_categorie, fk_actioncomm); +ALTER TABLE llx_categorie_actioncomm ADD INDEX idx_categorie_actioncomm_fk_categorie (fk_categorie); +ALTER TABLE llx_categorie_actioncomm ADD INDEX idx_categorie_actioncomm_fk_actioncomm (fk_actioncomm); + +ALTER TABLE llx_categorie_actioncomm ADD CONSTRAINT fk_categorie_actioncomm_categorie_rowid FOREIGN KEY (fk_categorie) REFERENCES llx_categorie (rowid); +ALTER TABLE llx_categorie_actioncomm ADD CONSTRAINT fk_categorie_actioncomm_fk_actioncomm FOREIGN KEY (fk_actioncomm) REFERENCES llx_actioncomm (id); diff --git a/htdocs/install/mysql/tables/llx_categorie_actioncomm.sql b/htdocs/install/mysql/tables/llx_categorie_actioncomm.sql new file mode 100644 index 00000000000..52aa2a2c95d --- /dev/null +++ b/htdocs/install/mysql/tables/llx_categorie_actioncomm.sql @@ -0,0 +1,26 @@ +-- ============================================================================ +-- Copyright (C) 2016 Charlie Benke +-- Copyright (C) 2016-2019 Frédéric France +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- Table to link actioncomm tag/categories with actioncomms +-- =========================================================================== + +CREATE TABLE llx_categorie_actioncomm +( + fk_categorie integer NOT NULL, + fk_actioncomm integer NOT NULL, + import_key varchar(14) +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_contrat.sql b/htdocs/install/mysql/tables/llx_contrat.sql index d3f84a8bb6c..fbb36a5674b 100644 --- a/htdocs/install/mysql/tables/llx_contrat.sql +++ b/htdocs/install/mysql/tables/llx_contrat.sql @@ -30,7 +30,6 @@ create table llx_contrat datec datetime, -- creation date date_contrat datetime, statut smallint DEFAULT 0, -- not used. deprecated - mise_en_service datetime, fin_validite datetime, date_cloture datetime, fk_soc integer NOT NULL, @@ -39,7 +38,6 @@ create table llx_contrat fk_commercial_suivi integer, -- obsolete fk_user_author integer NOT NULL default 0, fk_user_modif integer, - fk_user_mise_en_service integer, fk_user_cloture integer, note_private text, note_public text, diff --git a/htdocs/install/mysql/tables/llx_facture.sql b/htdocs/install/mysql/tables/llx_facture.sql index 3b49ef04010..5a2d5464cfc 100644 --- a/htdocs/install/mysql/tables/llx_facture.sql +++ b/htdocs/install/mysql/tables/llx_facture.sql @@ -34,7 +34,6 @@ create table llx_facture ref_client varchar(255), -- reference for customer type smallint DEFAULT 0 NOT NULL, -- type of invoice - increment varchar(10), fk_soc integer NOT NULL, datec datetime, -- date de creation de la facture datef date, -- date invoice @@ -43,7 +42,7 @@ create table llx_facture tms timestamp, -- date creation/modification date_closing datetime, -- date de cloture paye smallint DEFAULT 0 NOT NULL, - amount double(24,8) DEFAULT 0 NOT NULL, + --amount double(24,8) DEFAULT 0 NOT NULL, remise_percent real DEFAULT 0, -- remise relative remise_absolue real DEFAULT 0, -- remise absolue remise real DEFAULT 0, -- remise totale calculee @@ -70,6 +69,7 @@ create table llx_facture fk_fac_rec_source integer, -- facture rec source fk_facture_source integer, -- facture origin if credit notes or replacement invoice fk_projet integer DEFAULT NULL, -- project invoice is linked to + increment varchar(10), -- Numero of generation if generated from recurring template invoice fk_account integer, -- bank account fk_currency varchar(3), -- currency code diff --git a/htdocs/install/mysql/tables/llx_holiday_users.key.sql b/htdocs/install/mysql/tables/llx_holiday_users.key.sql index 0a055b6006a..8ac7919e658 100644 --- a/htdocs/install/mysql/tables/llx_holiday_users.key.sql +++ b/htdocs/install/mysql/tables/llx_holiday_users.key.sql @@ -1,5 +1,5 @@ -- =================================================================== --- Copyright (C) 2017 Laurent Destailleur +-- Copyright (C) 2017-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 @@ -16,4 +16,4 @@ -- -- =================================================================== -ALTER TABLE llx_holiday_users ADD UNIQUE INDEX uk_holiday_users(fk_user, fk_type, nb_holiday); +ALTER TABLE llx_holiday_users ADD UNIQUE INDEX uk_holiday_users(fk_user, fk_type); diff --git a/htdocs/install/mysql/tables/llx_holiday_users.sql b/htdocs/install/mysql/tables/llx_holiday_users.sql index 1d3bcbc9361..3f9a7e61d0a 100644 --- a/htdocs/install/mysql/tables/llx_holiday_users.sql +++ b/htdocs/install/mysql/tables/llx_holiday_users.sql @@ -1,5 +1,5 @@ -- =================================================================== --- Copyright (C) 2012-2015 Laurent Destailleur +-- Copyright (C) 2012-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 @@ -14,6 +14,7 @@ -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . -- +-- Table with remain quantity of holiday for each type of leave. -- =================================================================== CREATE TABLE llx_holiday_users diff --git a/htdocs/install/mysql/tables/llx_object_lang.key.sql b/htdocs/install/mysql/tables/llx_object_lang.key.sql new file mode 100644 index 00000000000..31cda3c8bfa --- /dev/null +++ b/htdocs/install/mysql/tables/llx_object_lang.key.sql @@ -0,0 +1,20 @@ +-- ============================================================================ +-- Copyright (C) 2019 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 . +-- +-- ============================================================================ + + +ALTER TABLE llx_object_lang ADD UNIQUE INDEX uk_object_lang (fk_object, type_object, property, lang); diff --git a/htdocs/install/mysql/tables/llx_object_lang.sql b/htdocs/install/mysql/tables/llx_object_lang.sql new file mode 100644 index 00000000000..9bbc296d27c --- /dev/null +++ b/htdocs/install/mysql/tables/llx_object_lang.sql @@ -0,0 +1,31 @@ +-- ============================================================================ +-- Copyright (C) 2019 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 . +-- +-- ============================================================================ + + +-- Table to store some translations of values of objects + +create table llx_object_lang +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + fk_object integer DEFAULT 0 NOT NULL, + type_object varchar(32) NOT NULL, -- 'thirdparty', 'contact', '...' + property varchar(32) NOT NULL, + lang varchar(5) DEFAULT 0 NOT NULL, + value text, + import_key varchar(14) DEFAULT NULL +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 45084179908..7d00d9fb1dd 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -28,7 +28,7 @@ create table llx_societe_rib fk_soc integer NOT NULL, datec datetime, tms timestamp, - + -- For BAN bank varchar(255), -- bank name code_banque varchar(128), -- bank code @@ -66,6 +66,7 @@ create table llx_societe_rib --For Stripe stripe_card_ref varchar(128), -- 'card_...' + stripe_account varchar(128), -- 'pk_live_...' comment varchar(255), ipaddress varchar(68), diff --git a/htdocs/install/mysql/tables/llx_subscription.sql b/htdocs/install/mysql/tables/llx_subscription.sql index 85e2ae716ef..a3562f12c57 100644 --- a/htdocs/install/mysql/tables/llx_subscription.sql +++ b/htdocs/install/mysql/tables/llx_subscription.sql @@ -27,5 +27,7 @@ create table llx_subscription datef date, subscription double(24,8), fk_bank integer DEFAULT NULL, + fk_user_creat integer DEFAULT NULL, + fk_user_valid integer DEFAULT NULL, note text )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticket.sql b/htdocs/install/mysql/tables/llx_ticket.sql index 3f3cdf58cd9..82e692a7f0d 100644 --- a/htdocs/install/mysql/tables/llx_ticket.sql +++ b/htdocs/install/mysql/tables/llx_ticket.sql @@ -38,5 +38,6 @@ CREATE TABLE llx_ticket date_read datetime, date_close datetime, notify_tiers_at_create tinyint, - tms timestamp + tms timestamp, + import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php index c5d1d7837e9..b3ff583042d 100644 --- a/htdocs/install/upgrade2.php +++ b/htdocs/install/upgrade2.php @@ -983,7 +983,7 @@ function migrate_contracts_det($db, $langs, $conf) print '
'; print ''.$langs->trans('MigrationContractsUpdate')."
\n"; - $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.mise_en_service, c.fin_validite, c.date_cloture, c.fk_product, c.fk_facture, c.fk_user_author,"; + $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.fk_product, c.fk_facture, c.fk_user_author,"; $sql .= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p"; @@ -1014,15 +1014,15 @@ function migrate_contracts_det($db, $langs, $conf) $sql .= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,"; $sql .= "subprice, price_ht, fk_user_author, fk_user_ouverture)"; $sql .= " VALUES ("; - $sql .= $obj->cref.",".($obj->fk_product ? $obj->fk_product : 0).","; - $sql .= ($obj->mise_en_service ? "4" : "0").","; - $sql .= "'".$db->escape($obj->label)."', null,"; - $sql .= ($obj->mise_en_service ? "'".$obj->mise_en_service."'" : ($obj->date_contrat ? "'".$obj->date_contrat."'" : "null")).","; - $sql .= ($obj->mise_en_service ? "'".$obj->mise_en_service."'" : "null").","; - $sql .= ($obj->fin_validite ? "'".$obj->fin_validite."'" : "null").","; - $sql .= "'".$obj->tva_tx."', 1,"; - $sql .= "'".$obj->price."', '".$obj->price."',".$obj->fk_user_author.","; - $sql .= ($obj->mise_en_service ? $obj->fk_user_author : "null"); + $sql .= $obj->cref.", ".($obj->fk_product ? $obj->fk_product : 0).", "; + $sql .= "0, "; + $sql .= "'".$db->escape($obj->label)."', null, "; + $sql .= ($obj->date_contrat ? "'".$obj->date_contrat."'" : "null").", "; + $sql .= "null, "; + $sql .= "null, "; + $sql .= "'".$obj->tva_tx."' , 1, "; + $sql .= "'".$obj->price."', '".$obj->price."', ".$obj->fk_user_author.","; + $sql .= "null"; $sql .= ")"; if ($db->query($sql)) diff --git a/htdocs/langs/de_DE/holiday.lang b/htdocs/langs/de_DE/holiday.lang index 5fea5c32a28..f2c467e72b2 100644 --- a/htdocs/langs/de_DE/holiday.lang +++ b/htdocs/langs/de_DE/holiday.lang @@ -131,3 +131,5 @@ FreeLegalTextOnHolidays=Freitext als PDF WatermarkOnDraftHolidayCards=Wasserzeichen auf Urlaubsantragsentwurf (leerlassen wenn keines benötigt wird) HolidaysToApprove=Urlaubstage zu genehmigen NobodyHasPermissionToValidateHolidays=Niemand hat die Erlaubnis, Feiertage zu bestätigen. +Morning=Vormittags +Afternoon=Nachmittags diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 336bf2a35cd..c8302b9617e 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -270,6 +270,7 @@ ChangeBinding=Change the binding Accounted=Accounted in ledger NotYetAccounted=Not yet accounted in ledger ShowTutorial=Show Tutorial +NotReconciled=Not reconciled ## Admin ApplyMassCategories=Apply mass categories diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 0bf914d0e22..6ec05d5e956 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -1716,8 +1716,9 @@ ChequeReceiptsNumberingModule=Check Receipts Numbering Module MultiCompanySetup=Multi-company module setup ##### Suppliers ##### SuppliersSetup=Vendor module setup -SuppliersCommandModel=Complete template of purchase order (logo...) -SuppliersInvoiceModel=Complete template of vendor invoice (logo...) +SuppliersCommandModel=Complete template of Purchase Order +SuppliersCommandModelMuscadet=Complete template of Purchase Order (old implementation of cornas template) +SuppliersInvoiceModel=Complete template of Vendor Invoice SuppliersInvoiceNumberingModel=Vendor invoices numbering models IfSetToYesDontForgetPermission=If set to a non null value, don't forget to provide permissions to groups or users allowed for the second approval ##### GeoIPMaxmind ##### @@ -1793,6 +1794,7 @@ BackgroundTableLineEvenColor=Background color for even table lines MinimumNoticePeriod=Minimum notice period (Your leave request must be done before this delay) NbAddedAutomatically=Number of days added to counters of users (automatically) each month EnterAnyCode=This field contains a reference to identify line. Enter any value of your choice, but without special characters. +Enter0or1=Enter 0 or 1 UnicodeCurrency=Enter here between braces, list of byte number that represent the currency symbol. For example: for $, enter [36] - for brazil real R$ [82,36] - for €, enter [8364] ColorFormat=The RGB color is in HEX format, eg: FF0000 PositionIntoComboList=Position of line into combo lists diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang index 5e56ca9a875..2f68cbeda58 100644 --- a/htdocs/langs/en_US/agenda.lang +++ b/htdocs/langs/en_US/agenda.lang @@ -123,6 +123,7 @@ AgendaUrlOptionsNotAdmin=logina=!%s to restrict output to actions not own AgendaUrlOptions4=logint=%s to restrict output to actions assigned to user %s (owner and others). AgendaUrlOptionsProject=project=__PROJECT_ID__ to restrict output to actions linked to project __PROJECT_ID__. AgendaUrlOptionsNotAutoEvent=notactiontype=systemauto to exclude automatic events. +AgendaUrlOptionsIncludeHolidays=includeholidays=1 to include events of holidays. AgendaShowBirthdayEvents=Show birthdays of contacts AgendaHideBirthdayEvents=Hide birthdays of contacts Busy=Busy diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 6e26ecb6835..6d7c61784f7 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -419,6 +419,7 @@ PaymentCondition14DENDMONTH=Within 14 days following the end of the month FixAmount=Fixed amount - 1 line with label '%s' VarAmount=Variable amount (%% tot.) VarAmountOneLine=Variable amount (%% tot.) - 1 line with label '%s' +VarAmountAllLines=Variable amount (%% tot.) - all same lines # PaymentType PaymentTypeVIR=Bank transfer PaymentTypeShortVIR=Bank transfer @@ -512,7 +513,7 @@ RevenueStamp=Revenue stamp YouMustCreateInvoiceFromThird=This option is only available when creating an invoice from tab "Customer" of third party YouMustCreateInvoiceFromSupplierThird=This option is only available when creating an invoice from tab "Vendor" of third party YouMustCreateStandardInvoiceFirstDesc=You have to create a standard invoice first and convert it to "template" to create a new template invoice -PDFCrabeDescription=Invoice PDF template Crabe. A complete invoice template (recommended Template) +PDFCrabeDescription=Invoice PDF template Crabe. A complete invoice template (old implementation of Sponge template) PDFSpongeDescription=Invoice PDF template Sponge. A complete invoice template PDFCrevetteDescription=Invoice PDF template Crevette. A complete invoice template for situation invoices TerreNumRefModelDesc1=Return number with format %syymm-nnnn for standard invoices and %syymm-nnnn for credit notes where yy is year, mm is month and nnnn is a sequence with no break and no return to 0 diff --git a/htdocs/langs/en_US/cashdesk.lang b/htdocs/langs/en_US/cashdesk.lang index 964bd7c436c..9ba2a068478 100644 --- a/htdocs/langs/en_US/cashdesk.lang +++ b/htdocs/langs/en_US/cashdesk.lang @@ -81,3 +81,6 @@ CustomReceipt=Custom Receipt ReceiptName=Receipt Name ProductSupplements=Product Supplements SupplementCategory=Supplement category +ColorTheme=Color theme +Colorful=Colorful +HeadBar=Head Bar diff --git a/htdocs/langs/en_US/categories.lang b/htdocs/langs/en_US/categories.lang index b6f64d8fbb8..7207bbacc38 100644 --- a/htdocs/langs/en_US/categories.lang +++ b/htdocs/langs/en_US/categories.lang @@ -90,4 +90,5 @@ ShowCategory=Show tag/category ByDefaultInList=By default in list ChooseCategory=Choose category StocksCategoriesArea=Warehouses Categories Area +ActionCommCategoriesArea=Events Categories Area UseOrOperatorForCategories=Use or operator for categories diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index d95cdc0772e..c569a48c84a 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -247,6 +247,12 @@ ProfId3US=- ProfId4US=- ProfId5US=- ProfId6US=- +ProfId1RO=Prof Id 1 (CUI) +ProfId2RO=Prof Id 2 (Nr. Înmatriculare) +ProfId3RO=Prof Id 3 (CAEN) +ProfId4RO=- +ProfId5RO=Prof Id 5 (EUID) +ProfId6RO=- ProfId1RU=Prof Id 1 (OGRN) ProfId2RU=Prof Id 2 (INN) ProfId3RU=Prof Id 3 (KPP) @@ -406,6 +412,13 @@ AllocateCommercial=Assigned to sales representative Organization=Organization FiscalYearInformation=Fiscal Year FiscalMonthStart=Starting month of the fiscal year +SocialNetworksInformation=Social networks +SocialNetworksFacebookURL=Facebook URL +SocialNetworksTwitterURL=Twitter URL +SocialNetworksLinkedinURL=Linkedin URL +SocialNetworksInstagramURL=Instagram URL +SocialNetworksYoutubeURL=Youtube URL +SocialNetworksGithubURL=Github URL YouMustAssignUserMailFirst=You must create an email for this user prior to being able to add an email notification. YouMustCreateContactFirst=To be able to add email notifications, you must first define contacts with valid emails for the third party ListSuppliersShort=List of Vendors diff --git a/htdocs/langs/en_US/compta.lang b/htdocs/langs/en_US/compta.lang index 91de8ebf212..5865826dc73 100644 --- a/htdocs/langs/en_US/compta.lang +++ b/htdocs/langs/en_US/compta.lang @@ -254,3 +254,4 @@ ByVatRate=By sale tax rate TurnoverbyVatrate=Turnover invoiced by sale tax rate TurnoverCollectedbyVatrate=Turnover collected by sale tax rate PurchasebyVatrate=Purchase by sale tax rate +LabelToShow=Short label \ No newline at end of file diff --git a/htdocs/langs/en_US/exports.lang b/htdocs/langs/en_US/exports.lang index ef5ff029c78..2dcf4317e00 100644 --- a/htdocs/langs/en_US/exports.lang +++ b/htdocs/langs/en_US/exports.lang @@ -37,7 +37,7 @@ FormatedExportDesc3=When data to export are selected, you can choose the format Sheet=Sheet NoImportableData=No importable data (no module with definitions to allow data imports) FileSuccessfullyBuilt=File generated -SQLUsedForExport=SQL Request used to build export file +SQLUsedForExport=SQL Request used to extract data LineId=Id of line LineLabel=Label of line LineDescription=Description of line diff --git a/htdocs/langs/en_US/install.lang b/htdocs/langs/en_US/install.lang index 708b3bac479..bf9c08c4ba7 100644 --- a/htdocs/langs/en_US/install.lang +++ b/htdocs/langs/en_US/install.lang @@ -16,6 +16,7 @@ PHPSupportCurl=This PHP supports Curl. PHPSupportCalendar=This PHP supports calendars extensions. PHPSupportUTF8=This PHP supports UTF8 functions. PHPSupportIntl=This PHP supports Intl functions. +PHPSupport=This PHP supports %s functions. PHPMemoryOK=Your PHP max session memory is set to %s. This should be enough. PHPMemoryTooLow=Your PHP max session memory is set to %s bytes. This is too low. Change your php.ini to set memory_limit parameter to at least %s bytes. Recheck=Click here for a more detailed test @@ -25,6 +26,7 @@ ErrorPHPDoesNotSupportCurl=Your PHP installation does not support Curl. ErrorPHPDoesNotSupportCalendar=Your PHP installation does not support php calendar extensions. ErrorPHPDoesNotSupportUTF8=Your PHP installation does not support UTF8 functions. Dolibarr cannot work correctly. Resolve this before installing Dolibarr. ErrorPHPDoesNotSupportIntl=Your PHP installation does not support Intl functions. +ErrorPHPDoesNotSupport=Your PHP installation does not support %s functions. ErrorDirDoesNotExists=Directory %s does not exist. ErrorGoBackAndCorrectParameters=Go back and check/correct the parameters. ErrorWrongValueForParameter=You may have typed a wrong value for parameter '%s'. @@ -89,7 +91,7 @@ GoToSetupArea=Go to Dolibarr (setup area) MigrationNotFinished=The database version is not completely up to date: run the upgrade process again. GoToUpgradePage=Go to upgrade page again WithNoSlashAtTheEnd=Without the slash "/" at the end -DirectoryRecommendation=It is recommended to use a directory outside of the web pages. +DirectoryRecommendation=IMPORTANT: You must use a directory that is outside of the web pages (so do not use a subdirectory of previous parameter). LoginAlreadyExists=Already exists DolibarrAdminLogin=Dolibarr admin login AdminLoginAlreadyExists=Dolibarr administrator account '%s' already exists. Go back if you want to create another one. diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 43331220bd0..3054b813f72 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -1014,4 +1014,9 @@ ContactDefault_ticketsup=Ticket ContactAddedAutomatically=Contact added from contact thirdparty roles More=More ShowDetails=Show details -CustomReports=Custom reports \ No newline at end of file +CustomReports=Custom reports +StatisticsOn=Statistics on +SelectYourGraphOptionsFirst=Select your graph options to build a graph +Measures=Measures +XAxis=X-Axis +YAxis=Y-Axis \ No newline at end of file diff --git a/htdocs/langs/en_US/orders.lang b/htdocs/langs/en_US/orders.lang index 558076ba11d..505fd0a97db 100644 --- a/htdocs/langs/en_US/orders.lang +++ b/htdocs/langs/en_US/orders.lang @@ -141,10 +141,10 @@ OrderByEMail=Email OrderByWWW=Online OrderByPhone=Phone # Documents models -PDFEinsteinDescription=A complete order model (logo...) -PDFEratostheneDescription=A complete order model (logo...) +PDFEinsteinDescription=A complete order model (old implementation of Eratosthene template) +PDFEratostheneDescription=A complete order model PDFEdisonDescription=A simple order model -PDFProformaDescription=A complete proforma invoice (logo…) +PDFProformaDescription=A complete Proforma invoice template CreateInvoiceForThisCustomer=Bill orders NoOrdersToInvoice=No orders billable CloseProcessedOrdersAutomatically=Classify "Processed" all selected orders. diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang index 55f70e68b21..14d0e9d2b19 100644 --- a/htdocs/langs/en_US/projects.lang +++ b/htdocs/langs/en_US/projects.lang @@ -69,6 +69,7 @@ NewTask=New task AddTask=Create task AddTimeSpent=Create time spent AddHereTimeSpentForDay=Add here time spent for this day/task +AddHereTimeSpentForWeek=Add here time spent for this week/task Activity=Activity Activities=Tasks/activities MyActivities=My tasks/activities @@ -187,6 +188,7 @@ ProjectMustBeValidatedFirst=Project must be validated first FirstAddRessourceToAllocateTime=Assign a user resource to task to allocate time InputPerDay=Input per day InputPerWeek=Input per week +InputPerMonth=Input per month InputDetail=Input detail TimeAlreadyRecorded=This is time spent already recorded for this task/day and user %s ProjectsWithThisUserAsContact=Projects with this user as contact @@ -255,3 +257,7 @@ ProjectFollowTasks=Follow tasks UsageOpportunity=Usage: Opportunity UsageTasks=Usage: Tasks UsageBillTimeShort=Usage: Bill time +InvoiceToUse=Draft invoice to use +NewInvoice=New invoice +OneLinePerTask=One line per task +OneLinePerPeriod=One line per period \ No newline at end of file diff --git a/htdocs/langs/en_US/propal.lang b/htdocs/langs/en_US/propal.lang index ca88cd480d5..71d6857c909 100644 --- a/htdocs/langs/en_US/propal.lang +++ b/htdocs/langs/en_US/propal.lang @@ -76,8 +76,8 @@ TypeContact_propal_external_BILLING=Customer invoice contact TypeContact_propal_external_CUSTOMER=Customer contact following-up proposal TypeContact_propal_external_SHIPPING=Customer contact for delivery # Document models -DocModelAzurDescription=A complete proposal model (logo...) -DocModelCyanDescription=A complete proposal model (logo...) +DocModelAzurDescription=A complete proposal model (old implementation of Cyan template) +DocModelCyanDescription=A complete proposal model DefaultModelPropalCreate=Default model creation DefaultModelPropalToBill=Default template when closing a business proposal (to be invoiced) DefaultModelPropalClosed=Default template when closing a business proposal (unbilled) diff --git a/htdocs/langs/en_US/receiptprinter.lang b/htdocs/langs/en_US/receiptprinter.lang index 5714ba78151..f79974558d6 100644 --- a/htdocs/langs/en_US/receiptprinter.lang +++ b/htdocs/langs/en_US/receiptprinter.lang @@ -45,3 +45,5 @@ DOL_ACTIVATE_BUZZER=Activate buzzer DOL_PRINT_QRCODE=Print QR Code DOL_PRINT_LOGO=Print logo of my company DOL_PRINT_LOGO_OLD=Print logo of my company (old printers) +DOL_BOLD=Bold +DOL_BOLD_DISABLED=Disable bold diff --git a/htdocs/langs/en_US/ticket.lang b/htdocs/langs/en_US/ticket.lang index f29c2f4a5ba..2a6c5bb3308 100644 --- a/htdocs/langs/en_US/ticket.lang +++ b/htdocs/langs/en_US/ticket.lang @@ -30,6 +30,7 @@ Permission56005=See tickets of all third parties (not effective for external use TicketDictType=Ticket - Types TicketDictCategory=Ticket - Groupes TicketDictSeverity=Ticket - Severities +TicketDictResolution=Ticket - Resolution TicketTypeShortBUGSOFT=Dysfonctionnement logiciel TicketTypeShortBUGHARD=Dysfonctionnement matériel TicketTypeShortCOM=Commercial question diff --git a/htdocs/langs/fr_FR/projects.lang b/htdocs/langs/fr_FR/projects.lang index 388de918e05..e1de5b386a1 100644 --- a/htdocs/langs/fr_FR/projects.lang +++ b/htdocs/langs/fr_FR/projects.lang @@ -69,6 +69,7 @@ NewTask=Nouvelle tâche AddTask=Créer tâche AddTimeSpent=Saisir temps consommé AddHereTimeSpentForDay=Ajoutez ici le temps passé pour cette journée/tâche +AddHereTimeSpentForWeek=Ajoutez ici le temps passé pour cette semaine/tâche Activity=Activité Activities=Tâches/activités MyActivities=Mes tâches/activités @@ -187,6 +188,7 @@ ProjectMustBeValidatedFirst=Le projet doit être validé d'abord FirstAddRessourceToAllocateTime=Affecter un utilisateur pour saisir des temps InputPerDay=Saisie par jour InputPerWeek=Saisie par semaine +InputPerMonth=Saisie par mois InputDetail=Saisir le détail TimeAlreadyRecorded=C'est le temps passé déjà enregistré pour cette tâche/jour et pour l'utilisateur %s ProjectsWithThisUserAsContact=Projets avec cet utilisateur comme contact diff --git a/htdocs/loan/class/loan.class.php b/htdocs/loan/class/loan.class.php index f655b3adcb2..340d9dea02a 100644 --- a/htdocs/loan/class/loan.class.php +++ b/htdocs/loan/class/loan.class.php @@ -433,19 +433,19 @@ class Loan extends CommonObject global $langs; // Load translation files required by the page - $langs->loadLangs(array("customers","bills")); + $langs->loadLangs(array("customers", "bills")); - unset($this->labelStatus); // Force to reset the array of status label, because label can change depending on parameters + unset($this->labelStatus); // Force to reset the array of status label, because label can change depending on parameters if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('Unpaid'); $this->labelStatus[self::STATUS_PAID] = $langs->trans('Paid'); - if ($status == 0 && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == 0 && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('Unpaid'); $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('Enabled'); - if ($status == 0 && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == 0 && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); } $statusType = 'status1'; diff --git a/htdocs/loan/list.php b/htdocs/loan/list.php index c26c8b5706b..106bec76f16 100644 --- a/htdocs/loan/list.php +++ b/htdocs/loan/list.php @@ -28,14 +28,14 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; // Load translation files required by the page -$langs->loadLangs(array("loan","compta","banks","bills")); +$langs->loadLangs(array("loan", "compta", "banks", "bills")); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'loan', '', '', ''); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); @@ -144,18 +144,18 @@ if ($resql) { $i = 0; - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($search_ref) $param.="&search_ref=".urlencode($search_ref); - if ($search_label) $param.="&search_label=".urlencode($search_label); - if ($search_amount) $param.="&search_amount=".urlencode($search_amount); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); + if ($search_label) $param .= "&search_label=".urlencode($search_label); + if ($search_amount) $param .= "&search_amount=".urlencode($search_amount); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->loan->write) { - $newcardbutton.= dolGetButtonTitle($langs->trans('NewLoan'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/loan/card.php?action=create'); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewLoan'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/loan/card.php?action=create'); } print ''."\n"; @@ -185,7 +185,7 @@ if ($resql) print '
 '; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
"; + print '
'; + print '
'."\n"; print ''; if ($agentid > 0) @@ -299,7 +305,8 @@ if ($result) print "\n"; } } - print "
"; + print ""; + print '
'; } else { diff --git a/htdocs/margin/customerMargins.php b/htdocs/margin/customerMargins.php index 35dde9a2e62..ed0a2a01b34 100644 --- a/htdocs/margin/customerMargins.php +++ b/htdocs/margin/customerMargins.php @@ -62,6 +62,9 @@ if (!empty($_POST['startdatemonth'])) if (!empty($_POST['enddatemonth'])) $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new Societe($db); +$hookmanager->initHooks(array('margincustomerlist')); /* * View @@ -255,8 +258,11 @@ if ($result) else // value is 'costprice' or 'pmp' $labelcostprice = 'CostPrice'; + $moreforfilter = ''; + $i = 0; - print ""; + print '
'; + print '
'."\n"; print ''; if (!empty($client)) { @@ -359,7 +365,8 @@ if ($result) print "\n"; print "\n"; - print "
".(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%")."
"; + print ""; + print '
'; } else { diff --git a/htdocs/margin/productMargins.php b/htdocs/margin/productMargins.php index 4b9c271cc5c..27354556910 100644 --- a/htdocs/margin/productMargins.php +++ b/htdocs/margin/productMargins.php @@ -76,6 +76,9 @@ if (!empty($_POST['startdatemonth'])) if (!empty($_POST['enddatemonth'])) $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new Product($db); +$hookmanager->initHooks(array('marginproductlist')); /* * View diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 0afcd403406..531d8d224d9 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -200,18 +200,18 @@ if ($dirins && $action == 'initmodule' && $modulename) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); - if($conf->global->MAIN_FEATURES_LEVEL >= 2){ - if(!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME)) $arrayreplacement['Editor name'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME; - if(!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL)) $arrayreplacement['https://www.example.com'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL; - if(!empty($conf->global->MODULEBUILDER_SPECIFIC_AUTHOR)) $arrayreplacement['---Put here your own copyright and developer email---'] = dol_print_date($now, '%Y').' '.$conf->global->MODULEBUILDER_SPECIFIC_AUTHOR; - if(!empty($conf->global->MODULEBUILDER_SPECIFIC_VERSION)) $arrayreplacement['1.0'] = $conf->global->MODULEBUILDER_SPECIFIC_VERSION; - if(!empty($conf->global->MODULEBUILDER_SPECIFIC_FAMILY)) $arrayreplacement['other'] = $conf->global->MODULEBUILDER_SPECIFIC_FAMILY; + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME)) $arrayreplacement['Editor name'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_NAME; + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL)) $arrayreplacement['https://www.example.com'] = $conf->global->MODULEBUILDER_SPECIFIC_EDITOR_URL; + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_AUTHOR)) $arrayreplacement['---Put here your own copyright and developer email---'] = dol_print_date($now, '%Y').' '.$conf->global->MODULEBUILDER_SPECIFIC_AUTHOR; + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_VERSION)) $arrayreplacement['1.0'] = $conf->global->MODULEBUILDER_SPECIFIC_VERSION; + if (!empty($conf->global->MODULEBUILDER_SPECIFIC_FAMILY)) $arrayreplacement['other'] = $conf->global->MODULEBUILDER_SPECIFIC_FAMILY; } - $result=dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); + $result = dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); //var_dump($result); if ($result < 0) @@ -238,7 +238,7 @@ if ($dirins && $action == 'initmodule' && $modulename) if ($dirins && $action == 'initapi' && !empty($module)) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase $objectname = $tabobj; dol_mkdir($dirins.'/'.strtolower($module).'/class'); @@ -251,7 +251,7 @@ if ($dirins && $action == 'initapi' && !empty($module)) if ($result > 0) { //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -263,7 +263,7 @@ if ($dirins && $action == 'initapi' && !empty($module)) 'myobject'=>strtolower($objectname), 'MyObject'=>$objectname, 'MYOBJECT'=>strtoupper($objectname), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -276,7 +276,7 @@ if ($dirins && $action == 'initapi' && !empty($module)) } if ($dirins && $action == 'initphpunit' && !empty($module)) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase $objectname = $tabobj; dol_mkdir($dirins.'/'.strtolower($module).'/class'); @@ -288,7 +288,7 @@ if ($dirins && $action == 'initphpunit' && !empty($module)) if ($result > 0) { //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -300,7 +300,7 @@ if ($dirins && $action == 'initphpunit' && !empty($module)) 'myobject'=>strtolower($objectname), 'MyObject'=>$objectname, 'MYOBJECT'=>strtoupper($objectname), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -313,7 +313,7 @@ if ($dirins && $action == 'initphpunit' && !empty($module)) } if ($dirins && $action == 'initsqlextrafields' && !empty($module)) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase $objectname = $tabobj; dol_mkdir($dirins.'/'.strtolower($module).'/sql'); @@ -329,10 +329,10 @@ if ($dirins && $action == 'initsqlextrafields' && !empty($module)) if ($result1 > 0 && $result2 > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -345,7 +345,7 @@ if ($dirins && $action == 'initsqlextrafields' && !empty($module)) 'MyObject'=>$objectname, 'my object'=>strtolower($objectname), 'myobject'=>strtolower($objectname), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile1, $arrayreplacement); @@ -449,7 +449,7 @@ if ($dirins && $action == 'initwidget' && !empty($module)) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -471,10 +471,10 @@ if ($dirins && $action == 'initcss' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -483,7 +483,7 @@ if ($dirins && $action == 'initcss' && !empty($module)) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':''), + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : ''), ); dolReplaceInFile($destfile, $arrayreplacement); @@ -510,10 +510,10 @@ if ($dirins && $action == 'initjs' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -522,7 +522,7 @@ if ($dirins && $action == 'initjs' && !empty($module)) 'Mon module'=>$modulename, 'mon module'=>$modulename, 'htdocs/modulebuilder/template'=>strtolower($modulename), - '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'') + '---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : '') ); dolReplaceInFile($destfile, $arrayreplacement); @@ -549,10 +549,10 @@ if ($dirins && $action == 'initcli' && !empty($module)) if ($result > 0) { - $modulename = ucfirst($module); // Force first letter in uppercase + $modulename = ucfirst($module); // Force first letter in uppercase //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($modulename), 'MyModule'=>$modulename, 'MYMODULE'=>strtoupper($modulename), @@ -659,6 +659,7 @@ if ($dirins && $action == 'confirm_removefile' && !empty($module)) } } +// Build the $fields array from SQL table (initfromtablename) if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', 'alpha')) { $tablename = GETPOST('initfromtablename', 'alpha'); @@ -710,15 +711,15 @@ if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', );*/ $string = 'public $fields=array('."\n"; - $string.="
"; - $i=10; + $string .= "
"; + $i = 10; while ($obj = $db->fetch_object($_results)) { // fieldname $fieldname = $obj->Field; // type $type = $obj->Type; - if ($type == 'int(11)') $type='integer'; + if ($type == 'int(11)') $type = 'integer'; if ($obj->Field == 'fk_soc') $type = 'integer:Societe:societe/class/societe.class.php'; if (preg_match('/^fk_proj/', $obj->Field)) $type = 'integer:Project:projet/class/project.class.php:1:fk_statut=1'; if (preg_match('/^fk_prod/', $obj->Field)) $type = 'integer:Product:product/class/product.class.php:1'; @@ -726,22 +727,22 @@ if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', if (preg_match('/^(fk_user|fk_commercial)/', $obj->Field)) $type = 'integer:User:user/class/user.class.php'; // notnull - $notnull = ($obj->Null == 'YES'?0:1); + $notnull = ($obj->Null == 'YES' ? 0 : 1); if ($fieldname == 'fk_user_modif') $notnull = -1; // label $label = preg_replace('/_/', ' ', ucfirst($fieldname)); - if ($fieldname == 'rowid') $label='TechnicalID'; - if ($fieldname == 'import_key') $label='ImportId'; - if ($fieldname == 'fk_soc') $label='ThirdParty'; - if ($fieldname == 'tms') $label='DateModification'; - if ($fieldname == 'datec') $label='DateCreation'; - if ($fieldname == 'date_valid') $label='DateValidation'; - if ($fieldname == 'datev') $label='DateValidation'; - if ($fieldname == 'note_private') $label='NotePublic'; - if ($fieldname == 'note_public') $label='NotePrivate'; - if ($fieldname == 'fk_user_creat') $label='UserAuthor'; - if ($fieldname == 'fk_user_modif') $label='UserModif'; - if ($fieldname == 'fk_user_valid') $label='UserValidation'; + if ($fieldname == 'rowid') $label = 'TechnicalID'; + if ($fieldname == 'import_key') $label = 'ImportId'; + if ($fieldname == 'fk_soc') $label = 'ThirdParty'; + if ($fieldname == 'tms') $label = 'DateModification'; + if ($fieldname == 'datec') $label = 'DateCreation'; + if ($fieldname == 'date_valid') $label = 'DateValidation'; + if ($fieldname == 'datev') $label = 'DateValidation'; + if ($fieldname == 'note_private') $label = 'NotePublic'; + if ($fieldname == 'note_public') $label = 'NotePrivate'; + if ($fieldname == 'fk_user_creat') $label = 'UserAuthor'; + if ($fieldname == 'fk_user_modif') $label = 'UserModif'; + if ($fieldname == 'fk_user_valid') $label = 'UserValidation'; // visible $visible = -1; if ($fieldname == 'entity') $visible = -2; @@ -753,28 +754,29 @@ if ($dirins && $action == 'initobject' && $module && GETPOST('createtablearray', $enabled = 1; // default $default = ''; - if ($fieldname == 'entity') $default=1; + if ($fieldname == 'entity') $default = 1; // position $position = $i; if (in_array($fieldname, array('status', 'statut', 'fk_status', 'fk_statut'))) $position = 500; + if ($fieldname == 'import_key') $position = 900; // index $index = 0; - if ($fieldname == 'entity') $index=1; + if ($fieldname == 'entity') $index = 1; - $string.= "'".$obj->Field."' =>array('type'=>'".$type."', 'label'=>'".$label."',"; - if ($default != '') $string.= " 'default'=>".$default.","; - $string.= " 'enabled'=>".$enabled.","; - $string.= " 'visible'=>".$visible; - if ($notnull) $string.= ", 'notnull'=>".$notnull; - if ($fieldname == 'ref') $string.= ", 'showoncombobox'=>1"; - $string.= ", 'position'=>".$position; - if ($index) $string.= ", 'index'=>".$index; - $string.= "),\n"; - $string.="
"; - $i+=5; + $string .= "'".$obj->Field."' =>array('type'=>'".$type."', 'label'=>'".$label."',"; + if ($default != '') $string .= " 'default'=>".$default.","; + $string .= " 'enabled'=>".$enabled.","; + $string .= " 'visible'=>".$visible; + if ($notnull) $string .= ", 'notnull'=>".$notnull; + if ($fieldname == 'ref') $string .= ", 'showoncombobox'=>1"; + $string .= ", 'position'=>".$position; + if ($index) $string .= ", 'index'=>".$index; + $string .= "),\n"; + $string .= "
"; + $i += 5; } - $string.= ');'."\n"; - $string.="
"; + $string .= ');'."\n"; + $string .= "
"; print $string; exit; } @@ -894,14 +896,14 @@ if ($dirins && $action == 'initobject' && $module && $objectname) // Scan for object class files $listofobject = dol_dir_list($destdir.'/class', 'files', 0, '\.class\.php$'); - $firstobjectname=''; - foreach($listofobject as $fileobj) + $firstobjectname = ''; + foreach ($listofobject as $fileobj) { if (preg_match('/^api_/', $fileobj['name'])) continue; if (preg_match('/^actions_/', $fileobj['name'])) continue; - $tmpcontent=file_get_contents($fileobj['fullname']); - $reg=array(); + $tmpcontent = file_get_contents($fileobj['fullname']); + $reg = array(); if (preg_match('/class\s+([^\s]*)\s+extends\s+CommonObject/ims', $tmpcontent, $reg)) { $objectnameloop = $reg[1]; @@ -954,7 +956,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname) $stringtoadd = preg_replace('/mymodule/', strtolower($module), $stringtoadd); $stringtoadd = preg_replace('/myobject/', strtolower($objectnameloop), $stringtoadd); - $moduledescriptorfile=$destdir.'/core/modules/mod'.$module.'.class.php'; + $moduledescriptorfile = $destdir.'/core/modules/mod'.$module.'.class.php'; // TODO Allow a replace with regex using dolReplaceInFile with param arryreplacementisregex to 1 // TODO Avoid duplicate addition @@ -962,19 +964,19 @@ if ($dirins && $action == 'initobject' && $module && $objectname) dolReplaceInFile($moduledescriptorfile, array('END MODULEBUILDER LEFTMENU MYOBJECT */' => '*/'."\n".$stringtoadd."\n\t\t/* END MODULEBUILDER LEFTMENU MYOBJECT */")); // Add module descriptor to list of files to replace "MyObject' string with real name of object. - $filetogenerate[]='core/modules/mod'.$module.'.class.php'; + $filetogenerate[] = 'core/modules/mod'.$module.'.class.php'; } } - if (! $error) + if (!$error) { // Edit PHP files to make replacement - foreach($filetogenerate as $destfile) + foreach ($filetogenerate as $destfile) { $phpfileval['fullname'] = $destdir.'/'.$destfile; //var_dump($phpfileval['fullname']); - $arrayreplacement=array( + $arrayreplacement = array( 'mymodule'=>strtolower($module), 'MyModule'=>$module, 'MYMODULE'=>strtoupper($module), @@ -997,38 +999,38 @@ if ($dirins && $action == 'initobject' && $module && $objectname) } } - if (! $error) + if (!$error) { // Edit the class file to write properties - $object=rebuildObjectClass($destdir, $module, $objectname, $newmask); + $object = rebuildObjectClass($destdir, $module, $objectname, $newmask); if (is_numeric($object) && $object < 0) $error++; } - if (! $error) + if (!$error) { // Edit sql with new properties - $result=rebuildObjectSql($destdir, $module, $objectname, $newmask, '', $object); + $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, '', $object); if ($result < 0) $error++; } - if (! $error) + if (!$error) { setEventMessages($langs->trans('FilesForObjectInitialized', $objectname), null); $tabobj = $objectname; } } -if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && !empty($module) && ! empty($tabobj)) +if ($dirins && ($action == 'droptable' || $action == 'droptableextrafields') && !empty($module) && !empty($tabobj)) { $objectname = $tabobj; - $arrayoftables=array(); + $arrayoftables = array(); if ($action == 'droptable') $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj); if ($action == 'droptableextrafields') $arrayoftables[] = MAIN_DB_PREFIX.strtolower($module).'_'.strtolower($tabobj).'_extrafields'; - foreach($arrayoftables as $tabletodrop) + foreach ($arrayoftables as $tabletodrop) { $nb = -1; - $sql="SELECT COUNT(*) as nb FROM ".$tabletodrop; + $sql = "SELECT COUNT(*) as nb FROM ".$tabletodrop; $resql = $db->query($sql); if ($resql) { @@ -1073,35 +1075,35 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) dol_mkdir($destdir); // We click on add property - if (! GETPOST('regenerateclasssql') && ! GETPOST('regeneratemissing')) + if (!GETPOST('regenerateclasssql') && !GETPOST('regeneratemissing')) { - if (! GETPOST('propname', 'aZ09')) + if (!GETPOST('propname', 'aZ09')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name")), null, 'errors'); } - if (! GETPOST('proplabel', 'alpha')) + if (!GETPOST('proplabel', 'alpha')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); } - if (! GETPOST('proptype', 'alpha')) + if (!GETPOST('proptype', 'alpha')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Type")), null, 'errors'); } - if (! $error) + if (!$error) { $addfieldentry = array( - 'name'=>GETPOST('propname', 'aZ09'),'label'=>GETPOST('proplabel', 'alpha'),'type'=>GETPOST('proptype', 'alpha'), - 'arrayofkeyval'=>GETPOST('proparrayofkeyval', 'none'), // Example json string '{"0":"Draft","1":"Active","-1":"Cancel"}' - 'visible'=>GETPOST('propvisible', 'int'),'enabled'=>GETPOST('propenabled', 'int'), - 'position'=>GETPOST('propposition', 'int'),'notnull'=>GETPOST('propnotnull', 'int'),'index'=>GETPOST('propindex', 'int'),'searchall'=>GETPOST('propsearchall', 'int'), - 'isameasure'=>GETPOST('propisameasure', 'int'), 'comment'=>GETPOST('propcomment', 'alpha'),'help'=>GETPOST('prophelp', 'alpha') + 'name'=>GETPOST('propname', 'aZ09'), 'label'=>GETPOST('proplabel', 'alpha'), 'type'=>GETPOST('proptype', 'alpha'), + 'arrayofkeyval'=>GETPOST('proparrayofkeyval', 'none'), // Example json string '{"0":"Draft","1":"Active","-1":"Cancel"}' + 'visible'=>GETPOST('propvisible', 'int'), 'enabled'=>GETPOST('propenabled', 'int'), + 'position'=>GETPOST('propposition', 'int'), 'notnull'=>GETPOST('propnotnull', 'int'), 'index'=>GETPOST('propindex', 'int'), 'searchall'=>GETPOST('propsearchall', 'int'), + 'isameasure'=>GETPOST('propisameasure', 'int'), 'comment'=>GETPOST('propcomment', 'alpha'), 'help'=>GETPOST('prophelp', 'alpha') ); - if (! empty($addfieldentry['arrayofkeyval']) && ! is_array($addfieldentry['arrayofkeyval'])) + if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) { $addfieldentry['arrayofkeyval'] = dol_json_decode($addfieldentry['arrayofkeyval'], true); } @@ -1115,9 +1117,9 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) }*/ // Edit the class file to write properties - if (! $error) + if (!$error) { - $object=rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, $addfieldentry); + $object = rebuildObjectClass($destdir, $module, $objectname, $newmask, $srcdir, $addfieldentry); if (is_numeric($object) && $object <= 0) { $error++; @@ -1125,23 +1127,23 @@ if ($dirins && $action == 'addproperty' && !empty($module) && !empty($tabobj)) } // Edit sql with new properties - if (! $error) + if (!$error) { - $result=rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object); + $result = rebuildObjectSql($destdir, $module, $objectname, $newmask, $srcdir, $object); if ($result <= 0) { $error++; } } - if (! $error) + if (!$error) { setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null); clearstatcache(true); // Make a redirect to reload all data - header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.($forceddirread?'@'.$dirread:'').'&tabobj='.$objectname.'&nocache='.time()); + header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj='.$objectname.'&nocache='.time()); exit; } @@ -1176,7 +1178,7 @@ if ($dirins && $action == 'confirm_deleteproperty' && $propertykey) clearstatcache(true); // Make a redirect to reload all data - header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.($forceddirread?'@'.$dirread:'').'&tabobj='.$objectname); + header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj='.$objectname); exit; } @@ -1253,10 +1255,10 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) ); $resultko = 0; - foreach($filetodelete as $filetodelete) + foreach ($filetodelete as $filetodelete) { $resulttmp = dol_delete_file($dir.'/'.$filetodelete, 0, 0, 1); - if (! $resulttmp) $resultko++; + if (!$resulttmp) $resultko++; } if ($resultko == 0) @@ -1410,24 +1412,24 @@ if ($action == 'savefile' && empty($cancel)) // Enable module if ($action == 'set' && $user->admin) { - $param=''; - if ($module) $param.='&module='.urlencode($module); - if ($tab) $param.='&tab='.urlencode($tab); - if ($tabobj) $param.='&tabobj='.urlencode($tabobj); + $param = ''; + if ($module) $param .= '&module='.urlencode($module); + if ($tab) $param .= '&tab='.urlencode($tab); + if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); $value = GETPOST('value', 'alpha'); $resarray = activateModule($value); - if (! empty($resarray['errors'])) setEventMessages('', $resarray['errors'], 'errors'); + if (!empty($resarray['errors'])) setEventMessages('', $resarray['errors'], 'errors'); else { //var_dump($resarray);exit; if ($resarray['nbperms'] > 0) { - $tmpsql="SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE admin <> 1"; - $resqltmp=$db->query($tmpsql); + $tmpsql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE admin <> 1"; + $resqltmp = $db->query($tmpsql); if ($resqltmp) { - $obj=$db->fetch_object($resqltmp); + $obj = $db->fetch_object($resqltmp); //var_dump($obj->nb);exit; if ($obj && $obj->nb > 1) { @@ -1445,13 +1447,13 @@ if ($action == 'set' && $user->admin) // Disable module if ($action == 'reset' && $user->admin) { - $param=''; - if ($module) $param.='&module='.urlencode($module); - if ($tab) $param.='&tab='.urlencode($tab); - if ($tabobj) $param.='&tabobj='.urlencode($tabobj); + $param = ''; + if ($module) $param .= '&module='.urlencode($module); + if ($tab) $param .= '&tab='.urlencode($tab); + if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); $value = GETPOST('value', 'alpha'); - $result=unActivateModule($value); + $result = unActivateModule($value); if ($result) setEventMessages($result, null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"]."?".$param); exit; @@ -1482,27 +1484,27 @@ llxHeader('', $langs->trans("ModuleBuilder"), '', '', 0, 0, ), array()); -$text=$langs->trans("ModuleBuilder"); +$text = $langs->trans("ModuleBuilder"); print load_fiche_titre($text, '', 'title_setup'); print ''.$langs->trans("ModuleBuilderDesc", 'https://wiki.dolibarr.org/index.php/Module_development#Create_your_module').'
'; -$dirsrootforscan=array($dirread); +$dirsrootforscan = array($dirread); // Add also the core modules into the list of modules to show/edit -if ($dirread != DOL_DOCUMENT_ROOT && ($conf->global->MAIN_FEATURES_LEVEL >=2 || ! empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT))) { $dirsrootforscan[]=DOL_DOCUMENT_ROOT; } +if ($dirread != DOL_DOCUMENT_ROOT && ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->MODULEBUILDER_ADD_DOCUMENT_ROOT))) { $dirsrootforscan[] = DOL_DOCUMENT_ROOT; } // Search modules to edit print ''."\n"; -$listofmodules=array(); -$i=0; -foreach($dirsrootforscan as $dirread) +$listofmodules = array(); +$i = 0; +foreach ($dirsrootforscan as $dirread) { - $dirsincustom=dol_dir_list($dirread, 'directories'); + $dirsincustom = dol_dir_list($dirread, 'directories'); if (is_array($dirsincustom) && count($dirsincustom) > 0) { foreach ($dirsincustom as $dircustomcursor) { $fullname = $dircustomcursor['fullname']; - if (dol_is_file($fullname . '/' . $FILEFLAG)) + if (dol_is_file($fullname.'/'.$FILEFLAG)) { // Get real name of module (MyModule instead of mymodule) $dirtoscanrel = basename($fullname).'/core/modules/'; @@ -1549,8 +1551,8 @@ foreach($dirsrootforscan as $dirread) } // Show description of content - $newdircustom=$dirins; - if (empty($newdircustom)) $newdircustom=img_warning(); + $newdircustom = $dirins; + if (empty($newdircustom)) $newdircustom = img_warning(); // If dirread was forced to somewhere else, by using URL // htdocs/modulebuilder/index.php?module=Inventory@/home/ldestailleur/git/dolibarr/htdocs/product if (empty($i)) print $langs->trans("DirScanned").' : '; @@ -1561,27 +1563,27 @@ foreach($dirsrootforscan as $dirread) print '
'; //var_dump($listofmodules); -$message=''; -if (! $dirins) +$message = ''; +if (!$dirins) { - $message=info_admin($langs->trans("ConfFileMustContainCustom", DOL_DOCUMENT_ROOT.'/custom', DOL_DOCUMENT_ROOT)); - $allowfromweb=-1; + $message = info_admin($langs->trans("ConfFileMustContainCustom", DOL_DOCUMENT_ROOT.'/custom', DOL_DOCUMENT_ROOT)); + $allowfromweb = -1; } else { if ($dirins_ok) { - if (! is_writable(dol_osencode($dirins))) + if (!is_writable(dol_osencode($dirins))) { $langs->load("errors"); - $message=info_admin($langs->trans("ErrorFailedToWriteInDir", $dirins)); - $allowfromweb=0; + $message = info_admin($langs->trans("ErrorFailedToWriteInDir", $dirins)); + $allowfromweb = 0; } } else { - $message=info_admin($langs->trans("NotExistsDirect", $dirins).$langs->trans("InfDirAlt").$langs->trans("InfDirExample")); - $allowfromweb=0; + $message = info_admin($langs->trans("NotExistsDirect", $dirins).$langs->trans("InfDirAlt").$langs->trans("InfDirExample")); + $allowfromweb = 0; } } if ($message) @@ -1667,7 +1669,7 @@ if ($module == 'initmodule') print '
'; - print '
'; + print '
'; print ''; } elseif ($module == 'deletemodule') @@ -1681,121 +1683,121 @@ elseif ($module == 'deletemodule') print $langs->trans("EnterNameOfModuleToDeleteDesc").'

'; print ''; - print ''; + print ''; print ''; } -elseif (! empty($module)) +elseif (!empty($module)) { // Tabs for module - if (! $error) + if (!$error) { $dirread = $listofmodules[strtolower($module)]['moduledescriptorrootpath']; $head2 = array(); - $h=0; + $h = 0; - $modulelowercase=strtolower($module); + $modulelowercase = strtolower($module); $const_name = 'MAIN_MODULE_'.strtoupper($module); - $param=''; - if ($tab) $param.='&tab='.urlencode($tab); - if ($module) $param.='&module='.urlencode($module); - if ($tabobj) $param.='&tabobj='.urlencode($tabobj); + $param = ''; + if ($tab) $param .= '&tab='.urlencode($tab); + if ($module) $param .= '&module='.urlencode($module); + if ($tabobj) $param .= '&tabobj='.urlencode($tabobj); - $urltomodulesetup=''.$langs->trans('Home').'-'.$langs->trans("Setup").'-'.$langs->trans("Modules").''; - $linktoenabledisable=''; - if (! empty($conf->global->$const_name)) // If module is already activated + $urltomodulesetup = ''.$langs->trans('Home').'-'.$langs->trans("Setup").'-'.$langs->trans("Modules").''; + $linktoenabledisable = ''; + if (!empty($conf->global->$const_name)) // If module is already activated { - $linktoenabledisable.=''; - $linktoenabledisable.=img_picto($langs->trans("Activated"), 'switch_on', '', false, 0, 0, '', '', 1); - $linktoenabledisable.=''; + $linktoenabledisable .= ''; + $linktoenabledisable .= img_picto($langs->trans("Activated"), 'switch_on', '', false, 0, 0, '', '', 1); + $linktoenabledisable .= ''; } else { - $linktoenabledisable.=''; - $linktoenabledisable.=img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', 1); - $linktoenabledisable.="\n"; + $linktoenabledisable .= ''; + $linktoenabledisable .= img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', 1); + $linktoenabledisable .= "\n"; } if (empty($conf->$modulelowercase->enabled)) { - $modulestatusinfo=$form->textwithpicto($langs->trans("ModuleIsNotActive", $urltomodulesetup), '', -1, 'help'); + $modulestatusinfo = $form->textwithpicto($langs->trans("ModuleIsNotActive", $urltomodulesetup), '', -1, 'help'); } else { - $modulestatusinfo=$form->textwithpicto($langs->trans("ModuleIsLive"), $langs->trans("Warning"), -1, 'warning'); + $modulestatusinfo = $form->textwithpicto($langs->trans("ModuleIsLive"), $langs->trans("Warning"), -1, 'warning'); } - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=description&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=description&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Description"); $head2[$h][2] = 'description'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=languages&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=languages&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Languages"); $head2[$h][2] = 'languages'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=dictionaries&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=dictionaries&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Dictionaries"); $head2[$h][2] = 'dictionaries'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Objects"); $head2[$h][2] = 'objects'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=menus&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=menus&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Menus"); $head2[$h][2] = 'menus'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=permissions&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=permissions&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Permissions"); $head2[$h][2] = 'permissions'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=hooks&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=hooks&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Hooks"); $head2[$h][2] = 'hooks'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=triggers&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=triggers&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Triggers"); $head2[$h][2] = 'triggers'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=widgets&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=widgets&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Widgets"); $head2[$h][2] = 'widgets'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=css&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=css&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("CSS"); $head2[$h][2] = 'css'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=js&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=js&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("JS"); $head2[$h][2] = 'js'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=cli&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=cli&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("CLI"); $head2[$h][2] = 'cli'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=cron&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=cron&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("CronList"); $head2[$h][2] = 'cron'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=specifications&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=specifications&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("Documentation"); $head2[$h][2] = 'specifications'; $h++; - $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=buildpackage&module='.$module.($forceddirread?'@'.$dirread:''); + $head2[$h][0] = $_SERVER["PHP_SELF"].'?tab=buildpackage&module='.$module.($forceddirread ? '@'.$dirread : ''); $head2[$h][1] = $langs->trans("BuildPackage"); $head2[$h][2] = 'buildpackage'; $h++; @@ -1829,15 +1831,15 @@ elseif (! empty($module)) print ''; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; print ''; print ' '.$langs->trans("ReadmeFile").' : '.$pathtofilereadme.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; print ''; print ' '.$langs->trans("ChangeLog").' : '.$pathtochangelog.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; print ''; print ''; @@ -1909,7 +1911,7 @@ elseif (! empty($module)) print $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module).'
'; } - if (! empty($moduleobj)) + if (!empty($moduleobj)) { print '

'; @@ -1998,8 +2000,8 @@ elseif (! empty($module)) { $pathtofile = $modulelowercase.'/langs/'.$langfile['relativename']; print ' '.$langs->trans("LanguageFile").' '.basename(dirname($pathtofile)).' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print ''; } print ''; @@ -2044,16 +2046,16 @@ elseif (! empty($module)) if ($action != 'editfile' || empty($file)) { print ''; - $htmlhelp=$langs->trans("DictionariesDefDescTooltip", ''.$langs->trans('Setup').' - '.$langs->trans('Dictionaries').''); + $htmlhelp = $langs->trans("DictionariesDefDescTooltip", ''.$langs->trans('Setup').' - '.$langs->trans('Dictionaries').''); print $form->textwithpicto($langs->trans("DictionariesDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'
'; print '
'; print '
'; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; print ' '.$langs->trans("LanguageFile").' :
'; - if (! is_array($dicts) || empty($dicts)) print ''.$langs->trans("NoDictionaries").''; + if (!is_array($dicts) || empty($dicts)) print ''.$langs->trans("NoDictionaries").''; else print ''.$dicts['langs'].''; print '
'; @@ -2146,7 +2148,7 @@ elseif (! empty($module)) } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -2158,8 +2160,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
'; print '
'; print ''; @@ -2174,12 +2176,12 @@ elseif (! empty($module)) if ($tab == 'objects') { $head3 = array(); - $h=0; + $h = 0; // Dir for module $dir = $dirread.'/'.$modulelowercase.'/class'; - $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread?'@'.$dirread:'').'&tabobj=newobject'; + $head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.($forceddirread ? '@'.$dirread : '').'&tabobj=newobject'; $head3[$h][1] = ''.$langs->trans("NewObjectInModulebuilder").''; $head3[$h][2] = 'newobject'; $h++; @@ -2232,10 +2234,10 @@ elseif (! empty($module)) print ''.$langs->trans("EnterNameOfObjectDesc").'

'; - print '
'; + print '
'; print ' '.$form->textwithpicto($langs->trans("IncludeRefGeneration"), $langs->trans("IncludeRefGenerationHelp")).'
'; print ' '.$form->textwithpicto($langs->trans("IncludeDocGeneration"), $langs->trans("IncludeDocGenerationHelp")).'
'; - print ''; + print ''; print '
'; print '
'; print '
'; @@ -2325,15 +2327,15 @@ elseif (! empty($module)) } print '
'; - print ' '.$langs->trans("ClassFile").' : '.($realpathtoclass?'':'').$pathtoclass.($realpathtoclass?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("ClassFile").' : '.($realpathtoclass ? '' : '').$pathtoclass.($realpathtoclass ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; - print ' '.$langs->trans("ApiClassFile").' : '.($realpathtoapi?'':'').$pathtoapi.($realpathtoapi?'':'').''; + print ' '.$langs->trans("ApiClassFile").' : '.($realpathtoapi ? '' : '').$pathtoapi.($realpathtoapi ? '' : '').''; if ($realpathtoapi) { - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print '   '; if (empty($conf->global->$const_name)) // If module is not activated { @@ -2347,67 +2349,67 @@ elseif (! empty($module)) else { //print ''.$langs->trans("FileNotYetGenerated").' '; - print ''; + print ''; } // PHPUnit print '
'; - print ' '.$langs->trans("TestClassFile").' : '.($realpathtophpunit?'':'').$pathtophpunit.($realpathtophpunit?'':'').''; + print ' '.$langs->trans("TestClassFile").' : '.($realpathtophpunit ? '' : '').$pathtophpunit.($realpathtophpunit ? '' : '').''; if ($realpathtophpunit) { - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } else { //print ''.$langs->trans("FileNotYetGenerated").' '; - print ''; + print ''; } print '
'; print '
'; - print ' '.$langs->trans("PageForLib").' : '.($realpathtolib?'':'').$pathtolib.($realpathtolib?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForLib").' : '.($realpathtolib ? '' : '').$pathtolib.($realpathtolib ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; - print ' '.$langs->trans("PageForObjLib").' : '.($realpathtoobjlib?'':'').$pathtoobjlib.($realpathtoobjlib?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForObjLib").' : '.($realpathtoobjlib ? '' : '').$pathtoobjlib.($realpathtoobjlib ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; - print ' '.$langs->trans("Image").' : '.($realpathtopicto?'':'').$pathtopicto.($realpathtopicto?'':'').''; + print ' '.$langs->trans("Image").' : '.($realpathtopicto ? '' : '').$pathtopicto.($realpathtopicto ? '' : '').''; //print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; print '
'; - print ' '.$langs->trans("SqlFile").' : '.($realpathtosql?'':'').$pathtosql.($realpathtosql?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; - print '   '.$langs->trans("DropTableIfEmpty").''; + print ' '.$langs->trans("SqlFile").' : '.($realpathtosql ? '' : '').$pathtosql.($realpathtosql ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print '   '.$langs->trans("DropTableIfEmpty").''; //print '   '.$langs->trans("RunSql").''; print '
'; - print ' '.$langs->trans("SqlFileKey").' : '.($realpathtosqlkey?'':'').$pathtosqlkey.($realpathtosqlkey?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("SqlFileKey").' : '.($realpathtosqlkey ? '' : '').$pathtosqlkey.($realpathtosqlkey ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; //print '   '.$langs->trans("RunSql").''; print '
'; - print ' '.$langs->trans("SqlFileExtraFields").' : '.($realpathtosqlextra?'':'').$pathtosqlextra.($realpathtosqlextra?'':'').''; + print ' '.$langs->trans("SqlFileExtraFields").' : '.($realpathtosqlextra ? '' : '').$pathtosqlextra.($realpathtosqlextra ? '' : '').''; if ($realpathtosqlextra) { - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print '   '; - print ''.$langs->trans("DropTableIfEmpty").''; + print ''.$langs->trans("DropTableIfEmpty").''; } else { - print ''; + print ''; } //print '   '.$langs->trans("RunSql").''; print '
'; - print ' '.$langs->trans("SqlFileKeyExtraFields").' : '.($realpathtosqlextrakey?'':'').$pathtosqlextrakey.($realpathtosqlextrakey?'':'').''; + print ' '.$langs->trans("SqlFileKeyExtraFields").' : '.($realpathtosqlextrakey ? '' : '').$pathtosqlextrakey.($realpathtosqlextrakey ? '' : '').''; if ($realpathtosqlextrakey) { - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } //print '   '.$langs->trans("RunSql").''; print '
'; @@ -2419,34 +2421,34 @@ elseif (! empty($module)) $urlofcard = dol_buildpath($pathtocard, 1); print '
'; - print ' '.$langs->trans("PageForList").' : '.($realpathtolist?'':'').$pathtolist.($realpathtolist?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForList").' : '.($realpathtolist ? '' : '').$pathtolist.($realpathtolist ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; - print ' '.$langs->trans("PageForCreateEditView").' : '.($realpathtocard?'':'').$pathtocard.($realpathtocard?'':'').'?action=create'; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForCreateEditView").' : '.($realpathtocard ? '' : '').$pathtocard.($realpathtocard ? '' : '').'?action=create'; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; - print ' '.$langs->trans("PageForAgendaTab").' : '.($realpathtoagenda?'':'').$pathtoagenda.($realpathtoagenda?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForAgendaTab").' : '.($realpathtoagenda ? '' : '').$pathtoagenda.($realpathtoagenda ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; if ($realpathtoagenda) { print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } print '
'; - print ' '.$langs->trans("PageForDocumentTab").' : '.($realpathtodocument?'':'').$pathtodocument.($realpathtodocument?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForDocumentTab").' : '.($realpathtodocument ? '' : '').$pathtodocument.($realpathtodocument ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; if ($realpathtodocument) { print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } print '
'; - print ' '.$langs->trans("PageForNoteTab").' : '.($realpathtonote?'':'').$pathtonote.($realpathtonote?'':'').''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.$langs->trans("PageForNoteTab").' : '.($realpathtonote ? '' : '').$pathtonote.($realpathtonote ? '' : '').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; if ($realpathtonote) { print ' '; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } print '
'; @@ -2582,25 +2584,25 @@ elseif (! empty($module)) if (in_array($propname, array('fk_element', 'lines'))) continue; }*/ - $propname=$propkey; - $proplabel=$propval['label']; - $proptype=$propval['type']; - $proparrayofkeyval=$propval['arrayofkeyval']; - $propnotnull=$propval['notnull']; - $propdefault=$propval['default']; - $propindex=$propval['index']; - $propforeignkey=$propval['foreignkey']; - $propposition=$propval['position']; - $propenabled=$propval['enabled']; - $propvisible=$propval['visible']; - $propnoteditable=$propval['noteditable']; - $propsearchall=$propval['searchall']; - $propisameasure=$propval['isameasure']; - $propcss=$propval['css']; - $prophelp=$propval['help']; - $propshowoncombobox=$propval['showoncombobox']; + $propname = $propkey; + $proplabel = $propval['label']; + $proptype = $propval['type']; + $proparrayofkeyval = $propval['arrayofkeyval']; + $propnotnull = $propval['notnull']; + $propdefault = $propval['default']; + $propindex = $propval['index']; + $propforeignkey = $propval['foreignkey']; + $propposition = $propval['position']; + $propenabled = $propval['enabled']; + $propvisible = $propval['visible']; + $propnoteditable = $propval['noteditable']; + $propsearchall = $propval['searchall']; + $propisameasure = $propval['isameasure']; + $propcss = $propval['css']; + $prophelp = $propval['help']; + $propshowoncombobox = $propval['showoncombobox']; //$propdisabled=$propval['disabled']; - $propcomment=$propval['comment']; + $propcomment = $propval['comment']; print ''; @@ -2625,37 +2627,37 @@ elseif (! empty($module)) print $propdefault; print ''; print ''; - print $propindex?'1':''; + print $propindex ? '1' : ''; print ''; print ''; - print $propforeignkey?$propforeignkey:''; + print $propforeignkey ? $propforeignkey : ''; print ''; print ''; print $propposition; print ''; print ''; - print $propenabled?$propenabled:''; + print $propenabled ? $propenabled : ''; print ''; print ''; - print $propvisible?$propvisible:''; + print $propvisible ? $propvisible : ''; print ''; print ''; - print $propnoteditable?$propnoteditable:''; + print $propnoteditable ? $propnoteditable : ''; print ''; print ''; - print $propsearchall?'1':''; + print $propsearchall ? '1' : ''; print ''; print ''; - print $propisameasure?$propisameasure:''; + print $propisameasure ? $propisameasure : ''; print ''; print ''; - print $propcss?$propcss:''; + print $propcss ? $propcss : ''; print ''; print ''; - print $prophelp?$prophelp:''; + print $prophelp ? $prophelp : ''; print ''; print ''; - print $propshowoncombobox?$propshowoncombobox:''; + print $propshowoncombobox ? $propshowoncombobox : ''; print ''; /*print ''; print $propdisabled?$propdisabled:''; @@ -2690,7 +2692,7 @@ elseif (! empty($module)) $format = 'asciidoc'; if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; print ' '.$langs->trans("SpecificationFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; } } @@ -2788,13 +2790,13 @@ elseif (! empty($module)) if ($action != 'editfile' || empty($file)) { print ''; - $htmlhelp=$langs->trans("MenusDefDescTooltip", ''.$langs->trans('Setup').' - '.$langs->trans('Menus').''); + $htmlhelp = $langs->trans("MenusDefDescTooltip", ''.$langs->trans('Setup').' - '.$langs->trans('Menus').''); print $form->textwithpicto($langs->trans("MenusDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'
'; print '
'; print '
'; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; print '
'; @@ -2928,13 +2930,13 @@ elseif (! empty($module)) if ($action != 'editfile' || empty($file)) { print ''; - $htmlhelp=$langs->trans("PermissionsDefDescTooltip", ''.$langs->trans('DefaultPermissions').''); + $htmlhelp = $langs->trans("PermissionsDefDescTooltip", ''.$langs->trans('DefaultPermissions').''); print $form->textwithpicto($langs->trans("PermissionsDefDesc"), $htmlhelp, 1, 'help', '', 0, 2, 'helpondesc').'
'; print '
'; print '
'; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; print '
'; @@ -3031,7 +3033,7 @@ elseif (! empty($module)) $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; print ''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; print ''; print ''; @@ -3040,13 +3042,13 @@ elseif (! empty($module)) if (dol_is_file($dirins.'/'.$pathtohook)) { print ''.$pathtohook.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } else { print ''.$langs->trans("FileNotYetGenerated").''; - print ''; + print ''; } print ''; } @@ -3098,8 +3100,8 @@ elseif (! empty($module)) print ''; print ' '.$langs->trans("TriggersFile").' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print ''; } } @@ -3107,7 +3109,7 @@ elseif (! empty($module)) { print ''; print ' '.$langs->trans("NoTrigger"); - print ''; + print ''; print ''; } print ''; @@ -3154,19 +3156,19 @@ elseif (! empty($module)) if (dol_is_file($dirins.'/'.$pathtohook)) { print ''.$pathtohook.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } else { print ''.$langs->trans("FileNotYetGenerated").''; - print ''; + print ''; } print ''; } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3178,8 +3180,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
'; print '
'; print ''; @@ -3206,19 +3208,19 @@ elseif (! empty($module)) if (dol_is_file($dirins.'/'.$pathtohook)) { print ''.$pathtohook.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; } else { print ''.$langs->trans("FileNotYetGenerated").''; - print ''; + print ''; } print ''; } else { - $fullpathoffile=dol_buildpath($file, 0); + $fullpathoffile = dol_buildpath($file, 0); $content = file_get_contents($fullpathoffile); @@ -3230,8 +3232,8 @@ elseif (! empty($module)) print ''; print ''; - $doleditor=new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); - print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09')?GETPOST('format', 'aZ09'):'html')); + $doleditor = new DolEditor('editfilecontent', $content, '', '300', 'Full', 'In', true, false, 'ace', 0, '99%'); + print $doleditor->Create(1, '', false, $langs->trans("File").' : '.$file, (GETPOST('format', 'aZ09') ?GETPOST('format', 'aZ09') : 'html')); print '
'; print '
'; print ''; @@ -3262,15 +3264,15 @@ elseif (! empty($module)) $pathtofile = $widget['relpath']; print ' '.$langs->trans("WidgetFile").' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print ''; } } else { print ' '.$langs->trans("NoWidget"); - print ''; + print ''; print ''; } print ''; @@ -3348,15 +3350,15 @@ elseif (! empty($module)) $pathtofile = $clifile['relpath']; print ' '.$langs->trans("CLIFile").' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print ''; } } else { print ' '.$langs->trans("NoCLIFile"); - print ''; + print ''; print ''; } print ''; @@ -3400,7 +3402,7 @@ elseif (! empty($module)) print '
'; print ' '.$langs->trans("DescriptorFile").' : '.$pathtofile.''; - print ' '.img_picto($langs->trans("Edit"), 'edit').''; + print ' '.img_picto($langs->trans("Edit"), 'edit').''; print '
'; print '
'; @@ -3529,8 +3531,8 @@ elseif (! empty($module)) if (preg_match('/\.md$/i', $spec['name'])) $format = 'markdown'; print ''; print ' '.$langs->trans("SpecificationFile").' : '.$pathtofile.''; - print ''.img_picto($langs->trans("Edit"), 'edit').''; - print ''.img_picto($langs->trans("Delete"), 'delete').''; + print ''.img_picto($langs->trans("Edit"), 'edit').''; + print ''.img_picto($langs->trans("Delete"), 'delete').''; print ''; } } @@ -3538,7 +3540,7 @@ elseif (! empty($module)) { print ''; print ' '.$langs->trans("FileNotYetGenerated"); - print ''; + print ''; print ''; } print ''; @@ -3616,7 +3618,7 @@ elseif (! empty($module)) print ''; print ''; print ''; print ''; } @@ -3626,28 +3628,28 @@ elseif (! empty($module)) print ''.$langs->trans("BuildPackageDesc").''; print '
'; - if (! class_exists('ZipArchive') && ! defined('ODTPHP_PATHTOPCLZIP')) + if (!class_exists('ZipArchive') && !defined('ODTPHP_PATHTOPCLZIP')) { print img_warning().' '.$langs->trans("ErrNoZipEngine"); print '
'; } - $modulelowercase=strtolower($module); + $modulelowercase = strtolower($module); // Zip file to build - $FILENAMEZIP=''; + $FILENAMEZIP = ''; // Load module $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; dol_include_once($pathtofile); - $class='mod'.$module; + $class = 'mod'.$module; if (class_exists($class)) { try { $moduleobj = new $class($db); } - catch(Exception $e) + catch (Exception $e) { $error++; dol_print_error($e->getMessage()); diff --git a/htdocs/modulebuilder/template/class/actions_mymodule.class.php b/htdocs/modulebuilder/template/class/actions_mymodule.class.php index 530b320b111..45548c28312 100644 --- a/htdocs/modulebuilder/template/class/actions_mymodule.class.php +++ b/htdocs/modulebuilder/template/class/actions_mymodule.class.php @@ -117,7 +117,7 @@ class ActionsMyModule /** - * Overloading the doActions function : replacing the parent's function with the one below + * Overloading the doMassActions function : replacing the parent's function with the one below * * @param array $parameters Hook metadatas (context, etc...) * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) @@ -238,5 +238,46 @@ class ActionsMyModule return $ret; } + + + /** + * Overloading the loadDataForCustomReports function : returns data to complete the customreport tool + * + * @param array $parameters Hook metadatas (context, etc...) + * @param string $action Current action (if set). Generally create or edit or null + * @param HookManager $hookmanager Hook manager propagated to allow calling another hook + * @return int < 0 on error, 0 on success, 1 to replace standard code + */ + public function loadDataForCustomReports($parameters, &$action, $hookmanager) + { + global $conf, $user, $langs; + + $langs->load("mymodule@mymodule"); + + $this->results = array(); + + $head = array(); + $h = 0; + + if ($parameters['tabfamily'] == 'mymodule') { + $head[$h][0] = dol_buildpath('/module/index.php', 1); + $head[$h][1] = $langs->trans("Home"); + $head[$h][2] = 'home'; + $h++; + + $this->results['title'] = $langs->trans("MyModule"); + $this->results['picto'] = 'mymodule@mymodule'; + } + + $head[$h][0] = 'customreports.php?objecttype='.$parameters['objecttype'].(empty($parameters['tabfamily'])?'':'&tabfamily='.$parameters['tabfamily']); + $head[$h][1] = $langs->trans("CustomReports"); + $head[$h][2] = 'customreports'; + + $this->results['head'] = $head; + + return 1; + } + + /* Add here any other hooked methods... */ } diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index 596e47e12c0..fe4cc0931fd 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -43,7 +43,8 @@ class MyObject extends CommonObject public $table_element = 'mymodule_myobject'; /** - * @var int Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table */ public $ismultientitymanaged = 0; @@ -67,7 +68,7 @@ class MyObject extends CommonObject * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') * 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. + * '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) @@ -237,13 +238,13 @@ class MyObject extends CommonObject // Translate some data of arrayofkeyval if (is_object($langs)) { - foreach($this->fields as $key => $val) + foreach ($this->fields as $key => $val) { if (is_array($val['arrayofkeyval'])) { - foreach($val['arrayofkeyval'] as $key2 => $val2) + foreach ($val['arrayofkeyval'] as $key2 => $val2) { - $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2); + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } } @@ -733,7 +734,7 @@ class MyObject extends CommonObject $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; if (isset($this->status)) { - $label.= '
' . $langs->trans("Status").": ".$this->getLibStatut(5); + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); } $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id; diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php index 26866a6b9f1..09e4902d6f9 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_advanced.php @@ -38,7 +38,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject * Dolibarr version of the loaded document * @var string */ - public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' /** * @var string Error message @@ -48,7 +48,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject /** * @var string name */ - public $name='advanced'; + public $name = 'advanced'; /** @@ -65,28 +65,28 @@ class mod_myobject_advanced extends ModeleNumRefMyObject $form = new Form($db); $texte = $langs->trans('GenericNumRefModelDesc')."
\n"; - $texte.= '
'; - $texte.= ''; - $texte.= ''; - $texte.= ''; - $texte.= ''; + $texte .= ''; + $texte .= ''; + $texte .= ''; + $texte .= ''; + $texte .= '
'; - $tooltip=$langs->trans("GenericMaskCodes", $langs->transnoentities("MyObject"), $langs->transnoentities("MyObject")); - $tooltip.=$langs->trans("GenericMaskCodes2"); - $tooltip.=$langs->trans("GenericMaskCodes3"); - $tooltip.=$langs->trans("GenericMaskCodes4a", $langs->transnoentities("MyObject"), $langs->transnoentities("MyObject")); - $tooltip.=$langs->trans("GenericMaskCodes5"); + $tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("MyObject"), $langs->transnoentities("MyObject")); + $tooltip .= $langs->trans("GenericMaskCodes2"); + $tooltip .= $langs->trans("GenericMaskCodes3"); + $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("MyObject"), $langs->transnoentities("MyObject")); + $tooltip .= $langs->trans("GenericMaskCodes5"); // Parametrage du prefix - $texte.= ''; - $texte.= ''; + $texte .= ''; + $texte .= ''; - $texte.= ''; + $texte .= ''; - $texte.= ''; + $texte .= ''; - $texte.= '
'.$langs->trans("Mask").':'.$form->textwithpicto('', $tooltip, 1, 1).'
'.$langs->trans("Mask").':'.$form->textwithpicto('', $tooltip, 1, 1).'   
'; - $texte.= '
'; + $texte .= ''; + $texte .= ''; return $texte; } @@ -98,17 +98,17 @@ class mod_myobject_advanced extends ModeleNumRefMyObject */ public function getExample() { - global $conf,$langs,$mysoc; + global $conf, $langs, $mysoc; - $old_code_client=$mysoc->code_client; - $old_code_type=$mysoc->typent_code; - $mysoc->code_client='CCCCCCCCCC'; - $mysoc->typent_code='TTTTTTTTTT'; - $numExample = $this->getNextValue($mysoc, ''); - $mysoc->code_client=$old_code_client; - $mysoc->typent_code=$old_code_type; + $old_code_client = $mysoc->code_client; + $old_code_type = $mysoc->typent_code; + $mysoc->code_client = 'CCCCCCCCCC'; + $mysoc->typent_code = 'TTTTTTTTTT'; + $numExample = $this->getNextValue($mysoc); + $mysoc->code_client = $old_code_client; + $mysoc->typent_code = $old_code_type; - if (! $numExample) + if (!$numExample) { $numExample = $langs->trans('NotConfigured'); } @@ -123,22 +123,22 @@ class mod_myobject_advanced extends ModeleNumRefMyObject */ public function getNextValue($object) { - global $db,$conf; + global $db, $conf; - require_once DOL_DOCUMENT_ROOT .'/core/lib/functions2.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // We get cursor rule - $mask=$conf->global->MYMODULE_MYOBJECT_ADVANCED_MASK; + $mask = $conf->global->MYMODULE_MYOBJECT_ADVANCED_MASK; - if (! $mask) + if (!$mask) { - $this->error='NotConfigured'; + $this->error = 'NotConfigured'; return 0; } $date = $object->date; - $numFinal=get_next_value($db, $mask, 'mymodule_myobject', 'ref', '', null, $date); + $numFinal = get_next_value($db, $mask, 'mymodule_myobject', 'ref', '', null, $date); return $numFinal; } diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php index e18e7636b6d..71926700aa4 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/mod_myobject_standard.php @@ -34,19 +34,19 @@ class mod_myobject_standard extends ModeleNumRefMyObject * Dolibarr version of the loaded document * @var string */ - public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' - public $prefix='MYOBJECT'; + public $prefix = 'MYOBJECT'; /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string name */ - public $name='standard'; + public $name = 'standard'; /** @@ -80,26 +80,26 @@ class mod_myobject_standard extends ModeleNumRefMyObject */ public function canBeActivated() { - global $conf,$langs,$db; + global $conf, $langs, $db; - $coyymm=''; $max=''; + $coyymm = ''; $max = ''; - $posindice=8; + $posindice = 8; $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max"; - $sql.= " FROM ".MAIN_DB_PREFIX."mymodule_myobject"; - $sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."mymodule_myobject"; + $sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; + $sql .= " AND entity = ".$conf->entity; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $row = $db->fetch_row($resql); - if ($row) { $coyymm = substr($row[0], 0, 6); $max=$row[0]; } + if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } } - if ($coyymm && ! preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) + if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) { $langs->load("errors"); - $this->error=$langs->trans('ErrorNumRefModel', $max); + $this->error = $langs->trans('ErrorNumRefModel', $max); return false; } @@ -114,21 +114,21 @@ class mod_myobject_standard extends ModeleNumRefMyObject */ public function getNextValue($object) { - global $db,$conf; + global $db, $conf; // D'abord on recupere la valeur max - $posindice=9; + $posindice = 9; $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max"; - $sql.= " FROM ".MAIN_DB_PREFIX."mymodule_myobject"; - $sql.= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; - $sql.= " AND entity = ".$conf->entity; + $sql .= " FROM ".MAIN_DB_PREFIX."mymodule_myobject"; + $sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; + $sql .= " AND entity = ".$conf->entity; - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $obj = $db->fetch_object($resql); if ($obj) $max = intval($obj->max); - else $max=0; + else $max = 0; } else { @@ -137,11 +137,11 @@ class mod_myobject_standard extends ModeleNumRefMyObject } //$date=time(); - $date=$object->date_creation; + $date = $object->date_creation; $yymm = strftime("%y%m", $date); - if ($max >= (pow(10, 4) - 1)) $num=$max+1; // If counter > 9999, we do not format on 4 chars, we take number as it is - else $num = sprintf("%04s", $max+1); + if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is + else $num = sprintf("%04s", $max + 1); dol_syslog("mod_myobject_standard::getNextValue return ".$this->prefix.$yymm."-".$num); return $this->prefix.$yymm."-".$num; diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index 46f347618f4..f7f2252ba3c 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -142,14 +142,14 @@ foreach($object->fields as $key => $val) // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { - foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], - 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), + 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], - 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]) + 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]) ); } } @@ -429,7 +429,7 @@ foreach ($object->fields as $key => $val) elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } - elseif (! preg_match('/^(date|timestamp)/', $val['type'])) print ''; + elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; print ''; } } diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index e677c64efc0..302c995b64e 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -491,7 +491,7 @@ class Mo extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - $i=0; + $i = 0; while ($i < $num) { $obj = $this->db->fetch_object($resql); if ($obj) { @@ -542,7 +542,7 @@ class Mo extends CommonObject $error++; } - if (! $error) { + if (!$error) { setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); $this->db->commit(); return 1; @@ -602,14 +602,14 @@ class Mo extends CommonObject } // Lines to consume - if (! $error) { + if (!$error) { foreach ($bom->lines as $line) { $moline = new MoLine($this->db); $moline->fk_mo = $this->id; if ($line->qty_frozen) { - $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce + $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce } else { $moline->qty = round($line->qty * $this->qty / $bom->efficiency, 2); } @@ -965,7 +965,7 @@ class Mo extends CommonObject $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; if (isset($this->status)) { - $label.= '
' . $langs->trans("Status").": ".$this->getLibStatut(5); + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); } $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id; @@ -1167,7 +1167,7 @@ class Mo extends CommonObject if (!dol_strlen($modele)) { //$modele = 'standard'; - $modele = ''; // Remove this once a pdf_standard.php exists. + $modele = ''; // Remove this once a pdf_standard.php exists. if ($this->modelpdf) { $modele = $this->modelpdf; @@ -1178,7 +1178,7 @@ class Mo extends CommonObject $modelpath = "core/modules/mrp/doc/"; - if (empty($modele)) return 1; // Remove this once a pdf_standard.php exists. + if (empty($modele)) return 1; // Remove this once a pdf_standard.php exists. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } diff --git a/htdocs/mrp/lib/mrp_mo.lib.php b/htdocs/mrp/lib/mrp_mo.lib.php index c3f8e7825d4..e1813a3f99c 100644 --- a/htdocs/mrp/lib/mrp_mo.lib.php +++ b/htdocs/mrp/lib/mrp_mo.lib.php @@ -45,10 +45,10 @@ function moPrepareHead($object) $head[$h][1] = $langs->trans("Production"); $arrayproduced = $object->fetchLinesLinked('produced', 0); $nbProduced = 0; - foreach($arrayproduced as $lineproduced) { + foreach ($arrayproduced as $lineproduced) { $nbProduced += $lineproduced['qty']; } - $head[$h][1].= ''.$nbProduced.' / '.$object->qty.''; + $head[$h][1] .= ''.$nbProduced.' / '.$object->qty.''; $head[$h][2] = 'production'; $h++; @@ -59,19 +59,19 @@ function moPrepareHead($object) if (!empty($object->note_public)) $nbNote++; $head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1].= ''.$nbNote.''; + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'note'; $h++; } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->mrp->dir_output . "/mo/" . dol_sanitizeFileName($object->ref); + $upload_dir = $conf->mrp->dir_output."/mo/".dol_sanitizeFileName($object->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ''.($nbFiles+$nbLinks).''; + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'document'; $h++; diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index abaf216b7ab..973e964a1cf 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -136,7 +136,7 @@ if (empty($reshook)) else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); } } - if ($cancel && ! empty($backtopageforcancel)) { + if ($cancel && !empty($backtopageforcancel)) { $backtopage = $backtopageforcancel; } @@ -522,7 +522,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (!empty($object->lines)) { $i = 0; - foreach($object->lines as $line) { + foreach ($object->lines as $line) { if ($line->role == 'toconsume') { if ($i) print ', '; $tmpproduct = new Product($db); @@ -541,7 +541,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (!empty($object->lines)) { $i = 0; - foreach($object->lines as $line) { + foreach ($object->lines as $line) { if ($line->role == 'toproduce') { if ($i) print ', '; $tmpproduct = new Product($db); diff --git a/htdocs/mrp/mo_production.php b/htdocs/mrp/mo_production.php index 873b154ffeb..8dffd3dad19 100644 --- a/htdocs/mrp/mo_production.php +++ b/htdocs/mrp/mo_production.php @@ -170,24 +170,24 @@ if (empty($reshook)) $db->begin(); // Process line to consume - foreach($object->lines as $line) { + foreach ($object->lines as $line) { if ($line->role == 'toconsume') { $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); - $i=1; + $i = 1; while (GETPOSTISSET('qty-'.$line->id.'-'.$i)) { $qtytoprocess = price2num(GETPOST('qty-'.$line->id.'-'.$i)); if ($qtytoprocess != 0) { // Check warehouse is set if we should have to if (GETPOSTISSET('idwarehouse-'.$line->id.'-'.$i)) { // If there is a warehouse to set - if (! (GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set. + if (!(GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set. $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors'); $error++; } - if ($tmpproduct->status_batch && (! GETPOST('batch-'.$line->id.'-'.$i))) { + if ($tmpproduct->status_batch && (!GETPOST('batch-'.$line->id.'-'.$i))) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors'); $error++; @@ -195,7 +195,7 @@ if (empty($reshook)) } $idstockmove = 0; - if (! $error && GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0) { + if (!$error && GETPOST('idwarehouse-'.$line->id.'-'.$i) > 0) { // Record stock movement $id_product_batch = 0; $stockmove->origin = $object; @@ -206,7 +206,7 @@ if (empty($reshook)) } } - if (! $error) { + if (!$error) { $pos = 0; // Record consumption $moline = new MoLine($db); @@ -237,24 +237,24 @@ if (empty($reshook)) } // Process line to produce - foreach($object->lines as $line) { + foreach ($object->lines as $line) { if ($line->role == 'toproduce') { $tmpproduct = new Product($db); $tmpproduct->fetch($line->fk_product); - $i=1; + $i = 1; while (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) { $qtytoprocess = price2num(GETPOST('qtytoproduce-'.$line->id.'-'.$i)); if ($qtytoprocess != 0) { // Check warehouse is set if we should have to if (GETPOSTISSET('idwarehousetoproduce-'.$line->id.'-'.$i)) { // If there is a warehouse to set - if (! (GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set. + if (!(GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0)) { // If there is no warehouse set. $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors'); $error++; } - if ($tmpproduct->status_batch && (! GETPOST('batchtoproduce-'.$line->id.'-'.$i))) { + if ($tmpproduct->status_batch && (!GETPOST('batchtoproduce-'.$line->id.'-'.$i))) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors'); $error++; @@ -262,7 +262,7 @@ if (empty($reshook)) } $idstockmove = 0; - if (! $error && GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0) { + if (!$error && GETPOST('idwarehousetoproduce-'.$line->id.'-'.$i) > 0) { // Record stock movement $id_product_batch = 0; $stockmove->origin = $object; @@ -273,7 +273,7 @@ if (empty($reshook)) } } - if (! $error) { + if (!$error) { $pos = 0; // Record production $moline = new MoLine($db); @@ -303,16 +303,16 @@ if (empty($reshook)) } } - if (! $error) { + if (!$error) { $consumptioncomplete = true; $productioncomplete = true; if (GETPOST('autoclose', 'int')) { - foreach($object->lines as $line) { + foreach ($object->lines as $line) { if ($line->role == 'toconsume') { $arrayoflines = $object->fetchLinesLinked('consumed', $line->id); $alreadyconsumed = 0; - foreach($arrayoflines as $line2) { + foreach ($arrayoflines as $line2) { $alreadyconsumed += $line2['qty']; } @@ -323,7 +323,7 @@ if (empty($reshook)) if ($line->role == 'toproduce') { $arrayoflines = $object->fetchLinesLinked('produced', $line->id); $alreadyproduced = 0; - foreach($arrayoflines as $line2) { + foreach ($arrayoflines as $line2) { $alreadyproduced += $line2['qty']; } @@ -650,8 +650,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''.$tmpproduct->getNomUrl(1).''; print ''; $help = ''; - if ($line->qty_frozen) $help.=($help ? '
' : '').''.$langs->trans("QuantityFrozen").': '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')'; - if ($line->disable_stock_change) $help.=($help ? '
' : '').''.$langs->trans("DisableStockChange").': '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')'; + if ($line->qty_frozen) $help .= ($help ? '
' : '').''.$langs->trans("QuantityFrozen").': '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')'; + if ($line->disable_stock_change) $help .= ($help ? '
' : '').''.$langs->trans("DisableStockChange").': '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')'; if ($help) { print $form->textwithpicto($line->qty, $help, -1); } else { @@ -685,7 +685,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Warehouse print ''; if ($conf->productbatch->enabled) { - print ''; // Lot + print ''; // Lot } print ''; @@ -823,7 +823,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Warehouse print ''; if ($conf->productbatch->enabled) { - print ''; // Lot + print ''; // Lot } print ''; diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 6d36495d5fc..08ee8624d30 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -1992,7 +1992,7 @@ else // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'product', 1); + print $form->showCategories($object->id, Categorie::TYPE_PRODUCT, 1); print ""; } diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 5eb8ab904cc..17a1e4952ce 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -844,10 +844,10 @@ class Product extends CommonObject $this->height_units = trim($this->height_units); // set unit not defined if (is_numeric($this->length_units)) { - $this->width_units = $this->length_units; // Not used yet + $this->width_units = $this->length_units; // Not used yet } if (is_numeric($this->length_units)) { - $this->height_units = $this->length_units; // Not used yet + $this->height_units = $this->length_units; // Not used yet } // Automated compute surface and volume if not filled if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) { @@ -1882,7 +1882,7 @@ class Product extends CommonObject $newminprice = 0; } if (empty($newminprice)) { - $newminprice=0; + $newminprice = 0; } // Check parameters @@ -4348,8 +4348,8 @@ class Product extends CommonObject $label .= '
'.$langs->trans('ProductAccountancyBuyCode').': '.length_accountg($this->accountancy_code_buy); } if (isset($this->status) && isset($this->status_buy)) { - $label.= '
' . $langs->trans("Status").": ".$this->getLibStatut(5, 0); - $label.= ' '.$this->getLibStatut(5, 1); + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5, 0); + $label .= ' '.$this->getLibStatut(5, 1); } if (!empty($this->entity)) { @@ -4801,7 +4801,7 @@ class Product extends CommonObject } if (!empty($conf->fournisseur->enabled) && !empty($conf->reception->enabled)) { - $result = $this->load_stats_reception(0, '4', 1); // Use same tables than when module reception is not used. + $result = $this->load_stats_reception(0, '4', 1); // Use same tables than when module reception is not used. if ($result < 0) dol_print_error($this->db, $this->error); $stock_reception_fournisseur = $this->stats_reception['qty']; } diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php index f1a2db542c1..f63cbe30017 100644 --- a/htdocs/product/inventory/class/inventory.class.php +++ b/htdocs/product/inventory/class/inventory.class.php @@ -101,7 +101,7 @@ class Inventory extends CommonObject 'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'visible'=>-2, 'enabled'=>1, 'position'=>512), 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), - 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>4, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Recorded', 9=>'Canceled')), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>4, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Recorded', 9=>'Canceled')) ); /** diff --git a/htdocs/product/list.php b/htdocs/product/list.php index 9fc5eaa62d4..df65a79f14b 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -168,24 +168,33 @@ $isInEEC = isInEEC($mysoc); $arrayfields = array( 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), - 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->service->enabled))), - 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled))), - 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(!empty($conf->service->enabled) && (string) $type == '1')), - 'p.weight'=>array('label'=>$langs->trans("Weight"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled))), - 'p.length'=>array('label'=>$langs->trans("Length"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_SIZE))), - 'p.surface'=>array('label'=>$langs->trans("Surface"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_SURFACE))), - 'p.volume'=>array('label'=>$langs->trans("Volume"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_DISABLE_VOLUME))), - 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES)), - 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(!empty($user->rights->fournisseur->lire))), - 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), - 'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), - 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire))), - 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service')), - 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical)), - 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1, 'position'=>10), + 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->service->enabled)), 'position'=>11), + 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>1, 'enabled'=>(!empty($conf->barcode->enabled)), 'position'=>12), + 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(!empty($conf->service->enabled) && (string) $type == '1'), 'position'=>13), + 'p.weight'=>array('label'=>$langs->trans('Weight'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>20), + 'p.weight_units'=>array('label'=>$langs->trans('WeightUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && $type != '1'), 'position'=>21), + 'p.length'=>array('label'=>$langs->trans('Length'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>22), + 'p.length_units'=>array('label'=>$langs->trans('LengthUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>23), + 'p.width'=>array('label'=>$langs->trans('Width'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>24), + 'p.width_units'=>array('label'=>$langs->trans('WidthUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>25), + 'p.height'=>array('label'=>$langs->trans('Height'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>26), + 'p.height_units'=>array('label'=>$langs->trans('HeightUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SIZE) && $type != '1'), 'position'=>27), + 'p.surface'=>array('label'=>$langs->trans('Surface'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>28), + 'p.surface_units'=>array('label'=>$langs->trans('SurfaceUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_SURFACE) && $type != '1'), 'position'=>29), + 'p.volume'=>array('label'=>$langs->trans('Volume'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>30), + 'p.volume_units'=>array('label'=>$langs->trans('VolumeUnits'), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && empty($conf->global->PRODUCT_DISABLE_VOLUME) && $type != '1'), 'position'=>31), + 'cu.label'=>array('label'=>$langs->trans("DefaultUnitToShow"), 'checked'=>0, 'enabled'=>(!empty($conf->product->enabled) && !empty($conf->global->PRODUCT_USE_UNITS)), 'position'=>32), + 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES), 'position'=>40), + 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>41), + 'p.numbuyprice'=>array('label'=>$langs->trans("BuyingPriceNumShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>42), + 'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>43), + 'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>44), + 'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>50), + 'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>51), + 'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>52), + 'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical), 'position'=>53), + 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>60), 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0, 'position'=>400), 'p.accountancy_code_sell_intra'=>array('label'=>$langs->trans("ProductAccountancySellIntraCode"), 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>401), 'p.accountancy_code_sell_export'=>array('label'=>$langs->trans("ProductAccountancySellExportCode"), 'checked'=>0, 'position'=>402), @@ -288,7 +297,8 @@ $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type, p.barcode, p $sql .= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; $sql .= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy,'; $sql .= ' p.datec as date_creation, p.tms as date_update, p.pmp, p.stock,'; -$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units,'; +$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units,'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ' p.fk_unit, cu.label as cu_label,'; $sql .= ' MIN(pfp.unitprice) as minsellprice'; if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid prod_comb_id'; @@ -311,6 +321,7 @@ if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; } +if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units cu ON cu.rowid = p.fk_unit"; $sql .= ' WHERE p.entity IN ('.getEntity('product').')'; @@ -375,7 +386,8 @@ $sql .= $hookmanager->resPrint; $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.tva_tx, p.price_ttc, p.price_base_type,"; $sql .= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; $sql .= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export, p.accountancy_code_buy, p.pmp, p.stock,'; -$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.width, p.width_units, p.height, p.height_units'; +$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units'; +if (!empty($conf->global->PRODUCT_USE_UNITS)) $sql .= ', p.fk_unit, cu.label'; if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) { $sql .= ', pac.rowid'; @@ -476,11 +488,11 @@ if ($resql) //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - $rightskey='produit'; - if ($type == Product::TYPE_SERVICE) $rightskey='service'; + $rightskey = 'produit'; + if ($type == Product::TYPE_SERVICE) $rightskey = 'service'; if ($user->rights->{$rightskey}->supprimer) $arrayofmassactions['predelete'] = "".$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; if ($type === "") $perm = ($user->rights->produit->creer || $user->rights->service->creer); @@ -624,24 +636,72 @@ if ($resql) print ''; print ''; } + // Weight units + if (!empty($arrayfields['p.weight_units']['checked'])) { + print ''; + print ''; + } // Length if (!empty($arrayfields['p.length']['checked'])) { print ''; print ''; } + // Length units + if (!empty($arrayfields['p.length_units']['checked'])) { + print ''; + print ''; + } + // Width + if (!empty($arrayfields['p.width']['checked'])) { + print ''; + print ''; + } + // Width units + if (!empty($arrayfields['p.width_units']['checked'])) { + print ''; + print ''; + } + // Height + if (!empty($arrayfields['p.height']['checked'])) + { + print ''; + print ''; + } + // Height units + if (!empty($arrayfields['p.height_units']['checked'])) { + print ''; + print ''; + } // Surface if (!empty($arrayfields['p.surface']['checked'])) { print ''; print ''; } + // Surface units + if (!empty($arrayfields['p.surface_units']['checked'])) { + print ''; + print ''; + } // Volume if (!empty($arrayfields['p.volume']['checked'])) { print ''; print ''; } + // Volume units + if (!empty($arrayfields['p.volume_units']['checked'])) { + print ''; + print ''; + } + + // Unit + if (!empty($arrayfields['cu.label']['checked'])) + { + print ''; + print ''; + } // Sell price if (!empty($arrayfields['p.sellprice']['checked'])) @@ -759,10 +819,19 @@ if ($resql) if (!empty($arrayfields['p.duration']['checked'])) { print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"], "p.duration", "", $param, '', $sortfield, $sortorder, 'center '); } - if (!empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER["PHP_SELF"], "p.weight", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER["PHP_SELF"], "p.length", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.surface']['checked'])) print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER["PHP_SELF"], "p.surface", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.volume']['checked'])) print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER["PHP_SELF"], "p.volume", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER['PHP_SELF'], 'p.weight', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.weight_units']['checked'])) print_liste_field_titre($arrayfields['p.weight_units']['label'], $_SERVER['PHP_SELF'], 'p.weight_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER['PHP_SELF'], 'p.length', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.length_units']['checked'])) print_liste_field_titre($arrayfields['p.length_units']['label'], $_SERVER['PHP_SELF'], 'p.length_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.width']['checked'])) print_liste_field_titre($arrayfields['p.width']['label'], $_SERVER['PHP_SELF'], 'p.width', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.width_units']['checked'])) print_liste_field_titre($arrayfields['p.width_units']['label'], $_SERVER['PHP_SELF'], 'p.width_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.height']['checked'])) print_liste_field_titre($arrayfields['p.height']['label'], $_SERVER['PHP_SELF'], 'p.height', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.height_units']['checked'])) print_liste_field_titre($arrayfields['p.height_units']['label'], $_SERVER['PHP_SELF'], 'p.height_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.surface']['checked'])) print_liste_field_titre($arrayfields['p.surface']['label'], $_SERVER['PHP_SELF'], "p.surface", '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.surface_units']['checked'])) print_liste_field_titre($arrayfields['p.surface_units']['label'], $_SERVER['PHP_SELF'], 'p.surface_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.volume']['checked'])) print_liste_field_titre($arrayfields['p.volume']['label'], $_SERVER['PHP_SELF'], 'p.volume', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['p.volume_units']['checked'])) print_liste_field_titre($arrayfields['p.volume_units']['label'], $_SERVER['PHP_SELF'], 'p.volume_units', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['cu.label']['checked'])) print_liste_field_titre($arrayfields['cu.label']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['p.sellprice']['checked'])) { print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); } @@ -880,6 +949,9 @@ if ($resql) $product_static->volume_units = $obj->volume_units; $product_static->surface = $obj->surface; $product_static->surface_units = $obj->surface_units; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $product_static->fk_unit = $obj->fk_unit; + } // STOCK_DISABLE_OPTIM_LOAD can be set to force load_stock whatever is permissions on stock. if ((!empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) || !empty($conf->global->STOCK_DISABLE_OPTIM_LOAD)) // To optimize call of load_stock @@ -974,6 +1046,13 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Weight units + if (!empty($arrayfields['p.weight_units']['checked'])) { + print ''; + if ($product_static->weight != '') print measuringUnitString(0, 'weight', $product_static->weight_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } // Length if (!empty($arrayfields['p.length']['checked'])) { @@ -982,6 +1061,43 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Length units + if (!empty($arrayfields['p.length_units']['checked'])) { + print ''; + if ($product_static->length != '') print measuringUnitString(0, 'size', $product_static->length_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Width + if (!empty($arrayfields['p.width']['checked'])) + { + print ''; + print $obj->width; + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Width units + if (!empty($arrayfields['p.width_units']['checked'])) { + print ''; + if ($product_static->width != '') print measuringUnitString(0, 'size', $product_static->width_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Height + if (!empty($arrayfields['p.height']['checked'])) + { + print ''; + print $obj->height; + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Height units + if (!empty($arrayfields['p.height_units']['checked'])) { + print ''; + if ($product_static->height != '') print measuringUnitString(0, 'size', $product_static->height_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } // Surface if (!empty($arrayfields['p.surface']['checked'])) { @@ -990,6 +1106,13 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Surface units + if (!empty($arrayfields['p.surface_units']['checked'])) { + print ''; + if ($product_static->surface != '') print measuringUnitString(0, 'surface', $product_static->surface_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } // Volume if (!empty($arrayfields['p.volume']['checked'])) { @@ -998,6 +1121,23 @@ if ($resql) print ''; if (!$i) $totalarray['nbfield']++; } + // Volume units + if (!empty($arrayfields['p.volume_units']['checked'])) { + print ''; + if ($product_static->volume != '') print measuringUnitString(0, 'volume', $product_static->volume_units); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Unit + if (!empty($arrayfields['cu.label']['checked'])) + { + print ''; + if (!empty($obj->cu_label)) { + print $langs->trans($obj->cu_label); + } + print ''; + if (!$i) $totalarray['nbfield']++; + } // Sell price if (!empty($arrayfields['p.sellprice']['checked'])) diff --git a/htdocs/product/reassortlot.php b/htdocs/product/reassortlot.php index b63a891973c..e07dcf0536d 100644 --- a/htdocs/product/reassortlot.php +++ b/htdocs/product/reassortlot.php @@ -38,20 +38,20 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->loadLangs(array('products', 'stocks', 'productbatch')); // Security check -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'produit|service'); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service'); -$action=GETPOST('action', 'alpha'); -$sref=GETPOST("sref", 'alpha'); -$snom=GETPOST("snom", 'alpha'); -$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$type=GETPOST("type", "int"); -$search_barcode=GETPOST("search_barcode", 'alpha'); -$search_warehouse=GETPOST('search_warehouse', 'alpha'); -$search_batch=GETPOST('search_batch', 'alpha'); -$catid=GETPOST('catid', 'int'); -$toolowstock=GETPOST('toolowstock'); +$action = GETPOST('action', 'alpha'); +$sref = GETPOST("sref", 'alpha'); +$snom = GETPOST("snom", 'alpha'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$type = GETPOST("type", "int"); +$search_barcode = GETPOST("search_barcode", 'alpha'); +$search_warehouse = GETPOST('search_warehouse', 'alpha'); +$search_batch = GETPOST('search_batch', 'alpha'); +$catid = GETPOST('catid', 'int'); +$toolowstock = GETPOST('toolowstock'); $tosell = GETPOST("tosell"); $tobuy = GETPOST("tobuy"); $fourn_id = GETPOST("fourn_id", 'int'); @@ -60,20 +60,20 @@ $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; -if (! $sortfield) $sortfield="p.ref"; -if (! $sortorder) $sortorder="ASC"; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +if (!$sortfield) $sortfield = "p.ref"; +if (!$sortorder) $sortorder = "ASC"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $limit * $page ; +$offset = $limit * $page; // Load sale and categ filters $search_sale = GETPOST("search_sale"); $search_categ = GETPOST("search_categ"); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$canvas=GETPOST("canvas"); -$objcanvas=null; -if (! empty($canvas)) +$canvas = GETPOST("canvas"); +$objcanvas = null; +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); @@ -88,20 +88,20 @@ if (! empty($canvas)) if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $sref=""; - $snom=""; - $sall=""; - $tosell=""; - $tobuy=""; - $search_sale=""; - $search_categ=""; - $type=""; - $catid=''; - $toolowstock=''; - $search_batch=''; - $search_warehouse=''; - $fourn_id=''; - $sbarcode=''; + $sref = ""; + $snom = ""; + $sall = ""; + $tosell = ""; + $tobuy = ""; + $search_sale = ""; + $search_categ = ""; + $type = ""; + $catid = ''; + $toolowstock = ''; + $search_batch = ''; + $search_warehouse = ''; + $fourn_id = ''; + $sbarcode = ''; } @@ -109,64 +109,64 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' * View */ -$helpurl='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; +$helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; -$form=new Form($db); -$htmlother=new FormOther($db); +$form = new Form($db); +$htmlother = new FormOther($db); -$title=$langs->trans("ProductsAndServices"); +$title = $langs->trans("ProductsAndServices"); $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; -$sql.= ' p.fk_product_type, p.tms as datem,'; -$sql.= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,'; -$sql.= ' ps.fk_entrepot,'; -$sql.= ' e.ref as warehouse_ref, e.lieu as warehouse_lieu, e.fk_parent as warehouse_parent,'; -$sql.= ' pb.batch, pb.eatby as oldeatby, pb.sellby as oldsellby,'; -$sql.= ' pl.rowid as lotid, pl.eatby, pl.sellby,'; -$sql.= ' SUM(pb.qty) as stock_physique, COUNT(pb.rowid) as nbinbatchtable'; -$sql.= ' FROM '.MAIN_DB_PREFIX.'product as p'; -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps on p.rowid = ps.fk_product'; // Detail for each warehouse -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid'; // Link on unique key -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key +$sql .= ' p.fk_product_type, p.tms as datem,'; +$sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,'; +$sql .= ' ps.fk_entrepot,'; +$sql .= ' e.ref as warehouse_ref, e.lieu as warehouse_lieu, e.fk_parent as warehouse_parent,'; +$sql .= ' pb.batch, pb.eatby as oldeatby, pb.sellby as oldsellby,'; +$sql .= ' pl.rowid as lotid, pl.eatby, pl.sellby,'; +$sql .= ' SUM(pb.qty) as stock_physique, COUNT(pb.rowid) as nbinbatchtable'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps on p.rowid = ps.fk_product'; // Detail for each warehouse +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid'; // Link on unique key +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key // We'll need this table joined to the select in order to filter by categ -if ($search_categ) $sql.= ", ".MAIN_DB_PREFIX."categorie_product as cp"; -$sql.= " WHERE p.entity IN (".getEntity('product').")"; -if ($search_categ) $sql.= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ -if ($sall) $sql.=natural_search(array('p.ref','p.label','p.description','p.note'), $sall); +if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp"; +$sql .= " WHERE p.entity IN (".getEntity('product').")"; +if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ +if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall); // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($type)) { - if ($type==1) + if ($type == 1) { - $sql.= " AND p.fk_product_type = '1'"; + $sql .= " AND p.fk_product_type = '1'"; } else { - $sql.= " AND p.fk_product_type <> '1'"; + $sql .= " AND p.fk_product_type <> '1'"; } } -if ($sref) $sql.= natural_search("p.ref", $sref); -if ($search_barcode) $sql.= natural_search("p.barcode", $search_barcode); -if ($snom) $sql.= natural_search("p.label", $snom); -if (! empty($tosell)) $sql.= " AND p.tosell = ".$tosell; -if (! empty($tobuy)) $sql.= " AND p.tobuy = ".$tobuy; -if (! empty($canvas)) $sql.= " AND p.canvas = '".$db->escape($canvas)."'"; -if($catid) $sql.= " AND cp.fk_categorie = ".$catid; -if ($fourn_id > 0) $sql.= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; +if ($sref) $sql .= natural_search("p.ref", $sref); +if ($search_barcode) $sql .= natural_search("p.barcode", $search_barcode); +if ($snom) $sql .= natural_search("p.label", $snom); +if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell; +if (!empty($tobuy)) $sql .= " AND p.tobuy = ".$tobuy; +if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'"; +if ($catid) $sql .= " AND cp.fk_categorie = ".$catid; +if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id; // Insert categ filter if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ); if ($search_warehouse) $sql .= natural_search("e.ref", $search_warehouse); if ($search_batch) $sql .= natural_search("pb.batch", $search_batch); -$sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; -$sql.= " p.fk_product_type, p.tms,"; -$sql.= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,"; -$sql.= " ps.fk_entrepot,"; -$sql.= " e.ref, e.lieu, e.fk_parent,"; -$sql.= " pb.batch, pb.eatby, pb.sellby,"; -$sql.= " pl.rowid, pl.eatby, pl.sellby"; -if ($toolowstock) $sql.= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet -$sql.= $db->order($sortfield, $sortorder); +$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; +$sql .= " p.fk_product_type, p.tms,"; +$sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,"; +$sql .= " ps.fk_entrepot,"; +$sql .= " e.ref, e.lieu, e.fk_parent,"; +$sql .= " pb.batch, pb.eatby, pb.sellby,"; +$sql .= " pl.rowid, pl.eatby, pl.sellby"; +if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) @@ -180,7 +180,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); if ($resql) @@ -198,35 +198,35 @@ if ($resql) if (isset($type)) { - if ($type==1) { $texte = $langs->trans("Services"); } + if ($type == 1) { $texte = $langs->trans("Services"); } else { $texte = $langs->trans("Products"); } } else { $texte = $langs->trans("ProductsAndServices"); } - $texte.=' ('.$langs->trans("StocksByLotSerial").')'; + $texte .= ' ('.$langs->trans("StocksByLotSerial").')'; - $param=''; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - if ($tosell) $param.="&tosell=".urlencode($tosell); - if ($tobuy) $param.="&tobuy=".urlencode($tobuy); - if ($type) $param.="&type=".urlencode($type); - if ($fourn_id) $param.="&fourn_id=".urlencode($fourn_id); - if ($snom) $param.="&snom=".urlencode($snom); - if ($sref) $param.="&sref=".urlencode($sref); - if ($search_batch) $param.="&search_batch=".urlencode($search_batch); - if ($sbarcode) $param.="&sbarcode=".urlencode($sbarcode); - if ($search_warehouse) $param.="&search_warehouse=".urlencode($search_warehouse); - if ($catid) $param.="&catid=".urlencode($catid); - if ($toolowstock) $param.="&toolowstock=".urlencode($toolowstock); - if ($search_sale) $param.="&search_sale=".urlencode($search_sale); - if ($search_categ) $param.="&search_categ=".urlencode($search_categ); + $param = ''; + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($sall) $param .= "&sall=".urlencode($sall); + if ($tosell) $param .= "&tosell=".urlencode($tosell); + if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); + if ($type) $param .= "&type=".urlencode($type); + if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); + if ($snom) $param .= "&snom=".urlencode($snom); + if ($sref) $param .= "&sref=".urlencode($sref); + if ($search_batch) $param .= "&search_batch=".urlencode($search_batch); + if ($sbarcode) $param .= "&sbarcode=".urlencode($sbarcode); + if ($search_warehouse) $param .= "&search_warehouse=".urlencode($search_warehouse); + if ($catid) $param .= "&catid=".urlencode($catid); + if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); + if ($search_sale) $param .= "&search_sale=".urlencode($search_sale); + if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); /*if ($eatby) $param.="&eatby=".$eatby; if ($sellby) $param.="&sellby=".$sellby;*/ llxHeader("", $title, $helpurl, $texte); - print '
'; + print ''; print ''; print ''; print ''; @@ -236,7 +236,7 @@ if ($resql) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'products', 0, '', '', $limit); - if (! empty($catid)) + if (!empty($catid)) { print "
"; $c = new Categorie($db); @@ -247,29 +247,29 @@ if ($resql) } // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) + $moreforfilter = ''; + if (!empty($conf->categorie->enabled)) { - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); - $moreforfilter.='
'; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('Categories').': '; + $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ'); + $moreforfilter .= '
'; } //$moreforfilter.=$langs->trans("StockTooLow").' '; - if (! empty($moreforfilter)) + if (!empty($moreforfilter)) { print '
'; print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
'; } print '
'; - print ''; + print '
'; // Fields title search print ''; @@ -279,7 +279,7 @@ if ($resql) print ''; - if (! empty($conf->service->enabled) && $type == 1) + if (!empty($conf->service->enabled) && $type == 1) { print ''; print ''; print ''; print ''; @@ -303,7 +303,7 @@ if ($resql) print ""; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder); - if (! empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); + if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center '); print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", $param, "", '', $sortfield, $sortorder); //print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right ); print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", $param, "", '', $sortfield, $sortorder, 'center '); @@ -318,52 +318,52 @@ if ($resql) print_liste_field_titre(''); print "\n"; - $product_static=new Product($db); - $product_lot_static=new Productlot($db); - $warehousetmp=new Entrepot($db); + $product_static = new Product($db); + $product_lot_static = new Productlot($db); + $warehousetmp = new Entrepot($db); while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); // Multilangs - if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active { $sql = "SELECT label"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql.= " WHERE fk_product=".$objp->rowid; - $sql.= " AND lang='". $langs->getDefaultLang() ."'"; - $sql.= " LIMIT 1"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product=".$objp->rowid; + $sql .= " AND lang='".$langs->getDefaultLang()."'"; + $sql .= " LIMIT 1"; $result = $db->query($sql); if ($result) { $objtp = $db->fetch_object($result); - if (! empty($objtp->label)) $objp->label = $objtp->label; + if (!empty($objtp->label)) $objp->label = $objtp->label; } } - $product_static->ref=$objp->ref; - $product_static->id=$objp->rowid; + $product_static->ref = $objp->ref; + $product_static->id = $objp->rowid; $product_static->label = $objp->label; - $product_static->type=$objp->fk_product_type; - $product_static->entity=$objp->entity; - $product_static->status=$objp->tosell; - $product_static->status_buy=$objp->tobuy; - $product_static->status_batch=$objp->tobatch; + $product_static->type = $objp->fk_product_type; + $product_static->entity = $objp->entity; + $product_static->status = $objp->tosell; + $product_static->status_buy = $objp->tobuy; + $product_static->status_batch = $objp->tobatch; - $product_lot_static->batch=$objp->batch; - $product_lot_static->product_id=$objp->rowid; - $product_lot_static->id=$objp->lotid; - $product_lot_static->eatby=$objp->eatby; - $product_lot_static->sellby=$objp->sellby; + $product_lot_static->batch = $objp->batch; + $product_lot_static->product_id = $objp->rowid; + $product_lot_static->id = $objp->lotid; + $product_lot_static->eatby = $objp->eatby; + $product_lot_static->sellby = $objp->sellby; - $warehousetmp->id=$objp->fk_entrepot; - $warehousetmp->ref=$objp->warehouse_ref; - $warehousetmp->label=$objp->warehouse_ref; - $warehousetmp->fk_parent=$objp->warehouse_parent; + $warehousetmp->id = $objp->fk_entrepot; + $warehousetmp->ref = $objp->warehouse_ref; + $warehousetmp->label = $objp->warehouse_ref; + $warehousetmp->fk_parent = $objp->warehouse_parent; print ''; @@ -376,7 +376,7 @@ if ($resql) // Label print ''; - if (! empty($conf->service->enabled) && $type == 1) + if (!empty($conf->service->enabled) && $type == 1) { print ''; + print ' ('.$graphfiles[$key]['total'].')'; print ''; print ''; // Image diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index 99dc1978886..d0a1fc5db76 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -454,7 +454,7 @@ else // Categories if ($conf->categorie->enabled) { print '"; } print "
'; print ''; print ''; print ' '; @@ -294,7 +294,7 @@ if ($resql) print '  '; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print '
'.$objp->label.''; if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear"); diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index 5ca7992be31..24387ef8b73 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2005 Eric Seigne * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2019 Thibault FOUCART * * 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 @@ -351,6 +352,7 @@ if ($result || empty($id)) $url = DOL_URL_ROOT.'/viewimage.php?modulepart='.$graphfiles[$key]['modulepart'].'&entity='.$object->entity.'&file='.urlencode($graphfiles[$key]['file']); $px->draw($dir."/".$graphfiles[$key]['file'], $url); + $graphfiles[$key]['total'] = $px->total(); $graphfiles[$key]['output'] = $px->show(); } else @@ -405,7 +407,7 @@ if ($result || empty($id)) // Label print '
'; print $graphfiles[$key]['label']; - print ''.$linktoregenerate.'
'.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'warehouse', 1); + print $form->showCategories($object->id, Categorie::TYPE_WAREHOUSE, 1); print "
"; diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php index 1c18627f2cf..0c61ae605c0 100644 --- a/htdocs/product/stock/class/api_stockmovements.class.php +++ b/htdocs/product/stock/class/api_stockmovements.class.php @@ -99,47 +99,47 @@ class StockMovements extends DolibarrApi $obj_ret = array(); - if(! DolibarrApiAccess::$user->rights->stock->lire) { + if (!DolibarrApiAccess::$user->rights->stock->lire) { throw new RestException(401); } $sql = "SELECT t.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."stock_mouvement as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as t"; //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')'; - $sql.= ' WHERE 1 = 1'; + $sql .= ' WHERE 1 = 1'; // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($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).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { if ($page < 0) { $page = 0; } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } $result = $db->query($sql); if ($result) { - $i=0; + $i = 0; $num = $db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); while ($i < $min) { $obj = $db->fetch_object($result); $stockmovement_static = new MouvementStock($db); - if($stockmovement_static->fetch($obj->rowid)) { + if ($stockmovement_static->fetch($obj->rowid)) { $obj_ret[] = $this->_cleanObjectDatas($stockmovement_static); } $i++; @@ -148,7 +148,7 @@ class StockMovements extends DolibarrApi else { throw new RestException(503, 'Error when retrieve stock movement list : '.$db->lasterror()); } - if( ! count($obj_ret)) { + if (!count($obj_ret)) { throw new RestException(404, 'No stock movement found'); } return $obj_ret; @@ -177,7 +177,7 @@ class StockMovements extends DolibarrApi */ public function post($product_id, $warehouse_id, $qty, $lot = '', $movementcode = '', $movementlabel = '', $price = '', $dlc = '', $dluo = '') { - if(! DolibarrApiAccess::$user->rights->stock->creer) { + if (!DolibarrApiAccess::$user->rights->stock->creer) { throw new RestException(401); } @@ -187,7 +187,7 @@ class StockMovements extends DolibarrApi // Type increase or decrease $type = 2; - if ($qty >= 0){ + if ($qty >= 0) { $type = 3; } @@ -195,7 +195,7 @@ class StockMovements extends DolibarrApi $eatBy = empty($dluo) ? '' : dol_stringtotime($dluo); $sellBy = empty($dlc) ? '' : dol_stringtotime($dlc); - if($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) { + if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) { $errormessage = $this->stockmovement->error; if (empty($errormessage)) $errormessage = join(',', $this->stockmovement->errors); throw new RestException(503, 'Error when create stock movement : '.$errormessage); diff --git a/htdocs/product/stock/class/entrepot.class.php b/htdocs/product/stock/class/entrepot.class.php index ab3dfde9bf0..40c358967ce 100644 --- a/htdocs/product/stock/class/entrepot.class.php +++ b/htdocs/product/stock/class/entrepot.class.php @@ -37,18 +37,18 @@ class Entrepot extends CommonObject /** * @var string ID to identify managed object */ - public $element='stock'; + public $element = 'stock'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='entrepot'; + public $table_element = 'entrepot'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto='stock'; - public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $picto = 'stock'; + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe /** * @var string Label @@ -102,7 +102,7 @@ class Entrepot extends CommonObject /** * @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( + public $fields = array( 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>10), 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-2, 'showoncombobox'=>1, 'position'=>25), 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>30), @@ -181,7 +181,7 @@ class Entrepot extends CommonObject return 0; } - $now=dol_now(); + $now = dol_now(); $this->db->begin(); @@ -189,7 +189,7 @@ class Entrepot extends CommonObject $sql .= " VALUES ('".$this->db->escape($this->libelle)."', ".$conf->entity.", '".$this->db->idate($now)."', ".$user->id.", ".($this->fk_parent > 0 ? $this->fk_parent : "NULL").")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot"); @@ -197,7 +197,7 @@ class Entrepot extends CommonObject { $this->id = $id; - if (! $error) + if (!$error) { $result = $this->update($id, $user); if ($result <= 0) @@ -207,11 +207,11 @@ class Entrepot extends CommonObject } // Actions on extra fields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -219,7 +219,7 @@ class Entrepot extends CommonObject } } - if (! $error) + if (!$error) { $this->db->commit(); return $id; @@ -232,14 +232,14 @@ class Entrepot extends CommonObject } } else { - $this->error="Failed to get insert id"; + $this->error = "Failed to get insert id"; dol_syslog(get_class($this)."::create return -2"); return -2; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_syslog(get_class($this)."::create Error ".$this->db->error()); $this->db->rollback(); return -1; @@ -257,56 +257,56 @@ class Entrepot extends CommonObject { global $conf; - $error=0; + $error = 0; if (empty($id)) $id = $this->id; // Check if new parent is already a child of current warehouse - if(!empty($this->fk_parent)) + if (!empty($this->fk_parent)) { $TChildWarehouses = array($id); $TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses); - if(in_array($this->fk_parent, $TChildWarehouses)) + if (in_array($this->fk_parent, $TChildWarehouses)) { $this->error = 'ErrorCannotAddThisParentWarehouse'; return -2; } } - $this->libelle=trim($this->libelle); - $this->description=trim($this->description); + $this->libelle = trim($this->libelle); + $this->description = trim($this->description); - $this->lieu=trim($this->lieu); + $this->lieu = trim($this->lieu); - $this->address=trim($this->address); - $this->zip=trim($this->zip); - $this->town=trim($this->town); - $this->country_id=($this->country_id > 0 ? $this->country_id : 0); + $this->address = trim($this->address); + $this->zip = trim($this->zip); + $this->town = trim($this->town); + $this->country_id = ($this->country_id > 0 ? $this->country_id : 0); $sql = "UPDATE ".MAIN_DB_PREFIX."entrepot "; - $sql .= " SET ref = '" . $this->db->escape($this->libelle) ."'"; - $sql .= ", fk_parent = " . (($this->fk_parent > 0) ? $this->fk_parent : "NULL"); - $sql .= ", description = '" . $this->db->escape($this->description) ."'"; - $sql .= ", statut = " . $this->statut; - $sql .= ", lieu = '" . $this->db->escape($this->lieu) ."'"; - $sql .= ", address = '" . $this->db->escape($this->address) ."'"; - $sql .= ", zip = '" . $this->db->escape($this->zip) ."'"; - $sql .= ", town = '" . $this->db->escape($this->town) ."'"; - $sql .= ", fk_pays = " . $this->country_id; - $sql .= " WHERE rowid = " . $id; + $sql .= " SET ref = '".$this->db->escape($this->libelle)."'"; + $sql .= ", fk_parent = ".(($this->fk_parent > 0) ? $this->fk_parent : "NULL"); + $sql .= ", description = '".$this->db->escape($this->description)."'"; + $sql .= ", statut = ".$this->statut; + $sql .= ", lieu = '".$this->db->escape($this->lieu)."'"; + $sql .= ", address = '".$this->db->escape($this->address)."'"; + $sql .= ", zip = '".$this->db->escape($this->zip)."'"; + $sql .= ", town = '".$this->db->escape($this->town)."'"; + $sql .= ", fk_pays = ".$this->country_id; + $sql .= " WHERE rowid = ".$id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); - if (! $resql) { + if (!$resql) { $error++; - $this->errors[]="Error ".$this->db->lasterror(); + $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - $result=$this->insertExtraFields(); + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) { + $result = $this->insertExtraFields(); if ($result < 0) { $error++; @@ -318,7 +318,7 @@ class Entrepot extends CommonObject return 1; } else { $this->db->rollback(); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -341,24 +341,24 @@ class Entrepot extends CommonObject $this->db->begin(); - if (! $error && empty($notrigger)) + if (!$error && empty($notrigger)) { // Call trigger - $result=$this->call_trigger('WAREHOUSE_DELETE', $user); + $result = $this->call_trigger('WAREHOUSE_DELETE', $user); if ($result < 0) { $error++; } // End call triggers } - $elements = array('stock_mouvement','product_stock','product_warehouse_properties'); - foreach($elements as $table) + $elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties'); + foreach ($elements as $table) { - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE fk_entrepot = " . $this->id; + $sql .= " WHERE fk_entrepot = ".$this->id; - $result=$this->db->query($sql); - if (! $result) + $result = $this->db->query($sql); + if (!$result) { $error++; $this->errors[] = $this->db->lasterror(); @@ -367,11 +367,11 @@ class Entrepot extends CommonObject } // Removed extrafields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -380,12 +380,12 @@ class Entrepot extends CommonObject } } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot"; - $sql.= " WHERE rowid = " . $this->id; - $resql1=$this->db->query($sql); - if (! $resql1) + $sql .= " WHERE rowid = ".$this->id; + $resql1 = $this->db->query($sql); + if (!$resql1) { $error++; $this->errors[] = $this->db->lasterror(); @@ -393,12 +393,12 @@ class Entrepot extends CommonObject } } - if (! $error) + if (!$error) { // Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; - $resql2=$this->db->query($sql); - if (! $resql2) + $resql2 = $this->db->query($sql); + if (!$resql2) { $error++; $this->errors[] = $this->db->lasterror(); @@ -406,7 +406,7 @@ class Entrepot extends CommonObject } } - if (! $error) + if (!$error) { $this->db->commit(); return 1; @@ -433,9 +433,9 @@ class Entrepot extends CommonObject dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref); // Check parameters - if (! $id && ! $ref) + if (!$id && !$ref) { - $this->error='ErrorWrongParameters'; + $this->error = 'ErrorWrongParameters'; dol_syslog(get_class($this)."::fetch ".$this->error); return -1; } @@ -444,12 +444,12 @@ class Entrepot extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."entrepot"; if ($id) { - $sql.= " WHERE rowid = '".$id."'"; + $sql .= " WHERE rowid = '".$id."'"; } else { - $sql.= " WHERE entity = " .$conf->entity; - if ($ref) $sql.= " AND ref = '".$this->db->escape($ref)."'"; + $sql .= " WHERE entity = ".$conf->entity; + if ($ref) $sql .= " AND ref = '".$this->db->escape($ref)."'"; } $result = $this->db->query($sql); @@ -457,13 +457,13 @@ class Entrepot extends CommonObject { if ($this->db->num_rows($result) > 0) { - $obj=$this->db->fetch_object($result); + $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; $this->fk_parent = $obj->fk_parent; $this->ref = $obj->label; $this->label = $obj->label; - $this->libelle = $obj->label; // deprecated + $this->libelle = $obj->label; // deprecated $this->description = $obj->description; $this->statut = $obj->statut; $this->lieu = $obj->lieu; @@ -477,21 +477,21 @@ class Entrepot extends CommonObject $this->fetch_optionals(); include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $tmp=getCountry($this->country_id, 'all'); - $this->country=$tmp['label']; - $this->country_code=$tmp['code']; + $tmp = getCountry($this->country_id, 'all'); + $this->country = $tmp['label']; + $this->country_code = $tmp['code']; return 1; } else { - $this->error="Record Not Found"; + $this->error = "Record Not Found"; return 0; } } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -506,11 +506,11 @@ class Entrepot extends CommonObject public function info($id) { $sql = "SELECT e.rowid, e.datec, e.tms as datem, e.fk_user_author"; - $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; - $sql.= " WHERE e.rowid = ".$id; + $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e"; + $sql .= " WHERE e.rowid = ".$id; dol_syslog(get_class($this)."::info", LOG_DEBUG); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) @@ -522,7 +522,7 @@ class Entrepot extends CommonObject if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_valid) { @@ -557,14 +557,14 @@ class Entrepot extends CommonObject $liste = array(); $sql = "SELECT rowid, ref as label"; - $sql.= " FROM ".MAIN_DB_PREFIX."entrepot"; - $sql.= " WHERE entity IN (".getEntity('stock').")"; - $sql.= " AND statut = ".$status; + $sql .= " FROM ".MAIN_DB_PREFIX."entrepot"; + $sql .= " WHERE entity IN (".getEntity('stock').")"; + $sql .= " AND statut = ".$status; $result = $this->db->query($sql); $i = 0; $num = $this->db->num_rows($result); - if ( $result ) + if ($result) { while ($i < $num) { @@ -586,25 +586,25 @@ class Entrepot extends CommonObject public function nb_different_products() { // phpcs:enable - $ret=array(); + $ret = array(); $sql = "SELECT count(distinct p.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= ", ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE ps.fk_entrepot = ".$this->id; - $sql.= " AND ps.fk_product = p.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; + $sql .= " WHERE ps.fk_entrepot = ".$this->id; + $sql .= " AND ps.fk_product = p.rowid"; //print $sql; $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $ret['nb']=$obj->nb; + $ret['nb'] = $obj->nb; $this->db->free($result); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } @@ -620,26 +620,26 @@ class Entrepot extends CommonObject public function nb_products() { // phpcs:enable - $ret=array(); + $ret = array(); $sql = "SELECT sum(ps.reel) as nb, sum(ps.reel * p.pmp) as value"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; - $sql.= ", ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE ps.fk_entrepot = ".$this->id; - $sql.= " AND ps.fk_product = p.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; + $sql .= ", ".MAIN_DB_PREFIX."product as p"; + $sql .= " WHERE ps.fk_entrepot = ".$this->id; + $sql .= " AND ps.fk_product = p.rowid"; //print $sql; $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $ret['nb']=$obj->nb; - $ret['value']=$obj->value; + $ret['nb'] = $obj->nb; + $ret['value'] = $obj->value; $this->db->free($result); } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } @@ -695,40 +695,40 @@ class Entrepot extends CommonObject global $conf, $langs; $langs->load("stocks"); - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $result=''; + $result = ''; - $label = '' . $langs->trans("ShowWarehouse").''; - $label.= '
' . $langs->trans('Ref') . ': ' . (empty($this->ref)?(empty($this->label)?$this->libelle:$this->label):$this->ref); - if (! empty($this->lieu)) { - $label.= '
' . $langs->trans('LocationSummary').': '.$this->lieu; + $label = ''.$langs->trans("ShowWarehouse").''; + $label .= '
'.$langs->trans('Ref').': '.(empty($this->ref) ? (empty($this->label) ? $this->libelle : $this->label) : $this->ref); + if (!empty($this->lieu)) { + $label .= '
'.$langs->trans('LocationSummary').': '.$this->lieu; } if (isset($this->statut)) { - $label.= '
' . $langs->trans("Status").": ".$this->getLibStatut(5); + $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); } $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id; - $linkclose=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowWarehouse"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowWarehouse"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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.= ($showfullpath ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label)); + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= ($showfullpath ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label)); $result .= $linkend; return $result; @@ -743,23 +743,23 @@ class Entrepot extends CommonObject */ public function initAsSpecimen() { - global $user,$langs,$conf,$mysoc; + global $user, $langs, $conf, $mysoc; - $now=dol_now(); + $now = dol_now(); // Initialize parameters - $this->id=0; + $this->id = 0; $this->libelle = 'WAREHOUSE SPECIMEN'; $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now, 'dayhourlog'); - $this->statut=1; - $this->specimen=1; + $this->statut = 1; + $this->specimen = 1; - $this->lieu='Location test'; - $this->address='21 jump street'; - $this->zip='99999'; - $this->town='MyTown'; - $this->country_id=1; - $this->country_code='FR'; + $this->lieu = 'Location test'; + $this->address = '21 jump street'; + $this->zip = '99999'; + $this->town = 'MyTown'; + $this->country_id = 1; + $this->country_code = 'FR'; } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -771,16 +771,16 @@ class Entrepot extends CommonObject public function get_full_arbo() { // phpcs:enable - global $user,$langs,$conf; + global $user, $langs, $conf; - $TArbo = array(empty($this->label)?$this->libelle:$this->label); + $TArbo = array(empty($this->label) ? $this->libelle : $this->label); - $protection=100; // We limit depth of warehouses to 100 + $protection = 100; // We limit depth of warehouses to 100 $warehousetmp = new Entrepot($this->db); - $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents - $i=0; + $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents + $i = 0; while ($parentid > 0 && $i < $protection) { $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid; @@ -821,8 +821,8 @@ class Entrepot extends CommonObject WHERE fk_parent = '.$id; $resql = $this->db->query($sql); - if($resql) { - while($res = $this->db->fetch_object($resql)) { + if ($resql) { + while ($res = $this->db->fetch_object($resql)) { $TChildWarehouses[] = $res->rowid; $this->get_children_warehouses($res->rowid, $TChildWarehouses); } @@ -843,16 +843,16 @@ class Entrepot extends CommonObject */ public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { - global $conf,$user,$langs; + global $conf, $user, $langs; $langs->load("stocks"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'standard'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->STOCK_ADDON_PDF)) { + } elseif (!empty($conf->global->STOCK_ADDON_PDF)) { $modele = $conf->global->STOCK_ADDON_PDF; } } @@ -877,12 +877,12 @@ class Entrepot extends CommonObject $type_categ = Categorie::TYPE_WAREHOUSE; // Handle single category - if (! is_array($categories)) { + if (!is_array($categories)) { $categories = array($categories); } // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $c = new Categorie($this->db); $existing = $c->containing($this->id, $type_categ, 'id'); @@ -896,7 +896,7 @@ class Entrepot extends CommonObject } // Process - foreach($to_del as $del) { + foreach ($to_del as $del) { if ($c->fetch($del) > 0) { $c->del_type($this, $type_categ); } diff --git a/htdocs/product/stock/class/mouvementstock.class.php b/htdocs/product/stock/class/mouvementstock.class.php index 9e8dcc3184e..9364dd21fca 100644 --- a/htdocs/product/stock/class/mouvementstock.class.php +++ b/htdocs/product/stock/class/mouvementstock.class.php @@ -90,7 +90,8 @@ class MouvementStock extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** - * Add a movement of stock (in one direction only) + * Add a movement of stock (in one direction only). + * $this->origin can be also be set to save the source object of movement. * * @param User $user User object * @param int $fk_product Id of product @@ -123,19 +124,19 @@ class MouvementStock extends CommonObject dol_syslog(get_class($this)."::_create start userid=$user->id, fk_product=$fk_product, warehouse_id=$entrepot_id, qty=$qty, type=$type, price=$price, label=$label, inventorycode=$inventorycode, datem=".$datem.", eatby=".$eatby.", sellby=".$sellby.", batch=".$batch.", skip_batch=".$skip_batch); // Clean parameters - if (empty($price)) $price=0; - $now=(! empty($datem) ? $datem : dol_now()); + if (empty($price)) $price = 0; + $now = (!empty($datem) ? $datem : dol_now()); // Check parameters if (empty($fk_product)) return 0; if ($eatby < 0) { - $this->errors[]='ErrorBadValueForParameterEatBy'; + $this->errors[] = 'ErrorBadValueForParameterEatBy'; return -1; } if ($sellby < 0) { - $this->errors[]='ErrorBadValueForParameterSellBy'; + $this->errors[] = 'ErrorBadValueForParameterSellBy'; return -1; } @@ -154,7 +155,7 @@ class MouvementStock extends CommonObject $mvid = 0; $product = new Product($this->db); - $result=$product->fetch($fk_product); + $result = $product->fetch($fk_product); if ($result < 0) { $this->error = $product->error; @@ -168,11 +169,11 @@ class MouvementStock extends CommonObject $product->load_stock('novirtual'); // Test if product require batch data. If yes, and there is not, we throw an error. - if (! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) + if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) { if (empty($batch)) { - $this->errors[]=$langs->transnoentitiesnoconv("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref); + $this->errors[] = $langs->transnoentitiesnoconv("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref); dol_syslog("Try to make a movement of a product with status_batch on without any batch data"); $this->db->rollback(); @@ -186,13 +187,13 @@ class MouvementStock extends CommonObject // If found and eatby/sellby not defined into table and not provided, we do nothing // If not found, we add record $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".MAIN_DB_PREFIX."product_lot as pb"; - $sql.= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'"; + $sql .= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'"; dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); - $i=0; + $i = 0; if ($num > 0) { while ($i < $num) @@ -202,8 +203,8 @@ class MouvementStock extends CommonObject { if ($eatby) { - $tmparray=dol_getdate($eatby, true); - $eatbywithouthour=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); + $tmparray = dol_getdate($eatby, true); + $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility { // If found and eatby/sellby defined into table and provided and differs, return error @@ -240,12 +241,12 @@ class MouvementStock extends CommonObject { if ($sellby) { - $tmparray=dol_getdate($sellby, true); - $sellbywithouthour=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); + $tmparray = dol_getdate($sellby, true); + $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) // We test date without hours and with hours for backward compatibility { // If found and eatby/sellby defined into table and provided and differs, return error - $this->errors[]=$langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)); + $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)); dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR); $this->db->rollback(); return -3; @@ -305,25 +306,25 @@ class MouvementStock extends CommonObject } // Define if we must make the stock change (If product type is a service or if stock is used also for services) - $movestock=0; - if ($product->type != Product::TYPE_SERVICE || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock=1; + $movestock = 0; + if ($product->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock = 1; // Check if stock is enough when qty is < 0 // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2. if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) { - if (! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) + if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) { - $foundforbatch=0; - $qtyisnotenough=0; - foreach($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) + $foundforbatch = 0; + $qtyisnotenough = 0; + foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) { if ($batch != $batchcursor) continue; - $foundforbatch=1; + $foundforbatch = 1; if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty; break; } - if (! $foundforbatch || $qtyisnotenough) + if (!$foundforbatch || $qtyisnotenough) { $langs->load("stocks"); include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; @@ -352,7 +353,7 @@ class MouvementStock extends CommonObject if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after { $fk_project = 0; - if(!empty($this->origin)) { // This is set by caller for tracking reason + if (!empty($this->origin)) { // This is set by caller for tracking reason $origintype = $this->origin->element; $fk_origin = $this->origin->id; if ($origintype == 'project') $fk_project = $fk_origin; @@ -374,22 +375,22 @@ class MouvementStock extends CommonObject } $sql = "INSERT INTO ".MAIN_DB_PREFIX."stock_mouvement("; - $sql.= " datem, fk_product, batch, eatby, sellby,"; - $sql.= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet"; - $sql.= ")"; - $sql.= " VALUES ('".$this->db->idate($now)."', ".$this->product_id.", "; - $sql.= " ".($batch?"'".$batch."'":"null").", "; - $sql.= " ".($eatby?"'".$this->db->idate($eatby)."'":"null").", "; - $sql.= " ".($sellby?"'".$this->db->idate($sellby)."'":"null").", "; - $sql.= " ".$this->entrepot_id.", ".$this->qty.", ".$this->type.","; - $sql.= " ".$user->id.","; - $sql.= " '".$this->db->escape($label)."',"; - $sql.= " ".($inventorycode?"'".$this->db->escape($inventorycode)."'":"null").","; - $sql.= " '".price2num($price)."',"; - $sql.= " '".$fk_origin."',"; - $sql.= " '".$origintype."',"; - $sql.= " ". $fk_project; - $sql.= ")"; + $sql .= " datem, fk_product, batch, eatby, sellby,"; + $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet"; + $sql .= ")"; + $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->product_id.", "; + $sql .= " ".($batch ? "'".$batch."'" : "null").", "; + $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", "; + $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", "; + $sql .= " ".$this->entrepot_id.", ".$this->qty.", ".$this->type.","; + $sql .= " ".$user->id.","; + $sql .= " '".$this->db->escape($label)."',"; + $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").","; + $sql .= " '".price2num($price)."',"; + $sql .= " '".$fk_origin."',"; + $sql .= " '".$origintype."',"; + $sql .= " ".$fk_project; + $sql .= ")"; dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG); $resql = $this->db->query($sql); @@ -407,19 +408,19 @@ class MouvementStock extends CommonObject } // Define current values for qty and pmp - $oldqty=$product->stock_reel; - $oldpmp=$product->pmp; - $oldqtywarehouse=0; + $oldqty = $product->stock_reel; + $oldpmp = $product->pmp; + $oldqtywarehouse = 0; // Test if there is already a record for couple (warehouse / product) $alreadyarecord = 0; - if (! $error) + if (!$error) { $sql = "SELECT rowid, reel FROM ".MAIN_DB_PREFIX."product_stock"; - $sql.= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; // This is a unique key + $sql .= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; // This is a unique key dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); @@ -433,25 +434,25 @@ class MouvementStock extends CommonObject } else { - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error = -2; } } // Calculate new PMP. - $newpmp=0; - if (! $error) + $newpmp = 0; + if (!$error) { // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0. // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input) if (($type == 0 || $type == 3) && $price > 0) { - $oldqtytouse=($oldqty >= 0?$oldqty:0); + $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0); // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined - if ($oldpmp > 0) $newpmp=price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU'); + if ($oldpmp > 0) $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU'); else { - $newpmp=$price; // For this product, PMP was not yet set. We set it to input price. + $newpmp = $price; // For this product, PMP was not yet set. We set it to input price. } //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." "; //print "qty=".$qty." newpmp=".$newpmp; @@ -468,25 +469,25 @@ class MouvementStock extends CommonObject } } // Update stock quantity - if (! $error) + if (!$error) { if ($alreadyarecord > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."product_stock SET reel = reel + ".$qty; - $sql.= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; + $sql .= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_stock"; - $sql.= " (reel, fk_entrepot, fk_product) VALUES "; - $sql.= " (".$qty.", ".$entrepot_id.", ".$fk_product.")"; + $sql .= " (reel, fk_entrepot, fk_product) VALUES "; + $sql .= " (".$qty.", ".$entrepot_id.", ".$fk_product.")"; } dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error = -3; } elseif (empty($fk_product_stock)) @@ -496,61 +497,61 @@ class MouvementStock extends CommonObject } // Update detail stock for batch product - if (! $error && ! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) + if (!$error && !empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) { if ($id_product_batch > 0) { - $result=$this->createBatch($id_product_batch, $qty); + $result = $this->createBatch($id_product_batch, $qty); } else { - $param_batch=array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); - $result=$this->createBatch($param_batch, $qty); + $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); + $result = $this->createBatch($param_batch, $qty); } - if ($result<0) $error++; + if ($result < 0) $error++; } // Update PMP and denormalized value of stock qty at product level - if (! $error) + if (!$error) { // $sql = "UPDATE ".MAIN_DB_PREFIX."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty; // $sql.= " WHERE rowid = ".$fk_product; // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.", "; - $sql.= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; - $sql.= " WHERE rowid = ".$fk_product; + $sql .= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; + $sql .= " WHERE rowid = ".$fk_product; dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { - $this->errors[]=$this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $error = -4; } } // If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot. - $sql="DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)"; - $resql=$this->db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)"; + $resql = $this->db->query($sql); // We do not test error, it can fails if there is child in batch details } // Add movement for sub products (recursive call) - if (! $error && ! empty($conf->global->PRODUIT_SOUSPRODUITS) && empty($conf->global->INDEPENDANT_SUBPRODUCT_STOCK)) + if (!$error && !empty($conf->global->PRODUIT_SOUSPRODUITS) && empty($conf->global->INDEPENDANT_SUBPRODUCT_STOCK)) { - $error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode); // we use 0 as price, because pmp is not changed for subproduct + $error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode); // we use 0 as price, because pmp is not changed for subproduct } - if ($movestock && ! $error) + if ($movestock && !$error) { // Call trigger - $result=$this->call_trigger('STOCK_MOVEMENT', $user); + $result = $this->call_trigger('STOCK_MOVEMENT', $user); if ($result < 0) $error++; // End call triggers } - if (! $error) + if (!$error) { $this->db->commit(); return $mvid; @@ -594,12 +595,12 @@ class MouvementStock extends CommonObject $sql .= " t.eatby,"; $sql .= " t.sellby,"; $sql .= " t.fk_projet as fk_project"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; - $sql.= ' WHERE 1 = 1'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql .= ' WHERE 1 = 1'; //if (null !== $ref) { //$sql .= ' AND t.ref = ' . '\'' . $ref . '\''; //} else { - $sql .= ' AND t.rowid = ' . $id; + $sql .= ' AND t.rowid = '.$id; //} $resql = $this->db->query($sql); @@ -643,10 +644,10 @@ class MouvementStock extends CommonObject return 0; } } else { - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR); + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR); - return - 1; + return -1; } } @@ -675,19 +676,19 @@ class MouvementStock extends CommonObject $pqtys = array(); $sql = "SELECT fk_product_pere, fk_product_fils, qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."product_association"; - $sql.= " WHERE fk_product_pere = ".$idProduct; - $sql.= " AND incdec = 1"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_association"; + $sql .= " WHERE fk_product_pere = ".$idProduct; + $sql .= " AND incdec = 1"; dol_syslog(get_class($this)."::_createSubProduct for parent product ".$idProduct, LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $i=0; - while ($obj=$this->db->fetch_object($resql)) + $i = 0; + while ($obj = $this->db->fetch_object($resql)) { - $pids[$i]=$obj->fk_product_fils; - $pqtys[$i]=$obj->qty; + $pids[$i] = $obj->fk_product_fils; + $pqtys[$i] = $obj->qty; $i++; } $this->db->free($resql); @@ -698,12 +699,12 @@ class MouvementStock extends CommonObject } // Create movement for each subproduct - foreach($pids as $key => $value) + foreach ($pids as $key => $value) { - if (! $error) + if (!$error) { $tmpmove = clone $this; - $result = $tmpmove->_create($user, $pids[$key], $entrepot_id, ($qty * $pqtys[$key]), $type, 0, $label, $inventorycode); // This will also call _createSubProduct making this recursive + $result = $tmpmove->_create($user, $pids[$key], $entrepot_id, ($qty * $pqtys[$key]), $type, 0, $label, $inventorycode); // This will also call _createSubProduct making this recursive if ($result < 0) { $this->error = $tmpmove->error; @@ -739,7 +740,7 @@ class MouvementStock extends CommonObject * @param string $inventorycode Inventory code * @return int <0 if KO, >0 if OK */ - public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode='') + public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '') { global $conf; @@ -765,7 +766,7 @@ class MouvementStock extends CommonObject * @param string $inventorycode Inventory code * @return int <0 if KO, >0 if OK */ - public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode='') + public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '') { global $conf; @@ -806,19 +807,19 @@ class MouvementStock extends CommonObject */ public function calculateBalanceForProductBefore($productidselected, $datebefore) { - $nb=0; + $nb = 0; $sql = 'SELECT SUM(value) as nb from '.MAIN_DB_PREFIX.'stock_mouvement'; - $sql.= ' WHERE fk_product = '.$productidselected; - $sql.= " AND datem < '".$this->db->idate($datebefore)."'"; + $sql .= ' WHERE fk_product = '.$productidselected; + $sql .= " AND datem < '".$this->db->idate($datebefore)."'"; dol_syslog(get_class($this).__METHOD__.'', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $obj=$this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); if ($obj) $nb = $obj->nb; - return (empty($nb)?0:$nb); + return (empty($nb) ? 0 : $nb); } else { @@ -840,14 +841,14 @@ class MouvementStock extends CommonObject { global $user; - $pdluo=new Productbatch($this->db); + $pdluo = new Productbatch($this->db); - $result=0; + $result = 0; // Try to find an existing record with same batch number or id if (is_numeric($dluo)) { - $result=$pdluo->fetch($dluo); + $result = $pdluo->fetch($dluo); if (empty($pdluo->id)) { // We didn't find the line. May be it was deleted before by a previous move in same transaction. @@ -860,10 +861,10 @@ class MouvementStock extends CommonObject { if (isset($dluo['fk_product_stock'])) { - $vfk_product_stock=$dluo['fk_product_stock']; + $vfk_product_stock = $dluo['fk_product_stock']; $vbatchnumber = $dluo['batchnumber']; - $result = $pdluo->find($vfk_product_stock, '', '', $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here) + $result = $pdluo->find($vfk_product_stock, '', '', $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here) } else { @@ -886,24 +887,24 @@ class MouvementStock extends CommonObject $pdluo->qty += $qty; if ($pdluo->qty == 0) { - $result=$pdluo->delete($user, 1); + $result = $pdluo->delete($user, 1); } else { - $result=$pdluo->update($user, 1); + $result = $pdluo->update($user, 1); } } else // product_batch record not found { - $pdluo->fk_product_stock=$vfk_product_stock; + $pdluo->fk_product_stock = $vfk_product_stock; $pdluo->qty = $qty; $pdluo->eatby = $veatby; $pdluo->sellby = $vsellby; $pdluo->batch = $vbatchnumber; - $result=$pdluo->create($user, 1); + $result = $pdluo->create($user, 1); if ($result < 0) { - $this->error=$pdluo->error; - $this->errors=$pdluo->errors; + $this->error = $pdluo->error; + $this->errors = $pdluo->errors; } } } @@ -922,7 +923,7 @@ class MouvementStock extends CommonObject public function get_origin($fk_origin, $origintype) { // phpcs:enable - $origin=''; + $origin = ''; switch ($origintype) { case 'commande': @@ -957,7 +958,7 @@ class MouvementStock extends CommonObject default: if ($origintype) { - $result=dol_include_once('/'.$origintype.'/class/'.$origintype.'.class.php'); + $result = dol_include_once('/'.$origintype.'/class/'.$origintype.'.class.php'); if ($result) { $classname = ucfirst($origintype); @@ -967,7 +968,7 @@ class MouvementStock extends CommonObject break; } - if (empty($origin) || ! is_object($origin)) return ''; + if (empty($origin) || !is_object($origin)) return ''; if ($origin->fetch($fk_origin) > 0) { return $origin->getNomUrl(1); @@ -988,7 +989,7 @@ class MouvementStock extends CommonObject { if (!empty($origin_element) && $origin_id > 0) { - $origin=''; + $origin = ''; if ($origin_element == 'project') { if (!class_exists('Project')) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; @@ -1013,10 +1014,10 @@ class MouvementStock extends CommonObject */ public function initAsSpecimen() { - global $user,$langs,$conf,$mysoc; + global $user, $langs, $conf, $mysoc; // Initialize parameters - $this->id=0; + $this->id = 0; // There is no specific properties. All data into insert are provided as method parameter. } @@ -1039,23 +1040,23 @@ class MouvementStock extends CommonObject $result = ''; $companylink = ''; - $label = '' . $langs->trans("Movement") . ' '.$this->id.''; - $label.= '
'; - $label.= '' . $langs->trans('Label') . ': ' . $this->label; - $label.= '
' . $langs->trans('Qty') . ': ' .$this->qty; - $label.= '
'; + $label = ''.$langs->trans("Movement").' '.$this->id.''; + $label .= '
'; + $label .= ''.$langs->trans('Label').': '.$this->label; + $label .= '
'.$langs->trans('Qty').': '.$this->qty; + $label .= '
'; $link = 'id . $linkend; + $result .= $link.$this->id.$linkend; return $result; } @@ -1116,16 +1117,16 @@ class MouvementStock extends CommonObject */ public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { - global $conf,$user,$langs; + global $conf, $user, $langs; $langs->load("stocks"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'stdmovement'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->MOUVEMENT_ADDON_PDF)) { + } elseif (!empty($conf->global->MOUVEMENT_ADDON_PDF)) { $modele = $conf->global->MOUVEMENT_ADDON_PDF; } } diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index 5929a46edb8..af12804aac5 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -1018,7 +1018,8 @@ if (!$variants) { } } else { // List of variants - + include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; + include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php'; $prodstatic = new Product($db); $prodcomb = new ProductCombination($db); $comb2val = new ProductCombination2ValuePair($db); diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 527afee2607..4b36fda5ccb 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -200,52 +200,52 @@ jQuery(document).ready(function() { $sql = "SELECT"; -$sql.= " t.rowid,"; -$sql.= " t.entity,"; -$sql.= " t.fk_product,"; -$sql.= " t.batch,"; -$sql.= " t.sellby,"; -$sql.= " t.eatby,"; -$sql.= " t.datec as date_creation,"; -$sql.= " t.tms as date_update,"; -$sql.= " t.fk_user_creat,"; -$sql.= " t.fk_user_modif,"; -$sql.= " t.import_key,"; -$sql.= " p.fk_product_type as product_type,"; -$sql.= " p.ref as product_ref,"; -$sql.= " p.label as product_label,"; -$sql.= " p.tosell,"; -$sql.= " p.tobuy,"; -$sql.= " p.tobatch"; +$sql .= " t.rowid,"; +$sql .= " t.entity,"; +$sql .= " t.fk_product,"; +$sql .= " t.batch,"; +$sql .= " t.sellby,"; +$sql .= " t.eatby,"; +$sql .= " t.datec as date_creation,"; +$sql .= " t.tms as date_update,"; +$sql .= " t.fk_user_creat,"; +$sql .= " t.fk_user_modif,"; +$sql .= " t.import_key,"; +$sql .= " p.fk_product_type as product_type,"; +$sql .= " p.ref as product_ref,"; +$sql .= " p.label as product_label,"; +$sql .= " p.tosell,"; +$sql .= " p.tobuy,"; +$sql .= " p.tobatch"; // Add fields for extrafields -if (! empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " FROM ".MAIN_DB_PREFIX."product_lot as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -$sql.= ", ".MAIN_DB_PREFIX."product as p"; -$sql.= " WHERE p.rowid = t.fk_product"; -$sql.= " AND p.entity IN (".getEntity('product').")"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " FROM ".MAIN_DB_PREFIX."product_lot as t"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +$sql .= ", ".MAIN_DB_PREFIX."product as p"; +$sql .= " WHERE p.rowid = t.fk_product"; +$sql .= " AND p.entity IN (".getEntity('product').")"; -if ($search_entity) $sql.= natural_search("entity", $search_entity); -if ($search_product) $sql.= natural_search("p.ref", $search_product); -if ($search_batch) $sql.= natural_search("batch", $search_batch); -if ($search_fk_user_creat) $sql.= natural_search("fk_user_creat", $search_fk_user_creat); -if ($search_fk_user_modif) $sql.= natural_search("fk_user_modif", $search_fk_user_modif); -if ($search_import_key) $sql.= natural_search("import_key", $search_import_key); +if ($search_entity) $sql .= natural_search("entity", $search_entity); +if ($search_product) $sql .= natural_search("p.ref", $search_product); +if ($search_batch) $sql .= natural_search("batch", $search_batch); +if ($search_fk_user_creat) $sql .= natural_search("fk_user_creat", $search_fk_user_creat); +if ($search_fk_user_modif) $sql .= natural_search("fk_user_modif", $search_fk_user_modif); +if ($search_import_key) $sql .= natural_search("import_key", $search_import_key); -if ($sall) $sql.= natural_search(array_keys($fieldstosearchall), $sall); +if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.=$db->order($sortfield, $sortorder); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= $db->order($sortfield, $sortorder); //$sql.= $db->plimit($conf->liste_limit+1, $offset); // Count total nb of records diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index 8215eec4258..2489104eb34 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -146,7 +146,9 @@ $search_array_options_task = $extrafields->getOptionalsFromPost($object->table_e /* * Actions */ - +$parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Purge criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { diff --git a/htdocs/projet/activity/permonth.php b/htdocs/projet/activity/permonth.php new file mode 100644 index 00000000000..d121b39b683 --- /dev/null +++ b/htdocs/projet/activity/permonth.php @@ -0,0 +1,655 @@ + + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2010 François Legastelois + * + * 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/projet/activity/permonth.php + * \ingroup projet + * \brief List activities of tasks (per week entry) + */ + +require "../../main.inc.php"; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('projects','users','companies')); +$hookmanager->initHooks(array('timesheetpermonthcard')); + +$action=GETPOST('action', 'aZ09'); +$mode=GETPOST("mode", 'alpha'); +$id=GETPOST('id', 'int'); +$taskid=GETPOST('taskid', 'int'); + +$mine=0; +if ($mode == 'mine') $mine=1; + +$projectid=''; +$projectid=isset($_GET["id"])?$_GET["id"]:$_POST["projectid"]; + +// Security check +$socid=0; +// For external user, no check is done on company because readability is managed by public status of project and assignement. +// if ($user->societe_id > 0) $socid=$user->societe_id; +$result = restrictedArea($user, 'projet', $projectid); + +$now=dol_now(); +$nowtmp=dol_getdate($now); +$nowday=$nowtmp['mday']; +$nowmonth=$nowtmp['mon']; +$nowyear=$nowtmp['year']; + +$year=GETPOST('reyear')?GETPOST('reyear', 'int'):(GETPOST("year")?GETPOST("year", "int"):date("Y")); +$month=GETPOST('remonth')?GETPOST('remonth', 'int'):(GETPOST("month")?GETPOST("month", "int"):date("m")); +$day=GETPOST('reday')?GETPOST('reday', 'int'):(GETPOST("day")?GETPOST("day", "int"):date("d")); +$day = (int) $day; +$week=GETPOST("week", "int")?GETPOST("week", "int"):date("W"); + +$search_categ=GETPOST("search_categ", 'alpha'); +$search_usertoprocessid=GETPOST('search_usertoprocessid', 'int'); +$search_task_ref=GETPOST('search_task_ref', 'alpha'); +$search_task_label=GETPOST('search_task_label', 'alpha'); +$search_project_ref=GETPOST('search_project_ref', 'alpha'); +$search_thirdparty=GETPOST('search_thirdparty', 'alpha'); +$search_declared_progress=GETPOST('search_declared_progress', 'alpha'); + +$startdayarray=dol_get_prev_month($month, $year); + +$prev = $startdayarray; +$prev_year = $prev['year']; +$prev_month = $prev['month']; +$prev_day = 1; + +$next = dol_get_next_month($month, $year); +$next_year = $next['year']; +$next_month = $next['month']; +$next_day = 1; +$TWeek = getWeekNumbersOfMonth($month, $year); +$firstdaytoshow = dol_mktime(0, 0, 0, $month, 1, $year); +$TFirstDays = getFirstDayOfEachWeek($TWeek, $year); +$TFirstDays[reset($TWeek)] = '01'; //first day of month +$TLastDays = getLastDayOfEachWeek($TWeek, $year); +$TLastDays[end($TWeek)] = date("t", strtotime($year.'-'.$month.'-'.$day)); //last day of month +if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) +{ + $usertoprocess=$user; + $search_usertoprocessid=$usertoprocess->id; +} +elseif ($search_usertoprocessid > 0) +{ + $usertoprocess=new User($db); + $usertoprocess->fetch($search_usertoprocessid); + $search_usertoprocessid=$usertoprocess->id; +} +else +{ + $usertoprocess=new User($db); +} + +$object=new Task($db); + + +/* + * Actions + */ +$parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid, 'TWeek' => $TWeek, 'TFirstDays' => $TFirstDays, 'TLastDays' => $TLastDays); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +// Purge criteria +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers +{ + $action = ''; + $search_categ=''; + $search_usertoprocessid = $user->id; + $search_task_ref = ''; + $search_task_label = ''; + $search_project_ref = ''; + $search_thirdparty = ''; + $search_declared_progress = ''; +} +if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) +{ + $action = ''; +} + +if (GETPOST('submitdateselect')) +{ + $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + + $action = ''; +} +if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) +{ + $action = 'assigntask'; + + if ($taskid > 0) + { + $result = $object->fetch($taskid, $ref); + if ($result < 0) $error++; + } + else + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors'); + $error++; + } + if (! GETPOST('type')) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); + $error++; + } + + if (! $error) + { + $idfortaskuser=$usertoprocess->id; + $result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal'); + + if ($result >= 0 || $result == -2) // Contact add ok or already contact of task + { + // Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project) + $sql='SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact'; + $sql.=' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'"; + $resql=$db->query($sql); + if ($resql) + { + $obj=$db->fetch_object($resql); + if (! $obj) // User is not already linked to project, so we will create link to first type + { + $project = new Project($db); + $project->fetch($object->fk_project); + // Get type + $listofprojcontact=$project->liste_type_contact('internal'); + + if (count($listofprojcontact)) + { + $typeforprojectcontact=reset(array_keys($listofprojcontact)); + $result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal'); + } + } + } + else + { + dol_print_error($db); + } + } + } + + if ($result < 0) + { + $error++; + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings'); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + + if (! $error) + { + setEventMessages("TaskAssignedToEnterTime", null); + $taskid=0; + } + + $action=''; +} + +if ($action == 'addtime' && $user->rights->projet->lire) +{ + $timetoadd=$_POST['task']; + if (empty($timetoadd)) + { + setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors'); + } + else + { + foreach($timetoadd as $taskid => $value) // Loop on each task + { + $updateoftaskdone=0; + foreach($value as $key => $val) // Loop on each day + { + $amountoadd=$timetoadd[$taskid][$key]; + if (! empty($amountoadd)) + { + $tmpduration=explode(':', $amountoadd); + $newduration=0; + if (! empty($tmpduration[0])) $newduration+=($tmpduration[0] * 3600); + if (! empty($tmpduration[1])) $newduration+=($tmpduration[1] * 60); + if (! empty($tmpduration[2])) $newduration+=($tmpduration[2]); + + if ($newduration > 0) + { + $object->fetch($taskid); + $object->progress = GETPOST($taskid . 'progress', 'int'); + $object->timespent_duration = $newduration; + $object->timespent_fk_user = $usertoprocess->id; + $object->timespent_date = dol_time_plus_duree($firstdaytoshow, $key, 'd'); + $object->timespent_datehour = $object->timespent_date; + + $result=$object->addTimeSpent($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + break; + } + + $updateoftaskdone++; + } + } + } + + if (! $updateoftaskdone) // Check to update progress if no update were done on task. + { + $object->fetch($taskid); + //var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit; + if ($object->progress != GETPOST($taskid . 'progress', 'int')) + { + $object->progress = GETPOST($taskid . 'progress', 'int'); + $result=$object->update($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + break; + } + } + } + } + + if (! $error) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + + $param=''; + $param.=($mode?'&mode='.$mode:''); + $param.=($projectid?'id='.$projectid:''); + $param.=($search_usertoprocessid?'&search_usertoprocessid='.$search_usertoprocessid:''); + $param.=($day?'&day='.$day:'').($month?'&month='.$month:'').($year?'&year='.$year:''); + $param.=($search_project_ref?'&search_project_ref='.$search_project_ref:''); + $param.=($search_usertoprocessid > 0?'&search_usertoprocessid='.$search_usertoprocessid:''); + $param.=($search_thirdparty?'&search_thirdparty='.$search_thirdparty:''); + $param.=($search_declared_progress?'&search_declared_progress='.$search_declared_progress:''); + $param.=($search_task_ref?'&search_task_ref='.$search_task_ref:''); + $param.=($search_task_label?'&search_task_label='.$search_task_label:''); + + // Redirect to avoid submit twice on back + header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); + exit; + } + } +} + + + +/* + * View + */ + +$form=new Form($db); +$formother=new FormOther($db); +$formcompany=new FormCompany($db); +$formproject=new FormProjets($db); +$projectstatic=new Project($db); +$project = new Project($db); +$taskstatic = new Task($db); +$thirdpartystatic = new Societe($db); +$holiday = new Holiday($db); + +$title=$langs->trans("TimeSpent"); + +$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id)?2:0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project +//var_dump($projectsListId); +if ($id) +{ + $project->fetch($id); + $project->fetch_thirdparty(); +} + +$onlyopenedproject=1; // or -1 +$morewherefilter=''; + +if ($search_project_ref) $morewherefilter.=natural_search(array("p.ref", "p.title"), $search_project_ref); +if ($search_task_ref) $morewherefilter.=natural_search("t.ref", $search_task_ref); +if ($search_task_label) $morewherefilter.=natural_search(array("t.ref", "t.label"), $search_task_label); +if ($search_thirdparty) $morewherefilter.=natural_search("s.nom", $search_thirdparty); +if ($search_declared_progress) $morewherefilter.=natural_search("t.progress", $search_declared_progress, 1); + +$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. +if ($morewherefilter) // Get all task without any filter, so we can show total of time spent for not visible tasks +{ + $tasksarraywithoutfilter=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid?$search_usertoprocessid:0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later. +} +$projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); +$tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); +//var_dump($tasksarray); +//var_dump($projectsrole); +//var_dump($taskrole); + + +llxHeader("", $title, "", '', '', '', array('/core/js/timesheet.js')); + +//print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'title_project'); + +$param=''; +$param.=($mode?'&mode='.$mode:''); +$param.=($search_project_ref?'&search_project_ref='.$search_project_ref:''); +$param.=($search_usertoprocessid > 0?'&search_usertoprocessid='.$search_usertoprocessid:''); +$param.=($search_thirdparty?'&search_thirdparty='.$search_thirdparty:''); +$param.=($search_task_ref?'&search_task_ref='.$search_task_ref:''); +$param.=($search_task_label?'&search_task_label='.$search_task_label:''); + +// Show navigation bar +$nav =''.img_previous($langs->trans("Previous"))."\n"; +$nav.=" ".dol_print_date(dol_mktime(0, 0, 0, $month, 1, $year), "%Y").", ".$langs->trans(date('F', mktime(0, 0, 0, $month, 10)))." \n"; +$nav.=''.img_next($langs->trans("Next"))."\n"; +$nav.="   (".$langs->trans("Today").")"; +$nav.='
'.$form->select_date(-1, '', 0, 0, 2, "addtime", 1, 0, 1).' '; +$nav.=' '; + +$picto='calendarweek'; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$head=project_timesheet_prepare_head($mode, $usertoprocess); +dol_fiche_head($head, 'inputpermonth', $langs->trans('TimeSpent'), -1, 'task'); + +// Show description of content +print '
'; +if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
'; +else +{ + if (empty($usertoprocess->id) || $usertoprocess->id < 0) + { + if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
'; + else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject?' '.$langs->trans("OnlyOpenedProject"):'').'
'; + } +} +if ($mine || ($usertoprocess->id == $user->id)) +{ + print $langs->trans("OnlyYourTaskAreVisible").'
'; +} +else +{ + print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'
'; +} +print '
'; + +dol_fiche_end(); + +print '
'.$nav.'
'; // We move this before the assign to components so, the default submit button is not the assign to. + +print '
'; +$titleassigntask = $langs->transnoentities("AssignTaskToMe"); +if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs)); +print '
'; +$formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1); +print '
'; +print ' '; +print $formcompany->selectTypeContact($object, '', 'type', 'internal', 'rowid', 0, 'maxwidth150onsmartphone'); +print ''; +print '
'; + +print '
'; + + +$moreforfilter=''; + +// Filter on categories +/* +if (! empty($conf->categorie->enabled)) +{ + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('ProjectCategories'). ': '; + $moreforfilter.=$formother->select_categories('project', $search_categ, 'search_categ', 1, 1, 'maxwidth300'); + $moreforfilter.='
'; +}*/ + +// If the user can view user other than himself +$moreforfilter.='
'; +$moreforfilter.='
'.$langs->trans('User'). '
'; +$includeonly='hierachyme'; +if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); +$moreforfilter.=$form->select_dolusers($search_usertoprocessid?$search_usertoprocessid:$usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire?0:0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200'); +$moreforfilter.='
'; + +if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) +{ + $moreforfilter.='
'; + $moreforfilter.='
'.$langs->trans('Project'). '
'; + $moreforfilter.=''; + $moreforfilter.='
'; + + $moreforfilter.='
'; + $moreforfilter.='
'.$langs->trans('ThirdParty'). '
'; + $moreforfilter.=''; + $moreforfilter.='
'; +} + +if (! empty($moreforfilter)) +{ + print '
'; + print $moreforfilter; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '
'; +} + +print '
'; + +print ''."\n"; + +print ''; +if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +$countWeek = count($TWeek); +for ($idw=0;$idw<$countWeek;$idw++) +{ + print ''; +} +// Action column +print ''; +print "\n"; + +print ''; +if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print ''; +print ''; +print ''; +print ''; +/*print ''; + if ($usertoprocess->id == $user->id) print ''; + else print '';*/ +print ''; +print ''; + +foreach ($TWeek as $week_number) +{ + print ''; +} +print ''; +print "\n"; + +$colspan=5; + +// By default, we can edit only tasks we are assigned to +$restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)?1:0); + +if (count($tasksarray) > 0) +{ + //var_dump($tasksarray); // contains only selected tasks + //var_dump($tasksarraywithoutfilter); // contains all tasks (if there is a filter, not defined if no filter) + //var_dump($tasksrole); + + $j=0; + $level=0; + $totalforvisibletasks = projectLinesPerMonth($j, $firstdaytoshow, $usertoprocess, 0, $tasksarray, $level, $projectsrole, $tasksrole, $mine, $restrictviewformytask, $isavailable, 0, $TWeek); + //var_dump($totalforvisibletasks); + + // Show total for all other tasks + + // Calculate total for all tasks + $listofdistinctprojectid=array(); // List of all distinct projects + if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) + { + foreach($tasksarraywithoutfilter as $tmptask) + { + $listofdistinctprojectid[$tmptask->fk_project]=$tmptask->fk_project; + } + } + //var_dump($listofdistinctprojectid); + $totalforeachweek=array(); + foreach($listofdistinctprojectid as $tmpprojectid) + { + $projectstatic->id=$tmpprojectid; + $projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + foreach($TWeek as $weekNb) + { + $totalforeachweek[$weekNb]+=$projectstatic->monthWorkLoad[$weekNb]; + } + } + + //var_dump($totalforeachday); + //var_dump($totalforvisibletasks); + + // Is there a diff between selected/filtered tasks and all tasks ? + $isdiff = 0; + if (count($totalforeachweek)) + { + foreach($TWeek as $weekNb) + { + $timeonothertasks=($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]); + if ($timeonothertasks) + { + $isdiff=1; + break; + } + } + } + + // There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user + if ($isdiff) + { + print ''; + print ''; + foreach ($TWeek as $weekNb) + { + print ''; + } + print ' '; + print ''; + } + + if ($conf->use_javascript_ajax) + { + print ' + '; + + foreach ($TWeek as $weekNb) + { + print ''; + } + print ' + '; + } +} +else +{ + print ''; +} +print "
'; +$searchpicto=$form->showFilterAndCheckAddButtons(0); +print $searchpicto; +print '
'.$langs->trans("Project").''.$langs->trans("ThirdParty").''.$langs->trans("Task").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpent").''.$langs->trans("TimeSpentByYou").''.$langs->trans("TimeSpentByUser").''.$langs->trans("TimeSpent").'
('.$langs->trans("Everybody").')
'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '
('.dol_trunc($usertoprocess->firstname, 10).')' : '').'
'.$langs->trans("Week").' '.$week_number.'
('.$TFirstDays[$week_number].'...'.$TLastDays[$week_number].')
'; + print $langs->trans("OtherFilteredTasks"); + print ''; + + $timeonothertasks=($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]); + if ($timeonothertasks) + { + print ''; + } + print '
'; + print $langs->trans("Total"); + print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; + print '
'. convertSecondToTime($totalforvisibletasks[$weekNb], 'allhourmin').'
 
'.$langs->trans("NoAssignedTasks").'
"; +print '
'; + +print ''."\n"; + +print '
'; +print ''; +print '
'; + +print ''."\n\n"; + +$modeinput='hours'; + +if ($conf->use_javascript_ajax) +{ + print "\n\n"; + print ''; +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index 4488342ab73..563b7ca19c9 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -36,58 +36,58 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; // Load translation files required by the page -$langs->loadLangs(array('projects','users','companies')); +$langs->loadLangs(array('projects', 'users', 'companies')); -$action=GETPOST('action', 'aZ09'); -$mode=GETPOST("mode", 'alpha'); -$id=GETPOST('id', 'int'); -$taskid=GETPOST('taskid', 'int'); +$action = GETPOST('action', 'aZ09'); +$mode = GETPOST("mode", 'alpha'); +$id = GETPOST('id', 'int'); +$taskid = GETPOST('taskid', 'int'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'perweekcard'; +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'perweekcard'; -$mine=0; -if ($mode == 'mine') $mine=1; +$mine = 0; +if ($mode == 'mine') $mine = 1; -$projectid=''; -$projectid=isset($_GET["id"])?$_GET["id"]:$_POST["projectid"]; +$projectid = ''; +$projectid = isset($_GET["id"]) ? $_GET["id"] : $_POST["projectid"]; $hookmanager->initHooks(array('timesheetperweekcard')); // Security check -$socid=0; +$socid = 0; // For external user, no check is done on company because readability is managed by public status of project and assignement. // if ($user->socid > 0) $socid=$user->socid; $result = restrictedArea($user, 'projet', $projectid); -$now=dol_now(); -$nowtmp=dol_getdate($now); -$nowday=$nowtmp['mday']; -$nowmonth=$nowtmp['mon']; -$nowyear=$nowtmp['year']; +$now = dol_now(); +$nowtmp = dol_getdate($now); +$nowday = $nowtmp['mday']; +$nowmonth = $nowtmp['mon']; +$nowyear = $nowtmp['year']; -$year=GETPOST('reyear', 'int')?GETPOST('reyear', 'int'):(GETPOST("year", 'int')?GETPOST("year", "int"):date("Y")); -$month=GETPOST('remonth', 'int')?GETPOST('remonth', 'int'):(GETPOST("month", 'int')?GETPOST("month", "int"):date("m")); -$day=GETPOST('reday', 'int')?GETPOST('reday', 'int'):(GETPOST("day", 'int')?GETPOST("day", "int"):date("d")); -$week=GETPOST("week", "int")?GETPOST("week", "int"):date("W"); +$year = GETPOST('reyear', 'int') ?GETPOST('reyear', 'int') : (GETPOST("year", 'int') ?GETPOST("year", "int") : date("Y")); +$month = GETPOST('remonth', 'int') ?GETPOST('remonth', 'int') : (GETPOST("month", 'int') ?GETPOST("month", "int") : date("m")); +$day = GETPOST('reday', 'int') ?GETPOST('reday', 'int') : (GETPOST("day", 'int') ?GETPOST("day", "int") : date("d")); +$week = GETPOST("week", "int") ?GETPOST("week", "int") : date("W"); $day = (int) $day; -$search_categ=GETPOST("search_categ", 'alpha'); -$search_usertoprocessid=GETPOST('search_usertoprocessid', 'int'); -$search_task_ref=GETPOST('search_task_ref', 'alpha'); -$search_task_label=GETPOST('search_task_label', 'alpha'); -$search_project_ref=GETPOST('search_project_ref', 'alpha'); -$search_thirdparty=GETPOST('search_thirdparty', 'alpha'); -$search_declared_progress=GETPOST('search_declared_progress', 'alpha'); +$search_categ = GETPOST("search_categ", 'alpha'); +$search_usertoprocessid = GETPOST('search_usertoprocessid', 'int'); +$search_task_ref = GETPOST('search_task_ref', 'alpha'); +$search_task_label = GETPOST('search_task_label', 'alpha'); +$search_project_ref = GETPOST('search_project_ref', 'alpha'); +$search_thirdparty = GETPOST('search_thirdparty', 'alpha'); +$search_declared_progress = GETPOST('search_declared_progress', 'alpha'); -$startdayarray=dol_get_first_day_week($day, $month, $year); +$startdayarray = dol_get_first_day_week($day, $month, $year); $prev = $startdayarray; $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_month = $prev['first_month']; $first_year = $prev['first_year']; $week = $prev['week']; @@ -162,7 +162,9 @@ $search_array_options_task = $extrafields->getOptionalsFromPost('projet_task', ' /* * Actions */ - +$parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Purge criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { @@ -808,27 +810,27 @@ if (count($tasksarray) > 0) if ($conf->use_javascript_ajax) { print ' - '; + '; print $langs->trans("Total"); print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print ''; for ($idw = 0; $idw < 7; $idw++) { - $cssweekend=''; + $cssweekend = ''; if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. { - $cssweekend='weekend'; + $cssweekend = 'weekend'; } - $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); + $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); - $cssonholiday=''; - if (! $isavailable[$tmpday]['morning'] && ! $isavailable[$tmpday]['afternoon']) $cssonholiday.='onholidayallday '; - elseif (! $isavailable[$tmpday]['morning']) $cssonholiday.='onholidaymorning '; - elseif (! $isavailable[$tmpday]['afternoon']) $cssonholiday.='onholidayafternoon '; + $cssonholiday = ''; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; + elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; + elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print '
 
'; + print '
 
'; } print '
 
'; diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 332049f194f..77e83dfae96 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -27,6 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; @@ -657,7 +658,8 @@ if ($action == 'create' && $user->rights->projet->creer) // Description print ''.$langs->trans("Description").''; print ''; - print ''; + $doleditor = new DolEditor('description', GETPOST("description", 'none'), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); + $doleditor->Create(); print ''; if ($conf->categorie->enabled) { @@ -927,7 +929,8 @@ elseif ($object->id > 0) // Description print ''.$langs->trans("Description").''; print ''; - print ''; + $doleditor = new DolEditor('description', $object->description, '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); + $doleditor->Create(); print ''; // Tags-Categories @@ -1083,7 +1086,7 @@ elseif ($object->id > 0) // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index a17453889c4..10e091e1244 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -1815,6 +1815,72 @@ class Project extends CommonObject return -1; } } + /** + * Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of project. + * Note: array weekWorkLoad and weekWorkLoadPerTask are reset and filled at each call. + * + * @param int $datestart First day of week (use dol_get_first_day to find this date) + * @param int $taskid Filter on a task id + * @param int $userid Time spent by a particular user + * @return int <0 if OK, >0 if KO + */ + public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0) + { + $error=0; + + $this->monthWorkLoad=array(); + $this->monthWorkLoadPerTask=array(); + + if (empty($datestart)) dol_print_error('', 'Error datestart parameter is empty'); + + $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt"; + $sql.= " WHERE ptt.fk_task = pt.rowid"; + $sql.= " AND pt.fk_projet = ".$this->id; + $sql.= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' "; + $sql.= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')"; + if ($task_id) $sql.= " AND ptt.fk_task=".$taskid; + if (is_numeric($userid)) $sql.= " AND ptt.fk_user=".$userid; + + //print $sql; + $resql=$this->db->query($sql); + if ($resql) + { + $weekalreadyfound=array(); + + $num = $this->db->num_rows($resql); + $i = 0; + // Loop on each record found, so each couple (project id, task id) + while ($i < $num) + { + $obj=$this->db->fetch_object($resql); + if(!empty($obj->task_date)) { + $date = explode('-', $obj->task_date); + $week_number = getWeekNumber($date[2], $date[1], $date[0]); + } + if (empty($weekalreadyfound[$week_number])) + { + $this->monthWorkLoad[$week_number] = $obj->task_duration; + $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] = $obj->task_duration; + } + else + { + $this->monthWorkLoad[$week_number] += $obj->task_duration; + $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] += $obj->task_duration; + } + $weekalreadyfound[$week_number]=1; + $i++; + } + $this->db->free($resql); + return 1; + } + else + { + $this->error="Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index 60657b08061..613daa18ab0 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -156,6 +156,7 @@ class Task extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task ("; $sql .= "fk_projet"; $sql .= ", ref"; + $sql .= ", entity"; $sql .= ", fk_task_parent"; $sql .= ", label"; $sql .= ", description"; @@ -168,6 +169,7 @@ class Task extends CommonObject $sql .= ") VALUES ("; $sql .= $this->fk_project; $sql .= ", ".(!empty($this->ref) ? "'".$this->db->escape($this->ref)."'" : 'null'); + $sql .= ", ".$conf->entity; $sql .= ", ".$this->fk_task_parent; $sql .= ", '".$this->db->escape($this->label)."'"; $sql .= ", '".$this->db->escape($this->description)."'"; diff --git a/htdocs/projet/comment.php b/htdocs/projet/comment.php index 8fd73f420be..d16dca5ceb1 100644 --- a/htdocs/projet/comment.php +++ b/htdocs/projet/comment.php @@ -160,7 +160,7 @@ print ''; // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } diff --git a/htdocs/projet/contact.php b/htdocs/projet/contact.php index cf94b1a5354..42226f93208 100644 --- a/htdocs/projet/contact.php +++ b/htdocs/projet/contact.php @@ -271,7 +271,7 @@ if ($id > 0 || ! empty($ref)) // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index dd89b3ca9c4..516069614b8 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -57,32 +57,32 @@ if (! empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salarie // Load translation files required by the page $langs->loadLangs(array('projects', 'companies', 'suppliers', 'compta')); -if (! empty($conf->facture->enabled)) $langs->load("bills"); -if (! empty($conf->commande->enabled)) $langs->load("orders"); -if (! empty($conf->propal->enabled)) $langs->load("propal"); -if (! empty($conf->ficheinter->enabled)) $langs->load("interventions"); -if (! empty($conf->deplacement->enabled)) $langs->load("trips"); -if (! empty($conf->expensereport->enabled)) $langs->load("trips"); -if (! empty($conf->don->enabled)) $langs->load("donations"); -if (! empty($conf->loan->enabled)) $langs->load("loan"); -if (! empty($conf->salaries->enabled)) $langs->load("salaries"); +if (!empty($conf->facture->enabled)) $langs->load("bills"); +if (!empty($conf->commande->enabled)) $langs->load("orders"); +if (!empty($conf->propal->enabled)) $langs->load("propal"); +if (!empty($conf->ficheinter->enabled)) $langs->load("interventions"); +if (!empty($conf->deplacement->enabled)) $langs->load("trips"); +if (!empty($conf->expensereport->enabled)) $langs->load("trips"); +if (!empty($conf->don->enabled)) $langs->load("donations"); +if (!empty($conf->loan->enabled)) $langs->load("loan"); +if (!empty($conf->salaries->enabled)) $langs->load("salaries"); -$id=GETPOST('id', 'int'); -$ref=GETPOST('ref', 'alpha'); -$action=GETPOST('action', 'alpha'); -$datesrfc=GETPOST('datesrfc'); -$dateerfc=GETPOST('dateerfc'); -$dates=dol_mktime(0, 0, 0, GETPOST('datesmonth'), GETPOST('datesday'), GETPOST('datesyear')); -$datee=dol_mktime(23, 59, 59, GETPOST('dateemonth'), GETPOST('dateeday'), GETPOST('dateeyear')); -if (empty($dates) && ! empty($datesrfc)) $dates=dol_stringtotime($datesrfc); -if (empty($datee) && ! empty($dateerfc)) $datee=dol_stringtotime($dateerfc); -if (! isset($_POST['datesrfc']) && ! isset($_POST['datesday']) && ! empty($conf->global->PROJECT_LINKED_ELEMENT_DEFAULT_FILTER_YEAR)) +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$datesrfc = GETPOST('datesrfc'); +$dateerfc = GETPOST('dateerfc'); +$dates = dol_mktime(0, 0, 0, GETPOST('datesmonth'), GETPOST('datesday'), GETPOST('datesyear')); +$datee = dol_mktime(23, 59, 59, GETPOST('dateemonth'), GETPOST('dateeday'), GETPOST('dateeyear')); +if (empty($dates) && !empty($datesrfc)) $dates = dol_stringtotime($datesrfc); +if (empty($datee) && !empty($dateerfc)) $datee = dol_stringtotime($dateerfc); +if (!isset($_POST['datesrfc']) && !isset($_POST['datesday']) && !empty($conf->global->PROJECT_LINKED_ELEMENT_DEFAULT_FILTER_YEAR)) { - $new=dol_now(); - $tmp=dol_getdate($new); + $new = dol_now(); + $tmp = dol_getdate($new); //$datee=$now //$dates=dol_time_plus_duree($datee, -1, 'y'); - $dates=dol_get_first_day($tmp['year'], 1); + $dates = dol_get_first_day($tmp['year'], 1); } if ($id == '' && $ref == '') { @@ -91,18 +91,18 @@ if ($id == '' && $ref == '') exit(); } -$mine = $_REQUEST['mode']=='mine' ? 1 : 0; +$mine = $_REQUEST['mode'] == 'mine' ? 1 : 0; //if (! $user->rights->projet->all->lire) $mine=1; // Special for projects $object = new Project($db); -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once -if(! empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once +if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); // Security check -$socid=$object->socid; +$socid = $object->socid; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. -$result = restrictedArea($user, 'projet', $object->id, 'projet&project'); +$result = restrictedArea($user, 'projet', $object->id, 'projet&project'); $hookmanager->initHooks(array('projectOverview')); @@ -164,23 +164,23 @@ print ''; print $langs->trans("Usage"); print ''; print ''; -if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) +if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; + print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowOpportunity"); print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); print '
'; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print 'usage_task ? ' checked="checked"' : '')).'"> '; + print 'usage_task ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectFollowTasks"); print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); print '
'; } -if (! empty($conf->global->PROJECT_BILL_TIME_SPENT)) +if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; + print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; $htmltext = $langs->trans("ProjectBillTimeDescription"); print $form->textwithpicto($langs->trans("BillTime"), $htmltext); print '
'; @@ -248,7 +248,7 @@ print ''; // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } @@ -511,19 +511,19 @@ $listofreferent = array( */ ); -$parameters=array('listofreferent'=>$listofreferent); +$parameters = array('listofreferent'=>$listofreferent); $resHook = $hookmanager->executeHooks('completeListOfReferent', $parameters, $object, $action); -if(!empty($hookmanager->resArray)) { +if (!empty($hookmanager->resArray)) { $listofreferent = array_merge($listofreferent, $hookmanager->resArray); } -if ($action=="addelement") +if ($action == "addelement") { $tablename = GETPOST("tablename"); $elementselectid = GETPOST("elementselect"); - $result=$object->update_element($tablename, $elementselectid); - if ($result<0) + $result = $object->update_element($tablename, $elementselectid); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -550,7 +550,7 @@ $showdatefilter = 0; if (!$showdatefilter) { print '
'; - print '
'; + print ''; print ''; print ''; print ''; @@ -591,53 +591,53 @@ print ''; foreach ($listofreferent as $key => $value) { - $name=$langs->trans($value['name']); - $title=$value['title']; - $classname=$value['class']; - $tablename=$value['table']; - $datefieldname=$value['datefieldname']; - $qualified=$value['test']; + $name = $langs->trans($value['name']); + $title = $value['title']; + $classname = $value['class']; + $tablename = $value['table']; + $datefieldname = $value['datefieldname']; + $qualified = $value['test']; $margin = $value['margin']; $project_field = $value['project_field']; if ($qualified && isset($margin)) // If this element must be included into profit calculation ($margin is 'minus' or 'plus') { $element = new $classname($db); - $elementarray = $object->get_element_list($key, $tablename, $datefieldname, $dates, $datee, !empty($project_field)?$project_field:'fk_projet'); + $elementarray = $object->get_element_list($key, $tablename, $datefieldname, $dates, $datee, !empty($project_field) ? $project_field : 'fk_projet'); - if (count($elementarray)>0 && is_array($elementarray)) + if (count($elementarray) > 0 && is_array($elementarray)) { $total_ht = 0; $total_ttc = 0; - $num=count($elementarray); + $num = count($elementarray); for ($i = 0; $i < $num; $i++) { - $tmp=explode('_', $elementarray[$i]); - $idofelement=$tmp[0]; - $idofelementuser=$tmp[1]; + $tmp = explode('_', $elementarray[$i]); + $idofelement = $tmp[0]; + $idofelementuser = $tmp[1]; $element->fetch($idofelement); if ($idofelementuser) $elementuser->fetch($idofelementuser); // Define if record must be used for total or not - $qualifiedfortotal=true; + $qualifiedfortotal = true; if ($key == 'invoice') { - if (! empty($element->close_code) && $element->close_code == 'replaced') $qualifiedfortotal=false; // Replacement invoice, do not include into total - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $element->type == Facture::TYPE_DEPOSIT) $qualifiedfortotal=false; // If hidden option to use deposits as payment (deprecated, not recommended to use this), deposits are not included + if (!empty($element->close_code) && $element->close_code == 'replaced') $qualifiedfortotal = false; // Replacement invoice, do not include into total + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $element->type == Facture::TYPE_DEPOSIT) $qualifiedfortotal = false; // If hidden option to use deposits as payment (deprecated, not recommended to use this), deposits are not included } if ($key == 'propal') { - if ($element->statut == Propal::STATUS_NOTSIGNED) $qualifiedfortotal=false; // Refused proposal must not be included in total + if ($element->statut == Propal::STATUS_NOTSIGNED) $qualifiedfortotal = false; // Refused proposal must not be included in total } if ($tablename != 'expensereport_det' && method_exists($element, 'fetch_thirdparty')) $element->fetch_thirdparty(); // Define $total_ht_by_line - if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ht_by_line=$element->amount; - elseif ($tablename == 'fichinter') $total_ht_by_line=$element->getAmount(); - elseif ($tablename == 'stock_mouvement') $total_ht_by_line=$element->price*abs($element->qty); + if ($tablename == 'don' || $tablename == 'chargesociales' || $tablename == 'payment_various' || $tablename == 'payment_salary') $total_ht_by_line = $element->amount; + elseif ($tablename == 'fichinter') $total_ht_by_line = $element->getAmount(); + elseif ($tablename == 'stock_mouvement') $total_ht_by_line = $element->price * abs($element->qty); elseif ($tablename == 'projet_task') { if ($idofelementuser) @@ -788,49 +788,49 @@ foreach ($listofreferent as $key => $value) $element = new $classname($db); - $addform=''; + $addform = ''; - $idtofilterthirdparty=0; + $idtofilterthirdparty = 0; $array_of_element_linkable_with_different_thirdparty = array('facture_fourn', 'commande_fournisseur'); - if (! in_array($tablename, $array_of_element_linkable_with_different_thirdparty)) + if (!in_array($tablename, $array_of_element_linkable_with_different_thirdparty)) { - $idtofilterthirdparty=$object->thirdparty->id; - if (! empty($conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS)) $idtofilterthirdparty.=','.$conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS; + $idtofilterthirdparty = $object->thirdparty->id; + if (!empty($conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS)) $idtofilterthirdparty .= ','.$conf->global->PROJECT_OTHER_THIRDPARTY_ID_TO_ADD_ELEMENTS; } if (empty($conf->global->PROJECT_LINK_ON_OVERWIEW_DISABLED) && $idtofilterthirdparty && !in_array($tablename, $exclude_select_element)) { - $selectList=$formproject->select_element($tablename, $idtofilterthirdparty, 'minwidth300', -2, !empty($project_field)?$project_field:'fk_projet'); - if ($selectList<0) + $selectList = $formproject->select_element($tablename, $idtofilterthirdparty, 'minwidth300', -2, !empty($project_field) ? $project_field : 'fk_projet'); + if ($selectList < 0) { setEventMessages($formproject->error, $formproject->errors, 'errors'); } - elseif($selectList) + elseif ($selectList) { // Define form with the combo list of elements to link - $addform.='
'; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.=''; - $addform.='
'.$langs->trans("SelectElement").''.$selectList.'
'; - $addform.=''; - $addform.='
'; + $addform .= '
'; + $addform .= '
'; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= ''; + $addform .= '
'.$langs->trans("SelectElement").''.$selectList.'
'; + $addform .= '
'; + $addform .= '
'; } } if (empty($conf->global->PROJECT_CREATE_ON_OVERVIEW_DISABLED) && $urlnew) { - $addform.='
'; - if ($testnew) $addform.=''.($buttonnew?$langs->trans($buttonnew):$langs->trans("Create")).''; + $addform .= '
'; + if ($testnew) $addform .= ''.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).''; elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - $addform.=''.($buttonnew?$langs->trans($buttonnew):$langs->trans("Create")).''; + $addform .= ''.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).''; } - $addform.='
'; + $addform .= '
'; } print load_fiche_titre($langs->trans($title), $addform, ''); @@ -855,6 +855,14 @@ foreach ($listofreferent as $key => $value) elseif (in_array($tablename, array('expensereport_det', 'don', 'projet_task', 'stock_mouvement', 'payment_salary'))) print $langs->trans("User"); else print $langs->trans("ThirdParty"); print ''; + // Duration of intervention + if ($tablename == 'fichinter') + { + print ''; + print $langs->trans("TotalDuration"); + $total_duration = 0; + print ''; + } // Amount HT //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print ''.$langs->trans("AmountHT").''; //elseif (empty($value['disableamount']) && in_array($tablename, array('projet_task'))) print ''.$langs->trans("Amount").''; @@ -938,7 +946,7 @@ foreach ($listofreferent as $key => $value) { if (empty($conf->global->PROJECT_DISABLE_UNLINK_FROM_OVERVIEW) || $user->admin) // PROJECT_DISABLE_UNLINK_FROM_OVERVIEW is empty by defaut, so this test true { - print ''; + print 'id.($project_field ? '&projectfield='.$project_field : '').'" class="reposition">'; print img_picto($langs->trans('Unlink'), 'unlink'); print ''; } @@ -1063,6 +1071,15 @@ foreach ($listofreferent as $key => $value) } print ''; + // Add duration and store it in counter for fichinter + if ($tablename == 'fichinter') + { + print ''; + print convertSecondToTime($element->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); + $total_duration += $element->duration; + print ''; + } + // Amount without tax $warning = ''; if (empty($value['disableamount'])) @@ -1108,9 +1125,9 @@ foreach ($listofreferent as $key => $value) if ($othermessage) print $othermessage; if (isset($total_ht_by_line)) { - if (! $qualifiedfortotal) print ''; + if (!$qualifiedfortotal) print ''; print price($total_ht_by_line); - if (! $qualifiedfortotal) print ''; + if (!$qualifiedfortotal) print ''; } if ($warning) print ' '.img_warning($warning); print ''; @@ -1156,9 +1173,9 @@ foreach ($listofreferent as $key => $value) if ($othermessage) print $othermessage; if (isset($total_ttc_by_line)) { - if (! $qualifiedfortotal) print ''; + if (!$qualifiedfortotal) print ''; print price($total_ttc_by_line); - if (! $qualifiedfortotal) print ''; + if (!$qualifiedfortotal) print ''; } if ($warning) print ' '.img_warning($warning); print ''; @@ -1242,6 +1259,8 @@ foreach ($listofreferent as $key => $value) } //if (empty($value['disableamount']) && ! in_array($tablename, array('projet_task'))) print ''.$langs->trans("TotalHT").' : '.price($total_ht).''; //elseif (empty($value['disableamount']) && in_array($tablename, array('projet_task'))) print ''.$langs->trans("Total").' : '.price($total_ht).''; + // If fichinter add the total_duration + if ($tablename == 'fichinter') print ''.convertSecondToTime($total_duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).''; print ''; if (empty($value['disableamount'])) { diff --git a/htdocs/projet/ganttview.php b/htdocs/projet/ganttview.php index 310e4705f71..db4a5642dec 100644 --- a/htdocs/projet/ganttview.php +++ b/htdocs/projet/ganttview.php @@ -204,7 +204,7 @@ if (($id > 0 && is_numeric($id)) || !empty($ref)) // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index 1424c64d8d3..b125ed7306e 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } // Load translation files required by the page $langs->loadLangs(array('projects', 'users', 'companies')); @@ -479,7 +480,7 @@ if ($id > 0 || !empty($ref)) // Categories if ($conf->categorie->enabled) { print ''.$langs->trans("Categories").''; - print $form->showCategories($object->id, 'project', 1); + print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1); print ""; } diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index f9069f7efa7..291ab4ab949 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -5,6 +5,7 @@ * Copyright (C) 2011 Juanjo Menent * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2018 Frédéric France + * Copyright (C) 2019 Christophe Battarel * * 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 @@ -21,9 +22,9 @@ */ /** - * \file htdocs/projet/tasks/time.php - * \ingroup project - * \brief Page to add new time spent on a task + * \file htdocs/projet/tasks/time.php + * \ingroup project + * \brief Page to add new time spent on a task */ require '../../main.inc.php'; @@ -38,18 +39,18 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; // Load translation files required by the page $langs->loadLangs(array('projects', 'bills', 'orders')); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) -$confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'alpha'); -$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$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 $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page -$optioncss = GETPOST('optioncss', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); -$id = GETPOST('id', 'int'); -$projectid = GETPOST('projectid', 'int'); -$ref = GETPOST('ref', 'alpha'); +$id = GETPOST('id', 'int'); +$projectid = GETPOST('projectid', 'int'); +$ref = GETPOST('ref', 'alpha'); $withproject = GETPOST('withproject', 'int'); $project_ref = GETPOST('project_ref', 'alpha'); @@ -68,14 +69,14 @@ $search_valuebilled = GETPOST('search_valuebilled', 'int'); // Security check $socid = 0; -//if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. +//if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. if (!$user->rights->projet->lire) accessforbidden(); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -113,20 +114,20 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_month = ''; $search_year = ''; $search_date = ''; - $search_datehour = ''; - $search_datewithhour = ''; - $search_note = ''; - $search_duration = ''; - $search_value = ''; - $search_date_creation = ''; - $search_date_update = ''; - $search_task_ref = ''; - $search_task_label = ''; - $search_user = 0; - $search_valuebilled = ''; - $toselect = ''; - $search_array_options = array(); - $action = ''; + $search_datehour = ''; + $search_datewithhour = ''; + $search_note = ''; + $search_duration = ''; + $search_value = ''; + $search_date_creation = ''; + $search_date_update = ''; + $search_task_ref = ''; + $search_task_label = ''; + $search_user = 0; + $search_valuebilled = ''; + $toselect = ''; + $search_array_options = array(); + $action = ''; } if ($action == 'addtimespent' && $user->rights->projet->lire) @@ -149,61 +150,61 @@ if ($action == 'addtimespent' && $user->rights->projet->lire) if (!$error) { - if ($id || $ref) + if ($id || $ref) { $object->fetch($id, $ref); } else { - if (!GETPOST('taskid', 'int') || GETPOST('taskid', 'int') < 0) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), null, 'errors'); - $action = 'createtime'; - $error++; - } - else - { - $object->fetch(GETPOST('taskid', 'int')); - } + if (!GETPOST('taskid', 'int') || GETPOST('taskid', 'int') < 0) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), null, 'errors'); + $action = 'createtime'; + $error++; + } + else + { + $object->fetch(GETPOST('taskid', 'int')); + } } if (!$error) { - $object->fetch_projet(); + $object->fetch_projet(); - if (empty($object->project->statut)) - { - setEventMessages($langs->trans("ProjectMustBeValidatedFirst"), null, 'errors'); - $action = 'createtime'; - $error++; - } - else - { - $object->timespent_note = $_POST["timespent_note"]; - if (GETPOST('progress', 'int') > 0) $object->progress = GETPOST('progress', 'int'); // If progress is -1 (not defined), we do not change value - $object->timespent_duration = $_POST["timespent_durationhour"] * 60 * 60; // We store duration in seconds - $object->timespent_duration += ($_POST["timespent_durationmin"] ? $_POST["timespent_durationmin"] : 0) * 60; // We store duration in seconds - if (GETPOST("timehour") != '' && GETPOST("timehour") >= 0) // If hour was entered - { - $object->timespent_date = dol_mktime(GETPOST("timehour"), GETPOST("timemin"), 0, GETPOST("timemonth"), GETPOST("timeday"), GETPOST("timeyear")); - $object->timespent_withhour = 1; - } - else - { - $object->timespent_date = dol_mktime(12, 0, 0, GETPOST("timemonth"), GETPOST("timeday"), GETPOST("timeyear")); - } - $object->timespent_fk_user = $_POST["userid"]; - $result = $object->addTimeSpent($user); - if ($result >= 0) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans($object->error), null, 'errors'); - $error++; - } - } + if (empty($object->project->statut)) + { + setEventMessages($langs->trans("ProjectMustBeValidatedFirst"), null, 'errors'); + $action = 'createtime'; + $error++; + } + else + { + $object->timespent_note = $_POST["timespent_note"]; + if (GETPOST('progress', 'int') > 0) $object->progress = GETPOST('progress', 'int'); // If progress is -1 (not defined), we do not change value + $object->timespent_duration = $_POST["timespent_durationhour"] * 60 * 60; // We store duration in seconds + $object->timespent_duration += ($_POST["timespent_durationmin"] ? $_POST["timespent_durationmin"] : 0) * 60; // We store duration in seconds + if (GETPOST("timehour") != '' && GETPOST("timehour") >= 0) // If hour was entered + { + $object->timespent_date = dol_mktime(GETPOST("timehour"), GETPOST("timemin"), 0, GETPOST("timemonth"), GETPOST("timeday"), GETPOST("timeyear")); + $object->timespent_withhour = 1; + } + else + { + $object->timespent_date = dol_mktime(12, 0, 0, GETPOST("timemonth"), GETPOST("timeday"), GETPOST("timeyear")); + } + $object->timespent_fk_user = $_POST["userid"]; + $result = $object->addTimeSpent($user); + if ($result >= 0) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans($object->error), null, 'errors'); + $error++; + } + } } } else @@ -225,34 +226,71 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$_POST["cancel if (!$error) { - $object->fetch($id, $ref); - // TODO Check that ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids)) - - $object->timespent_id = $_POST["lineid"]; - $object->timespent_note = $_POST["timespent_note_line"]; - $object->timespent_old_duration = $_POST["old_duration"]; - $object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds - $object->timespent_duration += $_POST["new_durationmin"] * 60; // We store duration in seconds - if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) // If hour was entered - { - $object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); - $object->timespent_withhour = 1; - } - else + if ($_POST['taskid'] != $id) { - $object->timespent_date = dol_mktime(12, 0, 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); - } - $object->timespent_fk_user = $_POST["userid_line"]; + $id = $_POST['taskid']; - $result = $object->updateTimeSpent($user); - if ($result >= 0) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $object->fetchTimeSpent(GETPOST('lineid', 'int')); + // TODO Check that ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids)) + $result = $object->delTimeSpent($user); + + $object->fetch($id, $ref); + $object->timespent_note = $_POST["timespent_note_line"]; + $object->timespent_old_duration = $_POST["old_duration"]; + $object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds + $object->timespent_duration += ($_POST["new_durationmin"] ? $_POST["new_durationmin"] : 0) * 60; // We store duration in seconds + if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) // If hour was entered + { + $object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); + $object->timespent_withhour = 1; + } + else + { + $object->timespent_date = dol_mktime(12, 0, 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); + } + $object->timespent_fk_user = $_POST["userid_line"]; + $result = $object->addTimeSpent($user); + if ($result >= 0) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans($object->error), null, 'errors'); + $error++; + } } else { - setEventMessages($langs->trans($object->error), null, 'errors'); - $error++; + $object->fetch($id, $ref); + // TODO Check that ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids)) + + $object->timespent_id = $_POST["lineid"]; + $object->timespent_note = $_POST["timespent_note_line"]; + $object->timespent_old_duration = $_POST["old_duration"]; + $object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds + $object->timespent_duration += $_POST["new_durationmin"] * 60; // We store duration in seconds + if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) // If hour was entered + { + $object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); + $object->timespent_withhour = 1; + } + else + { + $object->timespent_date = dol_mktime(12, 0, 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear")); + } + $object->timespent_fk_user = $_POST["userid_line"]; + + $result = $object->updateTimeSpent($user); + if ($result >= 0) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans($object->error), null, 'errors'); + $error++; + } } } else @@ -305,24 +343,24 @@ if (GETPOST('projectid', 'int') > 0) $projectidforalltimes = GETPOST('projectid', 'int'); $result = $projectstatic->fetch($projectidforalltimes); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); - $res = $projectstatic->fetch_optionals(); + if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + $res = $projectstatic->fetch_optionals(); } elseif (GETPOST('project_ref', 'alpha')) { - $projectstatic->fetch(0, GETPOST('project_ref', 'alpha')); - $projectidforalltimes = $projectstatic->id; - $withproject = 1; + $projectstatic->fetch(0, GETPOST('project_ref', 'alpha')); + $projectidforalltimes = $projectstatic->id; + $withproject = 1; } elseif ($id > 0) { - $object->fetch($id); - $result = $projectstatic->fetch($object->fk_project); + $object->fetch($id); + $result = $projectstatic->fetch($object->fk_project); } if ($action == 'confirm_generateinvoice') { - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); if (!($projectstatic->thirdparty->id > 0)) @@ -342,9 +380,26 @@ if ($action == 'confirm_generateinvoice') $db->begin(); $idprod = GETPOST('productid', 'int'); + $generateinvoicemode = GETPOST('generateinvoicemode', 'string'); + $invoiceToUse = GETPOST('invoiceid', 'int'); + + $prodDurationHours = 1.0; if ($idprod > 0) { $tmpproduct->fetch($idprod); + if ($tmpproduct->duration_unit == 'i') + $prodDurationHours = 1. / 60; + if ($tmpproduct->duration_unit == 'h') + $prodDurationHours = 1.; + if ($tmpproduct->duration_unit == 'd') + $prodDurationHours = 24.; + if ($tmpproduct->duration_unit == 'w') + $prodDurationHours = 24. * 7; + if ($tmpproduct->duration_unit == 'm') + $prodDurationHours = 24. * 30; + if ($tmpproduct->duration_unit == 'y') + $prodDurationHours = 24. * 365; + $prodDurationHours *= $tmpproduct->duration_value; $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0); $pu_ht = empty($dataforprice['pu_ht']) ? 0 : $dataforprice['pu_ht']; @@ -354,73 +409,165 @@ if ($action == 'confirm_generateinvoice') } else { - $pu_ht = 0; - $txtva = get_default_tva($mysoc, $projectstatic->thirdparty); - $localtax1 = get_default_localtax($mysoc, $projectstatic->thirdparty, 1); - $localtax2 = get_default_localtax($mysoc, $projectstatic->thirdparty, 2); + $pu_ht = 0; + $txtva = get_default_tva($mysoc, $projectstatic->thirdparty); + $localtax1 = get_default_localtax($mysoc, $projectstatic->thirdparty, 1); + $localtax2 = get_default_localtax($mysoc, $projectstatic->thirdparty, 2); } $tmpinvoice->socid = $projectstatic->thirdparty->id; $tmpinvoice->date = dol_mktime(GETPOST('rehour', 'int'), GETPOST('remin', 'int'), GETPOST('resec', 'int'), GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); $tmpinvoice->fk_project = $projectstatic->id; - $result = $tmpinvoice->create($user); - if ($result <= 0) - { - $error++; - setEventMessages($tmpinvoice->error, $tmpinvoice->errors, 'errors'); - } + if ($invoiceToUse) { + $tmpinvoice->fetch($invoiceToUse); + } + else { + $result = $tmpinvoice->create($user); + if ($result <= 0) + { + $error++; + setEventMessages($tmpinvoice->error, $tmpinvoice->errors, 'errors'); + } + } if (!$error) { - $arrayoftasks = array(); - foreach ($toselect as $key => $value) - { - // Get userid, timepent - $object->fetchTimeSpent($value); - $arrayoftasks[$object->timespent_fk_user]['timespent'] += $object->timespent_duration; - $arrayoftasks[$object->timespent_fk_user]['totalvaluetodivideby3600'] += ($object->timespent_duration * $object->timespent_thm); - } - - foreach ($arrayoftasks as $userid => $value) - { - $fuser->fetch($userid); - //$pu_ht = $value['timespent'] * $fuser->thm; - $username = $fuser->getFullName($langs); - - // Define qty per hour - $qtyhour = round($value['timespent'] / 3600, 2); - $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); - - // If no unit price known - if (empty($pu_ht)) - { - $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); + if ($generateinvoicemode == 'onelineperuser') { + $arrayoftasks = array(); + foreach ($toselect as $key => $value) + { + // Get userid, timepent + $object->fetchTimeSpent($value); + $arrayoftasks[$object->timespent_fk_user]['timespent'] += $object->timespent_duration; + $arrayoftasks[$object->timespent_fk_user]['totalvaluetodivideby3600'] += ($object->timespent_duration * $object->timespent_thm); } - // Add lines - $lineid = $tmpinvoice->addline($langs->trans("TimeSpentForInvoice", $username).' : '.$qtyhourtext, $pu_ht, $qtyhour, $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0)); - - // Update lineid into line of timespent - $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; - $sql .= ' WHERE rowid in ('.join(',', $toselect).') AND fk_user = '.$userid; - $result = $db->query($sql); - if (!$result) + foreach ($arrayoftasks as $userid => $value) { - $error++; - setEventMessages($db->lasterror(), null, 'errors'); - break; + $fuser->fetch($userid); + //$pu_ht = $value['timespent'] * $fuser->thm; + $username = $fuser->getFullName($langs); + + // Define qty per hour + $qtyhour = $value['timespent'] / 3600; + $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); + + // If no unit price known + if (empty($pu_ht)) + { + $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); + } + + // Add lines + $lineid = $tmpinvoice->addline($langs->trans("TimeSpentForInvoice", $username).' : '.$qtyhourtext, $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0)); + + // Update lineid into line of timespent + $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; + $sql .= ' WHERE rowid in ('.join(',', $toselect).') AND fk_user = '.$userid; + $result = $db->query($sql); + if (!$result) + { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + break; + } + } + } + elseif ($generateinvoicemode == 'onelineperperiod') { + $arrayoftasks = array(); + foreach ($toselect as $key => $value) + { + // Get userid, timepent + $object->fetchTimeSpent($value); + $arrayoftasks[$object->timespent_id]['timespent'] = $object->timespent_duration; + $arrayoftasks[$object->timespent_id]['totalvaluetodivideby3600'] = $object->timespent_duration * $object->timespent_thm; + $arrayoftasks[$object->timespent_id]['note'] = $object->timespent_note; + $arrayoftasks[$object->timespent_id]['user'] = $object->timespent_fk_user; + } + + foreach ($arrayoftasks as $timespent_id => $value) + { + $userid = $value['user']; + $fuser->fetch($userid); + //$pu_ht = $value['timespent'] * $fuser->thm; + $username = $fuser->getFullName($langs); + + // Define qty per hour + $qtyhour = $value['timespent'] / 3600; + $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); + + // If no unit price known + if (empty($pu_ht)) + { + $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); + } + + // Add lines + $lineid = $tmpinvoice->addline($value['note'], $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0)); + + // Update lineid into line of timespent + $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; + $sql .= ' WHERE rowid in ('.join(',', $toselect).') AND fk_user = '.$userid; + $result = $db->query($sql); + if (!$result) + { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + break; + } + } + } + elseif ($generateinvoicemode == 'onelinepertask') { + $arrayoftasks = array(); + foreach ($toselect as $key => $value) + { + // Get userid, timepent + $object->fetchTimeSpent($value); + // $object->id is the task id + $arrayoftasks[$object->id]['timespent'] += $object->timespent_duration; + $arrayoftasks[$object->id]['totalvaluetodivideby3600'] += $object->timespent_duration * $object->timespent_thm; + } + + foreach ($arrayoftasks as $task_id => $value) + { + $ftask = new Task($db); + $ftask->fetch($task_id); + // Define qty per hour + $qtyhour = $value['timespent'] / 3600; + $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY); + + // If no unit price known + if (empty($pu_ht)) + { + $pu_ht = price2num($value['totalvaluetodivideby3600'] / 3600, 'MU'); + } + + // Add lines + $lineName = $ftask->ref.' - '.$ftask->label; + $lineid = $tmpinvoice->addline($lineName, $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0)); + + // Update lineid into line of timespent + $sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id; + $sql .= ' WHERE rowid in ('.join(',', $toselect).')'; + $result = $db->query($sql); + if (!$result) + { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + break; + } } } } if (!$error) { - $urltoinvoice = $tmpinvoice->getNomUrl(0); - setEventMessages($langs->trans("InvoiceGeneratedFromTimeSpent", $urltoinvoice), null, 'mesgs'); - //var_dump($tmpinvoice); + $urltoinvoice = $tmpinvoice->getNomUrl(0); + setEventMessages($langs->trans("InvoiceGeneratedFromTimeSpent", $urltoinvoice), null, 'mesgs'); + //var_dump($tmpinvoice); - $db->commit(); + $db->commit(); } else { @@ -447,14 +594,14 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) { /* * Fiche projet en mode visu - */ - if ($projectidforalltimes > 0) - { - $result = $projectstatic->fetch($projectidforalltimes); - if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); - $res = $projectstatic->fetch_optionals(); - } - elseif ($object->fetch($id, $ref) >= 0) + */ + if ($projectidforalltimes > 0) + { + $result = $projectstatic->fetch($projectidforalltimes); + if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty(); + $res = $projectstatic->fetch_optionals(); + } + elseif ($object->fetch($id, $ref) >= 0) { if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments(); $result = $projectstatic->fetch($object->fk_project); @@ -463,10 +610,10 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $res = $projectstatic->fetch_optionals(); $object->project = clone $projectstatic; - } + } - $userRead = $projectstatic->restrictedProjectArea($user, 'read'); - $linktocreatetime = ''; + $userRead = $projectstatic->restrictedProjectArea($user, 'read'); + $linktocreatetime = ''; if ($projectstatic->id > 0) { @@ -482,114 +629,114 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Project card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
'; - // Title - $morehtmlref .= $projectstatic->title; - // Thirdparty - if ($projectstatic->thirdparty->id > 0) - { - $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); - } - $morehtmlref .= '
'; + $morehtmlref = '
'; + // Title + $morehtmlref .= $projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref .= '
'; - // Define a complementary filter for search of next/prev ref. - if (!$user->rights->projet->all->lire) - { - $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); - $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; - } + // Define a complementary filter for search of next/prev ref. + if (!$user->rights->projet->all->lire) + { + $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0); + $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")"; + } - dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; - // Usage - print ''; - print ''; + // Usage + print ''; + print ''; - // Visibility - print ''; + // Visibility + print ''; - // Date start - end - print ''; + // Date start - end + print ''; - // Budget - print ''; + // Budget + 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 $langs->trans("Usage"); - print ''; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; - $htmltext = $langs->trans("ProjectFollowOpportunity"); - print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); - print '
'; - } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { - print 'usage_task ? ' checked="checked"' : '')).'"> '; - $htmltext = $langs->trans("ProjectFollowTasks"); - print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); - print '
'; - } - if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { - print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; - $htmltext = $langs->trans("ProjectBillTimeDescription"); - print $form->textwithpicto($langs->trans("BillTime"), $htmltext); - print '
'; - } - print '
'; + print $langs->trans("Usage"); + print ''; + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + { + print 'usage_opportunity ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("ProjectFollowOpportunity"); + print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext); + print '
'; + } + if (empty($conf->global->PROJECT_HIDE_TASKS)) + { + print 'usage_task ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("ProjectFollowTasks"); + print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext); + print '
'; + } + if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) + { + print 'usage_bill_time ? ' checked="checked"' : '')).'"> '; + $htmltext = $langs->trans("ProjectBillTimeDescription"); + print $form->textwithpicto($langs->trans("BillTime"), $htmltext); + print '
'; + } + print '
'.$langs->trans("Visibility").''; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
'.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; - $start = dol_print_date($projectstatic->date_start, 'day'); - print ($start ? $start : '?'); - $end = dol_print_date($projectstatic->date_end, 'day'); - print ' - '; - print ($end ? $end : '?'); - if ($projectstatic->hasDelay()) print img_warning("Late"); - print '
'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + $start = dol_print_date($projectstatic->date_start, 'day'); + print ($start ? $start : '?'); + $end = dol_print_date($projectstatic->date_end, 'day'); + print ' - '; + print ($end ? $end : '?'); + if ($projectstatic->hasDelay()) print img_warning("Late"); + print '
'.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); - print '
'.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); + print '
'; + print ''; - print '
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; - // Description - print ''; + // Description + print ''; - // Categories - if ($conf->categorie->enabled) { - print '"; - } + // Categories + if ($conf->categorie->enabled) { + print '"; + } - print '
'.$langs->trans("Description").''; - print nl2br($projectstatic->description); - print '
'.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
'.$langs->trans("Categories").''; - print $form->showCategories($projectstatic->id, 'project', 1); - print "
'.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id, 'project', 1); + print "
'; + print ''; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '
'; + print '
'; dol_fiche_end(); @@ -597,46 +744,46 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } // Link to create time - $linktocreatetimeBtnStatus = 0; - $linktocreatetimeUrl = ''; - $linktocreatetimeHelpText = ''; - if ($user->rights->projet->all->lire || $user->rights->projet->lire) // To enter time, read permission is enough + $linktocreatetimeBtnStatus = 0; + $linktocreatetimeUrl = ''; + $linktocreatetimeHelpText = ''; + if ($user->rights->projet->all->lire || $user->rights->projet->lire) // To enter time, read permission is enough { if ($projectstatic->public || $userRead > 0) - { - $linktocreatetimeBtnStatus = 1; + { + $linktocreatetimeBtnStatus = 1; - if (!empty($projectidforalltimes)) // We are on tab 'Time Spent' of project - { - $backtourl = $_SERVER['PHP_SELF'].'?projectid='.$projectstatic->id.($withproject ? '&withproject=1' : ''); - $linktocreatetimeUrl = $_SERVER['PHP_SELF'].'?'.($withproject ? 'withproject=1' : '').'&projectid='.$projectstatic->id.'&action=createtime'.$param.'&backtopage='.urlencode($backtourl); - } - else // We are on tab 'Time Spent' of task - { - $backtourl = $_SERVER['PHP_SELF'].'?id='.$object->id.($withproject ? '&withproject=1' : ''); - $linktocreatetimeUrl = $_SERVER['PHP_SELF'].'?'.($withproject ? 'withproject=1' : '').($object->id > 0 ? '&id='.$object->id : '&projectid='.$projectstatic->id).'&action=createtime'.$param.'&backtopage='.urlencode($backtourl); - } - } - else - { - $linktocreatetimeBtnStatus = -2; - $linktocreatetimeHelpText = $langs->trans("NotOwnerOfProject"); - } + if (!empty($projectidforalltimes)) // We are on tab 'Time Spent' of project + { + $backtourl = $_SERVER['PHP_SELF'].'?projectid='.$projectstatic->id.($withproject ? '&withproject=1' : ''); + $linktocreatetimeUrl = $_SERVER['PHP_SELF'].'?'.($withproject ? 'withproject=1' : '').'&projectid='.$projectstatic->id.'&action=createtime'.$param.'&backtopage='.urlencode($backtourl); + } + else // We are on tab 'Time Spent' of task + { + $backtourl = $_SERVER['PHP_SELF'].'?id='.$object->id.($withproject ? '&withproject=1' : ''); + $linktocreatetimeUrl = $_SERVER['PHP_SELF'].'?'.($withproject ? 'withproject=1' : '').($object->id > 0 ? '&id='.$object->id : '&projectid='.$projectstatic->id).'&action=createtime'.$param.'&backtopage='.urlencode($backtourl); + } + } + else + { + $linktocreatetimeBtnStatus = -2; + $linktocreatetimeHelpText = $langs->trans("NotOwnerOfProject"); + } } - $linktocreatetime = dolGetButtonTitle($langs->trans('AddTimeSpent'), $linktocreatetimeHelpText, 'fa fa-plus-circle', $linktocreatetimeUrl, '', $linktocreatetimeBtnStatus); - } + $linktocreatetime = dolGetButtonTitle($langs->trans('AddTimeSpent'), $linktocreatetimeHelpText, 'fa fa-plus-circle', $linktocreatetimeUrl, '', $linktocreatetimeBtnStatus); + } $massactionbutton = ''; if ($projectstatic->usage_bill_time) { - $arrayofmassactions = array( - 'generateinvoice'=>$langs->trans("GenerateBill"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - //if ($user->rights->projet->creer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'generateinvoice'))) $arrayofmassactions = array(); - $massactionbutton = $form->selectMassAction('', $arrayofmassactions); + $arrayofmassactions = array( + 'generateinvoice'=>$langs->trans("GenerateBill"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->projet->creer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete', 'generateinvoice'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); } // Show section with information of task. If id of task is not defined and project id defined, then $projectidforalltimes is not empty. @@ -665,17 +812,17 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Project if (empty($withproject)) { - $morehtmlref .= '
'; - $morehtmlref .= $langs->trans("Project").': '; - $morehtmlref .= $projectstatic->getNomUrl(1); - $morehtmlref .= '
'; + $morehtmlref .= '
'; + $morehtmlref .= $langs->trans("Project").': '; + $morehtmlref .= $projectstatic->getNomUrl(1); + $morehtmlref .= '
'; - // Third party - $morehtmlref .= $langs->trans("ThirdParty").': '; - if (is_object($projectstatic->thirdparty)) { - $morehtmlref .= $projectstatic->thirdparty->getNomUrl(1); - } - $morehtmlref .= '
'; + // Third party + $morehtmlref .= $langs->trans("ThirdParty").': '; + if (is_object($projectstatic->thirdparty)) { + $morehtmlref .= $projectstatic->thirdparty->getNomUrl(1); + } + $morehtmlref .= '
'; } dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, $param); @@ -683,7 +830,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '
'; print '
'; - print '
'; + print '
'; print ''; // Date start - Date end @@ -749,126 +896,136 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print $form->formconfirm($_SERVER["PHP_SELF"]."?".($object->id > 0 ? "id=".$object->id : 'projectid='.$projectstatic->id).'&lineid='.GETPOST('lineid', 'int').($withproject ? '&withproject=1' : ''), $langs->trans("DeleteATimeSpent"), $langs->trans("ConfirmDeleteATimeSpent"), "confirm_delete", '', '', 1); } - // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array - $hookmanager->initHooks(array('tasktimelist')); + // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array + $hookmanager->initHooks(array('tasktimelist')); - // Definition of fields for list - $arrayfields = array(); - $arrayfields['t.task_date'] = array('label'=>$langs->trans("Date"), 'checked'=>1); - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - $arrayfields['t.task_ref'] = array('label'=>$langs->trans("RefTask"), 'checked'=>1); - $arrayfields['t.task_label'] = array('label'=>$langs->trans("LabelTask"), 'checked'=>1); - } - $arrayfields['author'] = array('label'=>$langs->trans("By"), 'checked'=>1); - $arrayfields['t.note'] = array('label'=>$langs->trans("Note"), 'checked'=>1); - $arrayfields['t.task_duration'] = array('label'=>$langs->trans("Duration"), 'checked'=>1); - $arrayfields['value'] = array('label'=>$langs->trans("Value"), 'checked'=>1, 'enabled'=>(empty($conf->salaries->enabled) ? 0 : 1)); - $arrayfields['valuebilled'] = array('label'=>$langs->trans("Billed"), 'checked'=>1, 'enabled'=>(((!empty($conf->global->PROJECT_HIDE_TASKS) || empty($conf->global->PROJECT_BILL_TIME_SPENT)) ? 0 : 1) && $projectstatic->usage_bill_time)); - // Extra fields - if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) - { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { - if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); - } - } - $arrayfields = dol_sort_array($arrayfields, 'position'); + // Definition of fields for list + $arrayfields = array(); + $arrayfields['t.task_date'] = array('label'=>$langs->trans("Date"), 'checked'=>1); + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + $arrayfields['t.task_ref'] = array('label'=>$langs->trans("RefTask"), 'checked'=>1); + $arrayfields['t.task_label'] = array('label'=>$langs->trans("LabelTask"), 'checked'=>1); + } + $arrayfields['author'] = array('label'=>$langs->trans("By"), 'checked'=>1); + $arrayfields['t.note'] = array('label'=>$langs->trans("Note"), 'checked'=>1); + $arrayfields['t.task_duration'] = array('label'=>$langs->trans("Duration"), 'checked'=>1); + $arrayfields['value'] = array('label'=>$langs->trans("Value"), 'checked'=>1, 'enabled'=>(empty($conf->salaries->enabled) ? 0 : 1)); + $arrayfields['valuebilled'] = array('label'=>$langs->trans("Billed"), 'checked'=>1, 'enabled'=>(((!empty($conf->global->PROJECT_HIDE_TASKS) || empty($conf->global->PROJECT_BILL_TIME_SPENT)) ? 0 : 1) && $projectstatic->usage_bill_time)); + // Extra fields + if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) + { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) + { + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + } + } + $arrayfields = dol_sort_array($arrayfields, 'position'); - $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($search_month > 0) $param .= '&search_month='.urlencode($search_month); - if ($search_year > 0) $param .= '&search_year='.urlencode($search_year); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_task_ref != '') $param .= '&search_task_ref='.urlencode($search_task_ref); - if ($search_task_label != '') $param .= '&search_task_label='.urlencode($search_task_label); - if ($search_note != '') $param .= '&search_note='.urlencode($search_note); - if ($search_duration != '') $param .= '&search_field2='.urlencode($search_duration); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - /* - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - */ - if ($id) $param .= '&id='.urlencode($id); - if ($projectid) $param .= '&projectid='.urlencode($projectid); - if ($withproject) $param .= '&withproject='.urlencode($withproject); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($search_month > 0) $param .= '&search_month='.urlencode($search_month); + if ($search_year > 0) $param .= '&search_year='.urlencode($search_year); + if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); + if ($search_task_ref != '') $param .= '&search_task_ref='.urlencode($search_task_ref); + if ($search_task_label != '') $param .= '&search_task_label='.urlencode($search_task_label); + if ($search_note != '') $param .= '&search_note='.urlencode($search_note); + if ($search_duration != '') $param .= '&search_field2='.urlencode($search_duration); + if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + /* + // Add $param from extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + */ + if ($id) $param .= '&id='.urlencode($id); + if ($projectid) $param .= '&projectid='.urlencode($projectid); + if ($withproject) $param .= '&withproject='.urlencode($withproject); - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - if ($action == 'editline') print ''; - elseif ($action == 'splitline') print ''; - elseif ($action == 'createtime' && $user->rights->projet->lire) print ''; - elseif ($massaction == 'generateinvoice' && $user->rights->facture->lire) print ''; - else print ''; - print ''; - print ''; - print ''; + print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + if ($action == 'editline') print ''; + elseif ($action == 'splitline') print ''; + elseif ($action == 'createtime' && $user->rights->projet->lire) print ''; + elseif ($massaction == 'generateinvoice' && $user->rights->facture->lire) print ''; + else print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - if ($massaction == 'generateinvoice') - { - //var_dump($_REQUEST); - print ''; + if ($massaction == 'generateinvoice') + { + //var_dump($_REQUEST); + print ''; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if ($conf->service->enabled) - { - print ''; - print ''; - print ''; - print ''; - } - /*print ''; - print ''; - print ''; - print '';*/ - print '
'; - print $langs->trans('DateInvoice'); - print ''; - print $form->selectDate('', '', '', '', '', '', 1, 1); - print '
'; - print $langs->trans('Mode'); - print ''; - $tmparray = array( - 'onelineperuser'=>'OneLinePerUser', - //'onelinepertask'=>'OneLinePerTask', - ); - print $form->selectarray('generateinvoicemode', $tmparray, 'onelineperuser', 0, 0, 0, '', 1); - print '
'; - print $langs->trans('ServiceToUseOnLines'); - print ''; - $form->select_produits('', 'productid', '1', 0, 0, 1, 2, '', 0, array(), 0, 'None', 0, 'maxwidth500'); - print '
'; - print $langs->trans('ValidateInvoices'); - print ''; - print $form->selectyesno('validate_invoices', 0, 1); - print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($conf->service->enabled) + { + print ''; + print ''; + print ''; + print ''; + } + print ''; + print ''; + print ''; + print ''; + /*print ''; + print ''; + print ''; + print '';*/ + print '
'; + print $langs->trans('DateInvoice'); + print ''; + print $form->selectDate('', '', '', '', '', '', 1, 1); + print '
'; + print $langs->trans('Mode'); + print ''; + $tmparray = array( + 'onelineperuser'=>'OneLinePerUser', + 'onelinepertask'=>'OneLinePerTask', + 'onelineperperiod'=>'OneLinePerPeriod', + ); + print $form->selectarray('generateinvoicemode', $tmparray, 'onelineperuser', 0, 0, 0, '', 1); + print '
'; + print $langs->trans('ServiceToUseOnLines'); + print ''; + $form->select_produits('', 'productid', '1', 0, 0, 1, 2, '', 0, array(), 0, 'None', 0, 'maxwidth500'); + print '
'; + print $langs->trans('InvoiceToUse'); + print ''; + $form->selectInvoice('invoice', '', 'invoiceid', 24, 0, $langs->trans('NewInvoice'), + 1, 0, 0, 'maxwidth500', '', 'all'); + print '
'; + print $langs->trans('ValidateInvoices'); + print ''; + print $form->selectyesno('validate_invoices', 0, 1); + print '
'; - print '
'; - print '
'; - print ' '; - print ''; - print '
'; - print '
'; - } + print '
'; + print '
'; + print ' '; + print ''; + print '
'; + print '
'; + } /* - * List of time spent + * List of time spent */ $tasks = array(); @@ -897,31 +1054,31 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $resql = $db->query($sql); - $nbtotalofrecords = $db->num_rows($resql); - if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 - { - $page = 0; - $offset = 0; - } + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 + { + $page = 0; + $offset = 0; + } } // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) { - $num = $nbtotalofrecords; + $num = $nbtotalofrecords; } else { - $sql .= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); - $resql = $db->query($sql); - if (!$resql) - { - dol_print_error($db); - exit; - } + $resql = $db->query($sql); + if (!$resql) + { + dol_print_error($db); + exit; + } - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); } if ($num >= 0) @@ -936,11 +1093,11 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) } else { - print ''."\n"; + print ''."\n"; - $title = $langs->trans("ListTaskTimeForTask"); + $title = $langs->trans("ListTaskTimeForTask"); - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, $linktocreatetime, '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, $linktocreatetime, '', $limit); } $i = 0; @@ -963,9 +1120,9 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) if ($action == 'createtime' && $user->rights->projet->lire) { print ''."\n"; - if (!empty($id)) print ''; + if (!empty($id)) print ''; - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; @@ -977,7 +1134,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print ''; if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print ''; + print ''; } print ''; print "\n"; @@ -994,9 +1151,9 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Task if (empty($id)) { - print ''; + print ''; } // Contributor @@ -1040,8 +1197,8 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Invoiced if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) { - print ''; + print ''; } print ''; + + print ''; + + if ($conf->global->TAKEPOS_SUPPLEMENTS) + { + print '\n"; + } } print '\n"; +// Color theme +print '\n"; + // Direct Payment print '\n"; +// Head Bar +/*print '\n"; +*/ + // Email template for send invoice print '
'.$langs->trans("ProgressDeclared").'
'; - $formproject->selectTasks(-1, GETPOST('taskid', 'int'), 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, ''); - print ''; + $formproject->selectTasks(-1, GETPOST('taskid', 'int'), 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, ''); + print ''; - print ''; + print ''; @@ -1065,16 +1222,16 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) if (!empty($moreforfilter)) { - print '
'; - print $moreforfilter; - print '
'; + print '
'; + print $moreforfilter; + print '
'; } $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields .= (is_array($arrayofmassactions) && count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); - print '
'; + print '
'; print ''."\n"; // Fields title search @@ -1088,23 +1245,23 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $formother->select_year($search_year, 'search_year', 1, 20, 5); print ''; } - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - if (!empty($arrayfields['t.task_ref']['checked'])) print ''; - if (!empty($arrayfields['t.task_label']['checked'])) print ''; - } - // Author - if (!empty($arrayfields['author']['checked'])) print ''; + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + if (!empty($arrayfields['t.task_ref']['checked'])) print ''; + if (!empty($arrayfields['t.task_label']['checked'])) print ''; + } + // Author + if (!empty($arrayfields['author']['checked'])) print ''; // Note - if (!empty($arrayfields['t.note']['checked'])) print ''; + if (!empty($arrayfields['t.note']['checked'])) print ''; // Duration - if (!empty($arrayfields['t.task_duration']['checked'])) print ''; + if (!empty($arrayfields['t.task_duration']['checked'])) print ''; // Value in main currency - if (!empty($arrayfields['value']['checked'])) print ''; - // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) print ''; + if (!empty($arrayfields['value']['checked'])) print ''; + // Value billed + if (!empty($arrayfields['valuebilled']['checked'])) print ''; - /* + /* // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; */ @@ -1120,26 +1277,26 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print ''."\n"; print ''; - if (!empty($arrayfields['t.task_date']['checked'])) print_liste_field_titre($arrayfields['t.task_date']['label'], $_SERVER['PHP_SELF'], 't.task_date,t.task_datehour,t.rowid', '', $param, '', $sortfield, $sortorder); - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - if (!empty($arrayfields['t.task_ref']['checked'])) print_liste_field_titre($arrayfields['t.task_ref']['label'], $_SERVER['PHP_SELF'], 'pt.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['t.task_label']['checked'])) print_liste_field_titre($arrayfields['t.task_label']['label'], $_SERVER['PHP_SELF'], 'pt.label', '', $param, '', $sortfield, $sortorder); - } - if (!empty($arrayfields['author']['checked'])) print_liste_field_titre($arrayfields['author']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['t.note']['checked'])) print_liste_field_titre($arrayfields['t.note']['label'], $_SERVER['PHP_SELF'], 't.note', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.task_date']['checked'])) print_liste_field_titre($arrayfields['t.task_date']['label'], $_SERVER['PHP_SELF'], 't.task_date,t.task_datehour,t.rowid', '', $param, '', $sortfield, $sortorder); + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + if (!empty($arrayfields['t.task_ref']['checked'])) print_liste_field_titre($arrayfields['t.task_ref']['label'], $_SERVER['PHP_SELF'], 'pt.ref', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.task_label']['checked'])) print_liste_field_titre($arrayfields['t.task_label']['label'], $_SERVER['PHP_SELF'], 'pt.label', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['author']['checked'])) print_liste_field_titre($arrayfields['author']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['t.note']['checked'])) print_liste_field_titre($arrayfields['t.note']['label'], $_SERVER['PHP_SELF'], 't.note', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['t.task_duration']['checked'])) print_liste_field_titre($arrayfields['t.task_duration']['label'], $_SERVER['PHP_SELF'], 't.task_duration', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['value']['checked'])) print_liste_field_titre($arrayfields['value']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['valuebilled']['checked'])) print_liste_field_titre($arrayfields['valuebilled']['label'], $_SERVER['PHP_SELF'], 'il.total_ht', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['value']['checked'])) print_liste_field_titre($arrayfields['value']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['valuebilled']['checked'])) print_liste_field_titre($arrayfields['valuebilled']['label'], $_SERVER['PHP_SELF'], 'il.total_ht', '', $param, '', $sortfield, $sortorder, 'center '); /* - // Extra fields + // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; */ - // Hook fields + // 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"], "", '', '', 'width="80"', $sortfield, $sortorder, 'center maxwidthsearch '); + $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"], "", '', '', 'width="80"', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; $tasktmp = new Task($db); @@ -1154,7 +1311,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $totalarray = array(); foreach ($tasks as $task_time) { - if ($i >= $limit) break; + if ($i >= $limit) break; print ''; @@ -1164,21 +1321,21 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) // Date if (!empty($arrayfields['t.task_date']['checked'])) { - print ''; - if (!$i) $totalarray['nbfield']++; + print ''; + if (!$i) $totalarray['nbfield']++; } // Task ref @@ -1187,102 +1344,109 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task { print ''; if (!$i) $totalarray['nbfield']++; } } // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - } + if (!empty($arrayfields['t.task_label']['checked'])) + { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + } - // User - if (!empty($arrayfields['author']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + // User + if (!empty($arrayfields['author']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Note - if (!empty($arrayfields['t.note']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - elseif ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } + if (!empty($arrayfields['t.note']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + elseif ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.task_duration'; - $totalarray['val']['t.task_duration'] += $task_time->task_duration; - if (!$i) $totalarray['totaldurationfield'] = $totalarray['nbfield']; - $totalarray['totalduration'] += $task_time->task_duration; - } + if (!empty($arrayfields['t.task_duration']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.task_duration'; + $totalarray['val']['t.task_duration'] += $task_time->task_duration; + if (!$i) $totalarray['totaldurationfield'] = $totalarray['nbfield']; + $totalarray['totalduration'] += $task_time->task_duration; + } // Value spent - if (!empty($arrayfields['value']['checked'])) - { + if (!empty($arrayfields['value']['checked'])) + { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totalvaluebilledfield'] = $totalarray['nbfield']; - $totalarray['totalvaluebilled'] += $valuebilled; - } + // Invoiced + if (!empty($arrayfields['valuebilled']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totalvaluebilledfield'] = $totalarray['nbfield']; + $totalarray['totalvaluebilled'] += $valuebilled; + } - /* - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - */ + /* + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + */ // Fields from hook $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$task_time); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - // Action column + // Action column print ''; - if (!$i) $totalarray['nbfield']++; + print ''; + if (!$i) $totalarray['nbfield']++; print "\n"; @@ -1385,298 +1549,298 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) { - print ''; + print ''; - // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { - print ''; - } + // Date + if (!empty($arrayfields['t.task_date']['checked'])) + { + print ''; + } - // Task ref - if (!empty($arrayfields['t.task_ref']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - print ''; - } - } + // Task ref + if (!empty($arrayfields['t.task_ref']['checked'])) + { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + } + } - // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - print ''; - } - } + // Task label + if (!empty($arrayfields['t.task_label']['checked'])) + { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + } + } - // User - if (!empty($arrayfields['author']['checked'])) - { - print ''; - } + // User + if (!empty($arrayfields['author']['checked'])) + { + print ''; + } - // Note - if (!empty($arrayfields['t.note']['checked'])) - { - print ''; - } - elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } + // Note + if (!empty($arrayfields['t.note']['checked'])) + { + print ''; + } + elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } - // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { - print ''; - } + // Time spent + if (!empty($arrayfields['t.task_duration']['checked'])) + { + print ''; + } - // Value spent - if (!empty($arrayfields['value']['checked'])) - { - print ''; - } + // Value spent + if (!empty($arrayfields['value']['checked'])) + { + print ''; + } - // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) - { - print ''; - } + // Value billed + if (!empty($arrayfields['valuebilled']['checked'])) + { + print ''; + } - /* - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - */ + /* + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + */ - // Fields from hook - $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$task_time); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$task_time); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - // Action column - print ''; + // Action column + print ''; - print "\n"; + print "\n"; - // Line for second dispatching + // Line for second dispatching - print ''; + print ''; - // Date - if (!empty($arrayfields['t.task_date']['checked'])) - { - print ''; - } + // Date + if (!empty($arrayfields['t.task_date']['checked'])) + { + print ''; + } - // Task ref - if (!empty($arrayfields['t.task_ref']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - print ''; - } - } + // Task ref + if (!empty($arrayfields['t.task_ref']['checked'])) + { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + } + } - // Task label - if (!empty($arrayfields['t.task_label']['checked'])) - { - if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task - { - print ''; - } - } + // Task label + if (!empty($arrayfields['t.task_label']['checked'])) + { + if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + } + } - // User - if (!empty($arrayfields['author']['checked'])) - { - print ''; - } + // User + if (!empty($arrayfields['author']['checked'])) + { + print ''; + } - // Note - if (!empty($arrayfields['t.note']['checked'])) - { - print ''; - } - elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } + // Note + if (!empty($arrayfields['t.note']['checked'])) + { + print ''; + } + elseif ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } - // Time spent - if (!empty($arrayfields['t.task_duration']['checked'])) - { - print ''; - } + // Time spent + if (!empty($arrayfields['t.task_duration']['checked'])) + { + print ''; + } - // Value spent - if (!empty($arrayfields['value']['checked'])) - { - print ''; - } + // Value spent + if (!empty($arrayfields['value']['checked'])) + { + print ''; + } - // Value billed - if (!empty($arrayfields['valuebilled']['checked'])) - { - print ''; - } + // Value billed + if (!empty($arrayfields['valuebilled']['checked'])) + { + print ''; + } - /* - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - */ + /* + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + */ - // Fields from hook - $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$task_time); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$task_time); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - // Action column - print ''; + // Action column + print ''; - print "\n"; + print "\n"; } $i++; diff --git a/htdocs/public/agenda/agendaexport.php b/htdocs/public/agenda/agendaexport.php index 9b76f2b90b3..a94b0659950 100644 --- a/htdocs/public/agenda/agendaexport.php +++ b/htdocs/public/agenda/agendaexport.php @@ -34,8 +34,10 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't ne if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (! defined('NOLOGIN')) define("NOLOGIN", 1); // This means this output page does not require to be logged. if (! defined('NOCSRFCHECK')) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -// C'est un wrapper, donc header vierge + +// It's a wrapper, so empty header /** * Header function @@ -72,7 +74,7 @@ if (GETPOST("format", 'alpha')) $format=GETPOST("format", 'apha'); if (GETPOST("type", 'apha')) $type=GETPOST("type", 'alpha'); $filters=array(); -if (GETPOST("year", 'int')) $filters['year']=GETPOST("year", 'int'); +if (GETPOST("year", 'int')) $filters['year']=GETPOST("year", 'int'); if (GETPOST("id", 'int')) $filters['id']=GETPOST("id", 'int'); if (GETPOST("idfrom", 'int')) $filters['idfrom']=GETPOST("idfrom", 'int'); if (GETPOST("idto", 'int')) $filters['idto']=GETPOST("idto", 'int'); @@ -157,10 +159,12 @@ $agenda=new ActionComm($db); $cachedelay=0; if (! empty($conf->global->MAIN_AGENDA_EXPORT_CACHE)) $cachedelay=$conf->global->MAIN_AGENDA_EXPORT_CACHE; +$exportholidays = GETPOST('includeholidays', 'int'); + // Build file if ($format == 'ical' || $format == 'vcal') { - $result=$agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters); + $result=$agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholidays); if ($result >= 0) { $attachment = true; @@ -195,7 +199,7 @@ if ($format == 'ical' || $format == 'vcal') if ($format == 'rss') { - $result=$agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters); + $result=$agenda->build_exportfile($format, $type, $cachedelay, $filename, $filters, $exportholidays); if ($result >= 0) { $attachment = false; diff --git a/htdocs/public/demo/index.php b/htdocs/public/demo/index.php index 7a962a15b79..c470055dbce 100644 --- a/htdocs/public/demo/index.php +++ b/htdocs/public/demo/index.php @@ -24,74 +24,74 @@ * \brief Entry page to access demo */ -define("NOLOGIN", 1); // This means this output page does not require to be logged. -define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. +define("NOLOGIN", 1); // This means this output page does not require to be logged. +define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. require '../../main.inc.php'; require_once '../../core/lib/functions2.lib.php'; $langs->loadLangs(array("main", "install", "other")); -$conf->dol_hide_topmenu=GETPOST('dol_hide_topmenu', 'int'); -$conf->dol_hide_leftmenu=GETPOST('dol_hide_leftmenu', 'int'); -$conf->dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen', 'int'); -$conf->dol_no_mouse_hover=GETPOST('dol_no_mouse_hover', 'int'); -$conf->dol_use_jmobile=GETPOST('dol_use_jmobile', 'int'); +$conf->dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int'); +$conf->dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int'); +$conf->dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int'); +$conf->dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int'); +$conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); // Security check global $dolibarr_main_demo; if (empty($dolibarr_main_demo)) accessforbidden('Parameter dolibarr_main_demo must be defined in conf file with value "default login,default pass" to enable the demo entry page', 0, 0, 1); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$res=$hookmanager->initHooks(array('demo')); +$res = $hookmanager->initHooks(array('demo')); -$demoprofiles=array(); -$alwayscheckedmodules=array(); -$alwaysuncheckedmodules=array(); -$alwayshiddencheckedmodules=array(); -$alwayshiddenuncheckedmodules=array(); +$demoprofiles = array(); +$alwayscheckedmodules = array(); +$alwaysuncheckedmodules = array(); +$alwayshiddencheckedmodules = array(); +$alwayshiddenuncheckedmodules = array(); -$url=''; -$url.=($url?'&':'').($conf->dol_hide_topmenu?'dol_hide_topmenu='.$conf->dol_hide_topmenu:''); -$url.=($url?'&':'').($conf->dol_hide_leftmenu?'dol_hide_leftmenu='.$conf->dol_hide_leftmenu:''); -$url.=($url?'&':'').($conf->dol_optimize_smallscreen?'dol_optimize_smallscreen='.$conf->dol_optimize_smallscreen:''); -$url.=($url?'&':'').($conf->dol_no_mouse_hover?'dol_no_mouse_hover='.$conf->dol_no_mouse_hover:''); -$url.=($url?'&':'').($conf->dol_use_jmobile?'dol_use_jmobile='.$conf->dol_use_jmobile:''); -$url=DOL_URL_ROOT.'/index.php'.($url?'?'.$url:''); +$url = ''; +$url .= ($url ? '&' : '').($conf->dol_hide_topmenu ? 'dol_hide_topmenu='.$conf->dol_hide_topmenu : ''); +$url .= ($url ? '&' : '').($conf->dol_hide_leftmenu ? 'dol_hide_leftmenu='.$conf->dol_hide_leftmenu : ''); +$url .= ($url ? '&' : '').($conf->dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$conf->dol_optimize_smallscreen : ''); +$url .= ($url ? '&' : '').($conf->dol_no_mouse_hover ? 'dol_no_mouse_hover='.$conf->dol_no_mouse_hover : ''); +$url .= ($url ? '&' : '').($conf->dol_use_jmobile ? 'dol_use_jmobile='.$conf->dol_use_jmobile : ''); +$url = DOL_URL_ROOT.'/index.php'.($url ? '?'.$url : ''); $tmpaction = 'view'; -$parameters=array(); -$object=new stdClass(); -$reshook=$hookmanager->executeHooks('addDemoProfile', $parameters, $object, $tmpaction); // Note that $action and $object may have been modified by some hooks -$error=$hookmanager->error; $errors=$hookmanager->errors; +$parameters = array(); +$object = new stdClass(); +$reshook = $hookmanager->executeHooks('addDemoProfile', $parameters, $object, $tmpaction); // Note that $action and $object may have been modified by some hooks +$error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { - $demoprofiles=array( - array('default'=>'1', 'key'=>'profdemoservonly','label'=>'DemoCompanyServiceOnly', + $demoprofiles = array( + array('default'=>'1', 'key'=>'profdemoservonly', 'label'=>'DemoCompanyServiceOnly', 'disablemodules'=>'adherent,barcode,bom,cashdesk,don,expedition,externalsite,ftp,incoterm,mailmanspip,margin,mrp,prelevement,product,productbatch,stock,takepos', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot8.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-service.jpg', 'url'=>$url ), - array('default'=>'0', 'key'=>'profmanufacture','label'=>'DemoCompanyManufacturing', + array('default'=>'0', 'key'=>'profmanufacture', 'label'=>'DemoCompanyManufacturing', 'disablemodules'=>'adherent,contrat,don,externalsite,ficheinter,ftp,mailmanspip,prelevement,service', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-manufacturing.jpg', 'url'=>$url ), - array('default'=>'0', 'key'=>'profdemoprodstock','label'=>'DemoCompanyProductAndStocks', + array('default'=>'0', 'key'=>'profdemoprodstock', 'label'=>'DemoCompanyProductAndStocks', 'disablemodules'=>'adherent,bom,contrat,don,externalsite,ficheinter,ftp,mailmanspip,mrp,prelevement,service', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot2.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-product.jpg', 'url'=>$url ), - array('default'=>'0', 'key'=>'profdemofun2','label'=>'DemoFundation2', + array('default'=>'0', 'key'=>'profdemofun2', 'label'=>'DemoFundation2', 'disablemodules'=>'barcode,cashdesk,bom,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,ftp,incoterm,mailmanspip,margin,mrp,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax,takepos', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot6.png', 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-foundation.jpg', 'url'=>$url ), // All demo profile - array('default'=>'0', 'key'=>'profdemoall','label'=>'ChooseYourDemoProfilMore', + array('default'=>'0', 'key'=>'profdemoall', 'label'=>'ChooseYourDemoProfilMore', 'disablemodules'=>'adherent,cashdesk,don,externalsite,mailmanspip', //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot9.png' 'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-all.jpg' @@ -100,21 +100,21 @@ if (empty($reshook)) // Visible - $alwayscheckedmodules=array('barcode','bookmark','categorie','externalrss','fckeditor','geoipmaxmind','gravatar','memcached','syslog','user','webservices'); // Technical module we always want - $alwaysuncheckedmodules=array('dav','dynamicprices','incoterm','loan','multicurrency','paybox','paypal','stripe','google','printing','scanner','skype','website'); // Module we dont want by default + $alwayscheckedmodules = array('barcode', 'bookmark', 'categorie', 'externalrss', 'fckeditor', 'geoipmaxmind', 'gravatar', 'memcached', 'syslog', 'user', 'webservices'); // Technical module we always want + $alwaysuncheckedmodules = array('dav', 'dynamicprices', 'incoterm', 'loan', 'multicurrency', 'paybox', 'paypal', 'stripe', 'google', 'printing', 'scanner', 'skype', 'website'); // Module we dont want by default // Not visible - $alwayshiddencheckedmodules=array('accounting','api','barcode','blockedlog','bookmark','clicktodial','comptabilite','cron','document','domain','externalrss','externalsite','fckeditor','geoipmaxmind','gravatar','label','ldap', - 'mailmanspip','notification','oauth','syslog','user','webservices','workflow', + $alwayshiddencheckedmodules = array('accounting', 'api', 'barcode', 'blockedlog', 'bookmark', 'clicktodial', 'comptabilite', 'cron', 'document', 'domain', 'externalrss', 'externalsite', 'fckeditor', 'geoipmaxmind', 'gravatar', 'label', 'ldap', + 'mailmanspip', 'notification', 'oauth', 'syslog', 'user', 'webservices', 'workflow', // Extended modules - 'memcached','numberwords','zipautofillfr'); - $alwayshiddenuncheckedmodules=array('dav','debugbar','emailcollector','ftp','hrm','modulebuilder','printing','webservicesclient', + 'memcached', 'numberwords', 'zipautofillfr'); + $alwayshiddenuncheckedmodules = array('dav', 'debugbar', 'emailcollector', 'ftp', 'hrm', 'modulebuilder', 'printing', 'webservicesclient', // Extended modules - 'awstats','bittorrent','bootstrap','cabinetmed','cmcic','concatpdf','customfield','deplacement','dolicloud','filemanager','lightbox','mantis','monitoring','moretemplates','multicompany','nltechno','numberingpack','openstreetmap', - 'ovh','phenix','phpsysinfo','pibarcode','postnuke','selectbank','skincoloreditor','submiteverywhere','survey','thomsonphonebook','topten','tvacerfa','voyage','webcalendar','webmail'); + 'awstats', 'bittorrent', 'bootstrap', 'cabinetmed', 'cmcic', 'concatpdf', 'customfield', 'deplacement', 'dolicloud', 'filemanager', 'lightbox', 'mantis', 'monitoring', 'moretemplates', 'multicompany', 'nltechno', 'numberingpack', 'openstreetmap', + 'ovh', 'phenix', 'phpsysinfo', 'pibarcode', 'postnuke', 'selectbank', 'skincoloreditor', 'submiteverywhere', 'survey', 'thomsonphonebook', 'topten', 'tvacerfa', 'voyage', 'webcalendar', 'webmail'); } // Search modules -$dirlist=$conf->file->dol_document_root; +$dirlist = $conf->file->dol_document_root; // Search modules dirs @@ -132,13 +132,13 @@ $j = 0; // j is module number. Automatically affected if module number not defin foreach ($modulesdir as $dir) { // Charge tableaux modules, nom, numero, orders depuis repertoire dir - $handle=@opendir($dir); + $handle = @opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { //print "$i ".$file."\n
"; - if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') + if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') { $modName = substr($file, 0, dol_strlen($file) - 10); @@ -158,25 +158,25 @@ foreach ($modulesdir as $dir) $j = 1000 + $i; } - $modulequalified=1; + $modulequalified = 1; // We discard modules according to features level (PS: if module is activated we always show it) $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod))); - if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) $modulequalified=0; - if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) $modulequalified=0; + if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) $modulequalified = 0; + if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) $modulequalified = 0; if ($modulequalified) { $modules[$i] = $objMod; - $filename[$i]= $modName; - $orders[$i] = $objMod->family."_".$j; // Tri par famille puis numero module + $filename[$i] = $modName; + $orders[$i] = $objMod->family."_".$j; // Tri par famille puis numero module //print "x".$modName." ".$orders[$i]."\n
"; $dirmod[$i] = $dirroot; $j++; $i++; } } - catch(Exception $e) + catch (Exception $e) { dol_syslog("Failed to load ".$dir.$file." ".$e->getMessage(), LOG_ERR); } @@ -197,7 +197,7 @@ asort($orders); if (GETPOST('action', 'aZ09') == 'gotodemo') // Action run when we click on "Start" after selection modules { //print 'ee'.GETPOST("demochoice"); - $disablestring=''; + $disablestring = ''; // If we disable modules using a profile choice if (GETPOST("demochoice")) { @@ -205,27 +205,27 @@ if (GETPOST('action', 'aZ09') == 'gotodemo') // Action run when we click on { if ($profilearray['key'] == GETPOST("demochoice")) { - $disablestring=$profilearray['disablemodules']; + $disablestring = $profilearray['disablemodules']; break; } } } // If we disable modules using personalized list - foreach($modules as $val) + foreach ($modules as $val) { - $modulekeyname=strtolower($val->name); - if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && ! in_array($modulekeyname, $alwayscheckedmodules)) + $modulekeyname = strtolower($val->name); + if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && !in_array($modulekeyname, $alwayscheckedmodules)) { - $disablestring.=$modulekeyname.','; - if ($modulekeyname=='propale') $disablestring.='propal,'; + $disablestring .= $modulekeyname.','; + if ($modulekeyname == 'propale') $disablestring .= 'propal,'; } } // Do redirect to login page if ($disablestring) { - if (GETPOST('urlfrom')) $url.=(preg_match('/\?/', $url)?'&':'?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha')); - $url.=(preg_match('/\?/', $url)?'&':'?').'disablemodules='.$disablestring; + if (GETPOST('urlfrom')) $url .= (preg_match('/\?/', $url) ? '&' : '?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha')); + $url .= (preg_match('/\?/', $url) ? '&' : '?').'disablemodules='.$disablestring; //var_dump($url);exit; header("Location: ".$url); exit; @@ -237,11 +237,11 @@ if (GETPOST('action', 'aZ09') == 'gotodemo') // Action run when we click on * View */ -$head=''; -$head.=''."\n"; -$head.=''."\n"; +$head = ''; +$head .= ''."\n"; +$head .= ''."\n"; -$head.=' +$head .= ' ' . "\n"; + print ''."\n"; print '
'; print '
'; - print $langs->trans("ThirdPartyType") . ':     '; + print $langs->trans("ThirdPartyType").':     '; print '
'; print ''; print '     '; print '
'; } @@ -2572,7 +2569,7 @@ else if ($object->prospect || $object->client || (!$object->fournisseur && !empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) { print ''; print '"; } @@ -2580,7 +2577,7 @@ else if ($object->fournisseur) { print ''; print '"; } } diff --git a/htdocs/societe/class/companypaymentmode.class.php b/htdocs/societe/class/companypaymentmode.class.php index 5fe072cc826..6cd09ce49c4 100644 --- a/htdocs/societe/class/companypaymentmode.class.php +++ b/htdocs/societe/class/companypaymentmode.class.php @@ -43,9 +43,10 @@ class CompanyPaymentMode extends CommonObject public $table_element = 'societe_rib'; /** - * @var int Does companypaymentmode support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table */ - public $ismultientitymanaged = 2; + public $ismultientitymanaged = 'fk_soc@societe'; /** * @var int Does companypaymentmode support extrafields ? 0=No, 1=Yes @@ -114,6 +115,7 @@ class CompanyPaymentMode extends CommonObject 'preapproval_key' =>array('type'=>'varchar(255)', 'label'=>'Preapproval key', 'enabled'=>1, 'visible'=>-2, 'position'=>160), 'total_amount_of_all_payments' =>array('type'=>'double(24,8)', 'label'=>'Total amount of all payments', 'enabled'=>1, 'visible'=>-2, 'position'=>165), 'stripe_card_ref' =>array('type'=>'varchar(128)', 'label'=>'Stripe card ref', 'enabled'=>1, 'visible'=>-2, 'position'=>170), + 'stripe_account' =>array('type'=>'varchar(128)', 'label'=>'Stripe account', 'enabled'=>1, 'visible'=>-2, 'position'=>171), 'status' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>175), 'starting_date' =>array('type'=>'date', 'label'=>'Starting date', 'enabled'=>1, 'visible'=>-2, 'position'=>180), 'ending_date' =>array('type'=>'date', 'label'=>'Ending date', 'enabled'=>1, 'visible'=>-2, 'position'=>185), @@ -165,6 +167,7 @@ class CompanyPaymentMode extends CommonObject public $preapproval_key; public $total_amount_of_all_payments; public $stripe_card_ref; + public $stripe_account; /** * @var int Status @@ -446,7 +449,7 @@ class CompanyPaymentMode extends CommonObject $this->db->begin(); - $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0"; + $sql2 = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET default_rib = 0, tms = tms"; $sql2.= " WHERE default_rib <> 0 AND fk_soc = ".$obj->fk_soc; if ($type) $sql2.= " AND type = '".$this->db->escape($type)."'"; dol_syslog(get_class($this).'::setAsDefault', LOG_DEBUG); diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 6f9b9ad26b8..08416ed8842 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -125,23 +125,99 @@ class Societe extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields = array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'), - 'nom' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'), - 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20), - 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60), - 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61), - 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500), - 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), - //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502), - 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510), - 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), - //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1, 'position'=>1000), + public $fields=array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30), + 'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35), + 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>45), + 'ref_int' =>array('type'=>'varchar(60)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'code_client' =>array('type'=>'varchar(24)', 'label'=>'Code client', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'Code fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'code_compta' =>array('type'=>'varchar(24)', 'label'=>'Code compta', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'Code compta fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>70), + 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80), + 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85), + 'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + 'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100), + 'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105), + 'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + 'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115), + 'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + /*'skype' =>array('type'=>'varchar(255)', 'label'=>'Skype', 'enabled'=>1, 'visible'=>-1, 'position'=>125), + 'whatsapp' =>array('type'=>'varchar(255)', 'label'=>'Whatsapp', 'enabled'=>1, 'visible'=>-1, 'position'=>130), + 'linkedin' =>array('type'=>'varchar(255)', 'label'=>'Linkedin', 'enabled'=>1, 'visible'=>-1, 'position'=>135), + 'youtube' =>array('type'=>'varchar(255)', 'label'=>'Youtube', 'enabled'=>1, 'visible'=>-1, 'position'=>140), + 'googleplus' =>array('type'=>'varchar(255)', 'label'=>'Googleplus', 'enabled'=>1, 'visible'=>-1, 'position'=>145), + 'snapchat' =>array('type'=>'varchar(255)', 'label'=>'Snapchat', 'enabled'=>1, 'visible'=>-1, 'position'=>150), + 'instagram' =>array('type'=>'varchar(255)', 'label'=>'Instagram', 'enabled'=>1, 'visible'=>-1, 'position'=>155), + 'facebook' =>array('type'=>'varchar(255)', 'label'=>'Facebook', 'enabled'=>1, 'visible'=>-1, 'position'=>160), + 'twitter' =>array('type'=>'varchar(255)', 'label'=>'Twitter', 'enabled'=>1, 'visible'=>-1, 'position'=>165),*/ + 'fk_effectif' =>array('type'=>'integer', 'label'=>'Fk effectif', 'enabled'=>1, 'visible'=>-1, 'position'=>170), + 'fk_typent' =>array('type'=>'integer', 'label'=>'Fk typent', 'enabled'=>1, 'visible'=>-1, 'position'=>175), + 'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'Fk forme juridique', 'enabled'=>1, 'visible'=>-1, 'position'=>180), + 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Fk currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185), + 'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200), + 'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205), + 'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206), + 'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207), + 'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210), + 'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'fk_stcomm' =>array('type'=>'integer', 'label'=>'Fk stcomm', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220), + 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225), + 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230), + 'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>'$conf->global->SOCIETE_USEPREFIX', 'visible'=>-1, 'position'=>235), + 'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240), + 'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245), + 'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250), + 'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255), + 'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260), + 'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265), + 'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270), + 'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275), + 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280), + //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1), + //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1), + 'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295), + 'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300), + 'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305), + 'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1), + 'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1), + 'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1), + 'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>325), + 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330), + 'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335), + 'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340), + 'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345), + 'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350), + 'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355), + 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360), + 'price_level' =>array('type'=>'integer', 'label'=>'Price level', 'enabled'=>'$conf->global->PRODUIT_MULTIPRICES || $conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES', 'visible'=>-1, 'position'=>365), + 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370), + 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375), + 'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405), + 'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410), + 'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435), + 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445), + 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>450), + 'fk_entrepot' =>array('type'=>'integer', 'label'=>'Fk entrepot', 'enabled'=>1, 'visible'=>-1, 'position'=>455), + 'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400), + 'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401), + 'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000), ); - /** * @var int Entity */ @@ -801,7 +877,8 @@ class Societe extends CommonObject $contact->firstname = $this->firstname; $contact->civility_id = $this->civility_id; $contact->socid = $this->id; // fk_soc - $contact->statut = 1; + $contact->statut = 1; // deprecated + $contact->status = 1; $contact->priv = 0; $contact->country_id = $this->country_id; $contact->state_id = $this->state_id; @@ -2003,7 +2080,7 @@ class Societe extends CommonObject $reparray = array(); - $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.office_phone, u.job, u.email, u.statut, u.entity, u.photo"; + $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.office_phone, u.job, u.email, u.statut as status, u.entity, u.photo"; $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u"; if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { @@ -2034,7 +2111,8 @@ class Societe extends CommonObject $reparray[$i]['email'] = $obj->email; $reparray[$i]['phone'] = $obj->office_phone; $reparray[$i]['job'] = $obj->job; - $reparray[$i]['statut'] = $obj->statut; + $reparray[$i]['statut'] = $obj->status; // deprecated + $reparray[$i]['status'] = $obj->status; $reparray[$i]['entity'] = $obj->entity; $reparray[$i]['login'] = $obj->login; $reparray[$i]['photo'] = $obj->photo; @@ -2492,7 +2570,7 @@ class Societe extends CommonObject $contact_property = array(); - $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname"; + $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople"; $sql .= " WHERE fk_soc = ".$this->id; $sql .= " ORDER BY lastname, firstname"; @@ -2518,7 +2596,7 @@ class Societe extends CommonObject else $property = $obj->$mode; // Show all contact. If hidedisabled is 1, showonly contacts with status = 1 - if ($obj->statut == 1 || empty($hidedisabled)) + if ($obj->status == 1 || empty($hidedisabled)) { if (empty($property)) { @@ -3637,6 +3715,15 @@ class Societe extends CommonObject $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL; $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX; $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB; + + // Social networks + $this->facebook_url = empty($conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_FACEBOOK_URL; + $this->twitter_url = empty($conf->global->MAIN_INFO_SOCIETE_TWITTER_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TWITTER_URL; + $this->linkedin_url = empty($conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LINKEDIN_URL; + $this->instagram_url = empty($conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_INSTAGRAM_URL; + $this->youtube_url = empty($conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_YOUTUBE_URL; + $this->github_url = empty($conf->global->MAIN_INFO_SOCIETE_GITHUB_URL) ? '' : $conf->global->MAIN_INFO_SOCIETE_GITHUB_URL; + // Id prof generiques $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN; $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET; @@ -3770,6 +3857,7 @@ class Societe extends CommonObject /** * Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases). + * Table c_revenuestamp contains the country and value of stamp per invoice. * * @return boolean true or false */ @@ -3859,7 +3947,7 @@ class Societe extends CommonObject * @param int|string $status Id or code for prospection status * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto * @param string $label Label to use for status for added status - * @return string Libelle du statut + * @return string Label of prospection status */ public function LibProspCommStatut($status, $mode = 0, $label = '') { @@ -3932,7 +4020,7 @@ class Societe extends CommonObject $table = 'propal'; if ($mode == 'supplier') $table = 'supplier_proposal'; - $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f"; + $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f"; $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('supplier_proposal').")"; @@ -3950,7 +4038,7 @@ class Societe extends CommonObject while ($obj = $this->db->fetch_object($resql)) { $outstandingTotal += $obj->total_ht; $outstandingTotalIncTax += $obj->total_ttc; - if ($obj->fk_statut != 0) // Not a draft + if ($obj->status != 0) // Not a draft { $outstandingOpened += $obj->total_ttc; } @@ -3972,7 +4060,7 @@ class Societe extends CommonObject $table = 'commande'; if ($mode == 'supplier') $table = 'commande_fournisseur'; - $sql = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f"; + $sql = "SELECT rowid, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f"; $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('supplier_order').")"; @@ -3990,7 +4078,7 @@ class Societe extends CommonObject while ($obj = $this->db->fetch_object($resql)) { $outstandingTotal += $obj->total_ht; $outstandingTotalIncTax += $obj->total_ttc; - if ($obj->fk_statut != 0) // Not a draft + if ($obj->status != 0) // Not a draft { $outstandingOpened += $obj->total_ttc; } @@ -4019,8 +4107,8 @@ class Societe extends CommonObject $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); */ - if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, type, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; - else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; + if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; + else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f"; $sql .= " WHERE fk_soc = ".$this->id; if ($mode == 'supplier') { $sql .= " AND entity IN (".getEntity('facture_fourn').")"; @@ -4048,18 +4136,18 @@ class Societe extends CommonObject while ($obj = $this->db->fetch_object($resql)) { $tmpobject->id = $obj->rowid; - if ($obj->fk_statut != $tmpobject::STATUS_DRAFT // Not a draft - && !($obj->fk_statut == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice + if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft + && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice ) { $outstandingTotal += $obj->total_ht; $outstandingTotalIncTax += $obj->total_ttc; } if ($obj->paye == 0 - && $obj->fk_statut != $tmpobject::STATUS_DRAFT // Not a draft - && $obj->fk_statut != $tmpobject::STATUS_ABANDONED // Not abandonned - && $obj->fk_statut != $tmpobject::STATUS_CLOSED) // Not classified as paid - //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason + && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft + && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned + && $obj->status != $tmpobject::STATUS_CLOSED) // Not classified as paid + //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason { $paiement = $tmpobject->getSommePaiement(); $creditnotes = $tmpobject->getSumCreditNotesUsed(); @@ -4097,8 +4185,8 @@ class Societe extends CommonObject /** * Return the label of the customer/prospect status * - * @param int $status Id statut - * @return string Libelle du statut + * @param int $status Id of prospection status + * @return string Label of prospection status */ public function LibCustProspStatut($status) { diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index 21602dae3c4..b4c91a3c04d 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -194,13 +194,13 @@ if (empty($reshook)) if ($action == 'updatecard') { // Modification - if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('cardnumber', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha') || !GETPOST('cvn', 'alpha')) + if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) { if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); if (!GETPOST('proprio', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); - if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); + //if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); - if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); + //if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); $action = 'createcard'; $error++; } @@ -220,6 +220,10 @@ if (empty($reshook)) $companypaymentmode->cvn = GETPOST('cvn', 'alpha'); $companypaymentmode->country_code = $object->country_code; + if (GETPOST('stripe_card_ref', 'alpha') && GETPOST('stripe_card_ref', 'alpha') != $companypaymentmode->stripe_card_ref) { + // If we set a stripe value that is different than previous one, we also set the stripe account + $companypaymentmode->stripe_account = $stripecu.'@'.$site_account; + } $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref', 'alpha'); $result = $companypaymentmode->update($user); @@ -346,13 +350,13 @@ if (empty($reshook)) { $error = 0; - if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('cardnumber', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha') || !GETPOST('cvn', 'alpha')) + if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) { if (!GETPOST('label', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); if (!GETPOST('proprio', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors'); - if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); + //if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors'); if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors'); - if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); + //if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors'); $action = 'createcard'; $error++; } @@ -377,6 +381,10 @@ if (empty($reshook)) $companypaymentmode->country_code = $object->country_code; $companypaymentmode->status = $servicestatus; + if (GETPOST('stripe_card_ref', 'alpha')) { + // If we set a stripe value, we also set the stripe account + $companypaymentmode->stripe_account = $stripecu.'@'.$site_account; + } $companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref', 'alpha'); $db->begin(); @@ -574,7 +582,7 @@ if (empty($reshook)) } $resql = $db->query($sql); - $num = $db->num_rows($resql); // Note: $num is always 0 on an update and delete, it is defined for select only. + $num = $db->num_rows($resql); // Note: $num is always 0 on an update and delete, it is defined for select only. if (!empty($newcu)) { if (empty($num)) { @@ -858,7 +866,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' $permissiontowrite = $user->rights->societe->creer; // Stripe customer key 'cu_....' stored into llx_societe_account print '\n"; - } - $db->free($resql); - } - else - { - dol_print_error($db); - } - - - // Bouton Enregistrer - if ($action != 'add_paiement') - { - $checkboxlabel = $langs->trans("ClosePaidInvoicesAutomatically"); - if ($facture->type == 2) $checkboxlabel = $langs->trans("ClosePaidCreditNotesAutomatically"); - $buttontitle = $langs->trans('ToMakePayment'); - if ($facture->type == 2) $buttontitle = $langs->trans('ToMakePaymentBack'); - - print '
'; - print ' '.$checkboxlabel; - /*if (! empty($conf->prelevement->enabled)) - { - $langs->load("withdrawals"); - if (! empty($conf->global->WITHDRAW_DISABLE_AUTOCREATE_ONPAYMENTS)) print '
'.$langs->trans("IfInvoiceNeedOnWithdrawPaymentWontBeClosed"); - }*/ - print '


'; - print '
'; - } - - // Form to confirm payment - if ($action == 'add_paiement') - { - $preselectedchoice = $addwarning ? 'no' : 'yes'; - - print '
'; - if (!empty($totalpayment)) { - $text = $langs->trans('ConfirmCustomerPayment', $totalpayment, $langs->trans("Currency".$conf->currency)); - } - if (!empty($multicurrency_totalpayment)) { - $text .= '
'.$langs->trans('ConfirmCustomerPayment', $multicurrency_totalpayment, $langs->trans("paymentInInvoiceCurrency")); - } - if (GETPOST('closepaidinvoices')) - { - $text .= '
'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed"); - print ''; - } - print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type, $langs->trans('ReceivedCustomersPayments'), $text, 'confirm_paiement', $formquestion, $preselectedchoice); - } - - print "\n"; - } -} - - -/** - * Show list of payments - */ - -if (!GETPOST('action')) -{ - if ($page == -1 || empty($page)) $page = 0; - $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; - $offset = $limit * $page; - - if (!$sortorder) $sortorder = 'DESC'; - if (!$sortfield) $sortfield = 'p.datep'; - - $sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.ref'; - $sql .= ', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p, '.MAIN_DB_PREFIX.'facture as f, '.MAIN_DB_PREFIX.'c_paiement as c'; - $sql .= ' WHERE p.fk_facture = f.rowid AND p.fk_paiement = c.id'; - $sql .= ' AND f.entity IN ('.getEntity('invoice').")"; - if ($socid) - { - $sql .= ' AND f.fk_soc = '.$socid; - } - - $sql .= ' ORDER BY '.$sortfield.' '.$sortorder; - $sql .= $db->plimit($limit + 1, $offset); - $resql = $db->query($sql); - - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - - print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num); - print '
'.$form->select_dolusers(($search_user > 0 ? $search_user : -1), 'search_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200').''.$form->select_dolusers(($search_user > 0 ? $search_user : -1), 'search_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200').''.$form->selectyesno('search_valuebilled', $search_valuebilled, 1, false, 1).''.$form->selectyesno('search_valuebilled', $search_valuebilled, 1, false, 1).'
'; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { - print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); - } - else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); - } - else - { - print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); - } - print ''; + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($task_time->task_date_withhour)) + { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); + } + else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } + else + { + print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); + } + print ''; - $tasktmp->id = $task_time->fk_task; - $tasktmp->ref = $task_time->ref; - $tasktmp->label = $task_time->label; - print $tasktmp->getNomUrl(1, 'withproject', 'time'); + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + $formproject->selectTasks(-1, GETPOST('taskid', 'int') ?GETPOST('taskid', 'int') : $task_time->fk_task, 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, ''); + } + else + { + $tasktmp->id = $task_time->fk_task; + $tasktmp->ref = $task_time->ref; + $tasktmp->label = $task_time->label; + print $tasktmp->getNomUrl(1, 'withproject', 'time'); + } print ''; - print $task_time->label; - print ''; + print $task_time->label; + print ''; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); - $contactsoftask = $object->getListContactId('internal'); - if (!in_array($task_time->fk_user, $contactsoftask)) { - $contactsoftask[] = $task_time->fk_user; - } - if (count($contactsoftask) > 0) { - print img_object('', 'user', 'class="hideonsmartphone"'); - print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, '', 0, '', $contactsoftask); - } else { - print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); - } - } - else - { - $userstatic->id = $task_time->fk_user; - $userstatic->lastname = $task_time->lastname; - $userstatic->firstname = $task_time->firstname; - $userstatic->photo = $task_time->photo; - $userstatic->statut = $task_time->user_status; - print $userstatic->getNomUrl(-1); - } - print ''; + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($object->id)) $object->fetch($id); + $contactsoftask = $object->getListContactId('internal'); + if (!in_array($task_time->fk_user, $contactsoftask)) { + $contactsoftask[] = $task_time->fk_user; + } + if (count($contactsoftask) > 0) { + print img_object('', 'user', 'class="hideonsmartphone"'); + print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, '', 0, '', $contactsoftask); + } else { + print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); + } + } + else + { + $userstatic->id = $task_time->fk_user; + $userstatic->lastname = $task_time->lastname; + $userstatic->firstname = $task_time->firstname; + $userstatic->photo = $task_time->photo; + $userstatic->statut = $task_time->user_status; + print $userstatic->getNomUrl(-1); + } + print ''; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } - else - { - print dol_nl2br($task_time->note); - } - print ''; + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } + else + { + print dol_nl2br($task_time->note); + } + print ''; - if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); - } - else - { - print convertSecondToTime($task_time->task_duration, 'allhourmin'); - } - print ''; + if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); + } + else + { + print convertSecondToTime($task_time->task_duration, 'allhourmin'); + } + print ''; $value = price2num($task_time->thm * $task_time->task_duration / 3600); print price($value, 1, $langs, 1, -1, -1, $conf->currency); @@ -1292,51 +1456,51 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) $totalarray['val']['value'] += $value; if (!$i) $totalarray['totalvaluefield'] = $totalarray['nbfield']; $totalarray['totalvalue'] += $value; - } + } - // Invoiced - if (!empty($arrayfields['valuebilled']['checked'])) - { - print ''; // invoice_id and invoice_line_id - if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) - { - if ($projectstatic->usage_bill_time) - { - if ($task_time->invoice_id) - { - $result = $tmpinvoice->fetch($task_time->invoice_id); - if ($result > 0) - { - print $tmpinvoice->getNomUrl(1); - } - } - else - { - print $langs->trans("No"); - } - } - else - { - print ''.$langs->trans("NA").''; - } - } - print ''; // invoice_id and invoice_line_id + if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_BILL_TIME_SPENT)) + { + if ($projectstatic->usage_bill_time) + { + if ($task_time->invoice_id) + { + $result = $tmpinvoice->fetch($task_time->invoice_id); + if ($result > 0) + { + print $tmpinvoice->getNomUrl(1); + } + } + else + { + print $langs->trans("No"); + } + } + else + { + print ''.$langs->trans("NA").''; + } + } + print ''; if (($action == 'editline' || $action == 'splitline') && $_GET['lineid'] == $task_time->rowid) { @@ -1345,19 +1509,19 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print '
'; print ''; } - elseif ($user->rights->projet->lire || $user->rights->projet->all->creer) // Read project and enter time consumed on assigned tasks + elseif ($user->rights->projet->lire || $user->rights->projet->all->creer) // Read project and enter time consumed on assigned tasks { if ($task_time->fk_user == $user->id || in_array($task_time->fk_user, $childids) || $user->rights->projet->all->creer) { - if ($conf->MAIN_FEATURES_LEVEL >= 2) - { - print ' '; - print 'rowid.$param.'">'; - print img_split(); - print ''; - } + if ($conf->MAIN_FEATURES_LEVEL >= 2) + { + print ' '; + print 'rowid.$param.'">'; + print img_split(); + print ''; + } - print ' '; + print ' '; print 'rowid.$param.'">'; print img_edit(); print ''; @@ -1367,17 +1531,17 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0) print img_delete(); print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected = 0; - if (in_array($task_time->rowid, $arrayofselected)) $selected = 1; - print ' '; - print ''; + $selected = 0; + if (in_array($task_time->rowid, $arrayofselected)) $selected = 1; + print ' '; + print ''; } - } + } } - print '
'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { - print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); - } - else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); - } - else - { - print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($task_time->task_date_withhour)) + { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0); + } + else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0); + } + else + { + print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); + } + print ''; - $tasktmp->id = $task_time->fk_task; - $tasktmp->ref = $task_time->ref; - $tasktmp->label = $task_time->label; - print $tasktmp->getNomUrl(1, 'withproject', 'time'); - print ''; + $tasktmp->id = $task_time->fk_task; + $tasktmp->ref = $task_time->ref; + $tasktmp->label = $task_time->label; + print $tasktmp->getNomUrl(1, 'withproject', 'time'); + print ''; - print $task_time->label; - print ''; + print $task_time->label; + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); - $contactsoftask = $object->getListContactId('internal'); - if (!in_array($task_time->fk_user, $contactsoftask)) { - $contactsoftask[] = $task_time->fk_user; - } - if (count($contactsoftask) > 0) { - print img_object('', 'user', 'class="hideonsmartphone"'); - print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, '', 0, '', $contactsoftask); - } else { - print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); - } - } - else - { - $userstatic->id = $task_time->fk_user; - $userstatic->lastname = $task_time->lastname; - $userstatic->firstname = $task_time->firstname; - $userstatic->photo = $task_time->photo; - $userstatic->statut = $task_time->user_status; - print $userstatic->getNomUrl(-1); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($object->id)) $object->fetch($id); + $contactsoftask = $object->getListContactId('internal'); + if (!in_array($task_time->fk_user, $contactsoftask)) { + $contactsoftask[] = $task_time->fk_user; + } + if (count($contactsoftask) > 0) { + print img_object('', 'user', 'class="hideonsmartphone"'); + print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, '', 0, '', $contactsoftask); + } else { + print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); + } + } + else + { + $userstatic->id = $task_time->fk_user; + $userstatic->lastname = $task_time->lastname; + $userstatic->firstname = $task_time->firstname; + $userstatic->photo = $task_time->photo; + $userstatic->statut = $task_time->user_status; + print $userstatic->getNomUrl(-1); + } + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } - else - { - print dol_nl2br($task_time->note); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } + else + { + print dol_nl2br($task_time->note); + } + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); - } - else - { - print convertSecondToTime($task_time->task_duration, 'allhourmin'); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + print $form->select_duration('new_duration', $task_time->task_duration, 0, 'text'); + } + else + { + print convertSecondToTime($task_time->task_duration, 'allhourmin'); + } + print ''; - $value = price2num($task_time->thm * $task_time->task_duration / 3600); - print price($value, 1, $langs, 1, -1, -1, $conf->currency); - print ''; + $value = price2num($task_time->thm * $task_time->task_duration / 3600); + print price($value, 1, $langs, 1, -1, -1, $conf->currency); + print ''; - $valuebilled = price2num($task_time->total_ht); - if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); - print ''; + $valuebilled = price2num($task_time->total_ht); + if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + print ''; - print ''; + print '
'; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($task_time->task_date_withhour)) - { - print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 3, 3, 2, "timespent_date", 1, 0); - } - else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 1, 1, 2, "timespent_date", 1, 0); - } - else - { - print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($task_time->task_date_withhour)) + { + print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 3, 3, 2, "timespent_date", 1, 0); + } + else print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 1, 1, 2, "timespent_date", 1, 0); + } + else + { + print dol_print_date(($date2 ? $date2 : $date1), ($task_time->task_date_withhour ? 'dayhour' : 'day')); + } + print ''; - $tasktmp->id = $task_time->fk_task; - $tasktmp->ref = $task_time->ref; - $tasktmp->label = $task_time->label; - print $tasktmp->getNomUrl(1, 'withproject', 'time'); - print ''; + $tasktmp->id = $task_time->fk_task; + $tasktmp->ref = $task_time->ref; + $tasktmp->label = $task_time->label; + print $tasktmp->getNomUrl(1, 'withproject', 'time'); + print ''; - print $task_time->label; - print ''; + print $task_time->label; + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - if (empty($object->id)) $object->fetch($id); - $contactsoftask = $object->getListContactId('internal'); - if (!in_array($task_time->fk_user, $contactsoftask)) { - $contactsoftask[] = $task_time->fk_user; - } - if (count($contactsoftask) > 0) { - print img_object('', 'user', 'class="hideonsmartphone"'); - print $form->select_dolusers($task_time->fk_user, 'userid_line_2', 0, '', 0, '', $contactsoftask); - } else { - print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); - } - } - else - { - $userstatic->id = $task_time->fk_user; - $userstatic->lastname = $task_time->lastname; - $userstatic->firstname = $task_time->firstname; - $userstatic->photo = $task_time->photo; - $userstatic->statut = $task_time->user_status; - print $userstatic->getNomUrl(-1); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + if (empty($object->id)) $object->fetch($id); + $contactsoftask = $object->getListContactId('internal'); + if (!in_array($task_time->fk_user, $contactsoftask)) { + $contactsoftask[] = $task_time->fk_user; + } + if (count($contactsoftask) > 0) { + print img_object('', 'user', 'class="hideonsmartphone"'); + print $form->select_dolusers($task_time->fk_user, 'userid_line_2', 0, '', 0, '', $contactsoftask); + } else { + print img_error($langs->trans('FirstAddRessourceToAllocateTime')).$langs->trans('FirstAddRessourceToAllocateTime'); + } + } + else + { + $userstatic->id = $task_time->fk_user; + $userstatic->lastname = $task_time->lastname; + $userstatic->firstname = $task_time->firstname; + $userstatic->photo = $task_time->photo; + $userstatic->statut = $task_time->user_status; + print $userstatic->getNomUrl(-1); + } + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - } - else - { - print dol_nl2br($task_time->note); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + } + else + { + print dol_nl2br($task_time->note); + } + print ''; - if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) - { - print ''; - print $form->select_duration('new_duration_2', 0, 0, 'text'); - } - else - { - print convertSecondToTime($task_time->task_duration, 'allhourmin'); - } - print ''; + if ($action == 'splitline' && $_GET['lineid'] == $task_time->rowid) + { + print ''; + print $form->select_duration('new_duration_2', 0, 0, 'text'); + } + else + { + print convertSecondToTime($task_time->task_duration, 'allhourmin'); + } + print ''; - $value = 0; - print price($value, 1, $langs, 1, -1, -1, $conf->currency); - print ''; + $value = 0; + print price($value, 1, $langs, 1, -1, -1, $conf->currency); + print ''; - $valuebilled = price2num($task_time->total_ht); - if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); - print ''; + $valuebilled = price2num($task_time->total_ht); + if (isset($task_time->total_ht)) print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency); + print ''; - print ''; + print '
'; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) + print '
'; + if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) { - print '
'; - if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) - { - $tmpcode = $object->code_fournisseur; - if (empty($tmpcode) && !empty($object->oldcopy->code_fournisseur)) $tmpcode = $object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. - if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); - print ''; - } - elseif ($object->codefournisseur_modifiable()) - { - print ''; - } - else - { - print $object->code_fournisseur; - print ''; - } - print ''; - $s = $modCodeFournisseur->getToolTip($langs, $object, 1); - print $form->textwithpicto('', $s, 1); - print '
'; + $tmpcode = $object->code_fournisseur; + if (empty($tmpcode) && !empty($object->oldcopy->code_fournisseur)) $tmpcode = $object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value. + if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); + print ''; } + elseif ($object->codefournisseur_modifiable()) + { + print ''; + } + else + { + print $object->code_fournisseur; + print ''; + } + print '
'; + $s = $modCodeFournisseur->getToolTip($langs, $object, 1); + print $form->textwithpicto('', $s, 1); + print '
'; print '
'.$langs->trans("CustomersCategoriesShort").''; - print $form->showCategories($object->id, 'customer', 1); + print $form->showCategories($object->id, Categorie::TYPE_CUSTOMER, 1); print "
'.$langs->trans("SuppliersCategoriesShort").''; - print $form->showCategories($object->id, 'supplier', 1); + print $form->showCategories($object->id, Categorie::TYPE_SUPPLIER, 1); print "
'; - print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 2, 'socid', 'Publishable key '.$site_account); + print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 2, 'socid'); print ''; print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid'); if (!empty($conf->stripe->enabled) && $stripecu && $action != 'editkey_account') @@ -870,7 +878,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$stripecu; } - print ' '.img_picto($langs->trans('ShowInStripe'), 'globe').''; + print ' '.img_picto($langs->trans('ShowInStripe').' - Publishable key = '.$site_account, 'globe').''; } print ''; if (empty($stripecu)) @@ -924,7 +932,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $url = 'https://dashboard.stripe.com/connect/accounts/'.$stripesupplieracc; } - print ' '.img_picto($langs->trans('ShowInStripe'), 'globe').''; + print ' '.img_picto($langs->trans('ShowInStripe').' - Publishable key '.$site_account, 'globe').''; } print ''; if (empty($stripesupplieracc)) @@ -999,20 +1007,21 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' } } } - catch(Exception $e) + catch (Exception $e) { dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id); } } print ''."\n"; - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''."\n"; print ''; - if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) + if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) { print ''; } + print ''; print ''; print ''; print ''; @@ -1066,6 +1075,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print $companypaymentmodetemp->id; print ''; print ''; + print ''; print ''; } + print ''; // Src ID print ''; + print ''; } } @@ -1367,14 +1381,14 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' // List of bank accounts - $morehtmlright= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&action=create'); + $morehtmlright = dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&action=create'); print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, ''); $rib_list = $object->get_all_rib(); if (is_array($rib_list)) { - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
'.$langs->trans('LocalID').''.$langs->trans('Label').''.$langs->trans('StripeID').''.$langs->trans('Type').''.$langs->trans('Informations').''; + print $companypaymentmodetemp->label; + print ''; print $companypaymentmodetemp->stripe_card_ref; if ($companypaymentmodetemp->stripe_card_ref) { @@ -1076,7 +1088,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { $url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$companypaymentmodetemp->stripe_card_ref; } - print ' '.img_picto($langs->trans('ShowInStripe'), 'globe').''; + print ' '.img_picto($langs->trans('ShowInStripe').' - Customer and Publishable key = '.$companypaymentmodetemp->stripe_account, 'globe').''; } print ''; @@ -1159,6 +1171,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' print ''; print ''; + print ''; $connect = ''; @@ -1330,7 +1344,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { foreach ($balance->available as $cpt) { - $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); + $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); if (!in_array($cpt->currency, $arrayzerounitcurrency)) { $currencybalance[$cpt->currency]['available'] = $cpt->amount / 100; } else { @@ -1344,11 +1358,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { foreach ($balance->pending as $cpt) { - $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); + $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); if (!in_array($cpt->currency, $arrayzerounitcurrency)) { - $currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available']+$cpt->amount / 100; + $currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount / 100; } else { - $currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available']+$cpt->amount; + $currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount; } } } @@ -1357,7 +1371,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' { foreach ($currencybalance as $cpt) { - print '
'.$langs->trans("Currency".strtoupper($cpt['currency'])).''.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).''.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).''.price($cpt['available']+$cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'
'.$langs->trans("Currency".strtoupper($cpt['currency'])).''.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).''.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).''.price($cpt['available'] + $cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'
'; print ''; @@ -1734,7 +1748,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) // Edit Card if ($socid && $action == 'editcard' && $user->rights->societe->creer) { - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = ''.$langs->trans("BackToList").''; @@ -1751,7 +1765,7 @@ if ($socid && $action == 'editcard' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -1760,7 +1774,7 @@ if ($socid && $action == 'editcard' && $user->rights->societe->creer) print $formother->select_year($companypaymentmode->exp_date_year, 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly'); print ''; - print ''; + print ''; print ''; print '"; @@ -1882,7 +1896,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) // Create Card if ($socid && $action == 'createcard' && $user->rights->societe->creer) { - dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company'); + dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company'); $linkback = ''.$langs->trans("BackToList").''; @@ -1899,7 +1913,7 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -1908,8 +1922,8 @@ if ($socid && $action == 'createcard' && $user->rights->societe->creer) print $formother->select_year(GETPOST('exp_date_year', 'int'), 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly'); print ''; - print ''; - print ''; + print ''; + print ''; print '"; print ''; diff --git a/htdocs/stripe/admin/stripe.php b/htdocs/stripe/admin/stripe.php index 838cc5ca37a..9d698c7c5f8 100644 --- a/htdocs/stripe/admin/stripe.php +++ b/htdocs/stripe/admin/stripe.php @@ -165,7 +165,7 @@ print ''; dol_fiche_head($head, 'stripeaccount', '', -1); -$stripearrayofwebhookevents = array('payout.created', 'payout.paid', 'charge.pending', 'charge.refunded', 'charge.succeeded', 'charge.failed', 'payment_intent.succeeded', 'payment_intent.payment_failed', 'payment_method.attached', 'payment_method.updated', 'payment_method.card_automatically_updated', 'payment_method.detached', 'source.chargeable', 'customer.deleted'); +$stripearrayofwebhookevents=array('account.updated', 'payout.created', 'payout.paid', 'charge.pending', 'charge.refunded', 'charge.succeeded', 'charge.failed', 'payment_intent.succeeded', 'payment_intent.payment_failed', 'payment_method.attached', 'payment_method.updated', 'payment_method.card_automatically_updated', 'payment_method.detached', 'source.chargeable', 'customer.deleted'); print ''.$langs->trans("StripeDesc")."
\n"; diff --git a/htdocs/stripe/charge.php b/htdocs/stripe/charge.php index d198555e421..bea6223ff32 100644 --- a/htdocs/stripe/charge.php +++ b/htdocs/stripe/charge.php @@ -26,17 +26,17 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; // Load translation files required by the page $langs->loadLangs(array('compta', 'salaries', 'bills', 'hrm', 'stripe')); // Security check $socid = GETPOST("socid", "int"); -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; //$result = restrictedArea($user, 'salaries', '', '', ''); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $rowid = GETPOST("rowid", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); @@ -154,16 +154,16 @@ if (!$rowid) } // The metadata FULLTAG is defined by the online payment page - $FULLTAG=$charge->metadata->FULLTAG; + $FULLTAG = $charge->metadata->FULLTAG; // Save into $tmparray all metadata $tmparray = dolExplodeIntoArray($FULLTAG, '.', '='); // Load origin object according to metadata - if (! empty($tmparray['CUS']) && $tmparray['CUS'] > 0) + if (!empty($tmparray['CUS']) && $tmparray['CUS'] > 0) { $societestatic->fetch($tmparray['CUS']); } - elseif (! empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0) + elseif (!empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0) { $societestatic->fetch($charge->metadata->dol_thirdparty_id); } diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php index f5656387192..32d9fd4784b 100644 --- a/htdocs/stripe/class/stripe.class.php +++ b/htdocs/stripe/class/stripe.class.php @@ -139,7 +139,8 @@ class Stripe extends CommonObject /** - * Get the Stripe customer of a thirdparty (with option to create it if not linked yet) + * Get the Stripe customer of a thirdparty (with option to create it if not linked yet). + * Search on site_account = 0 or = $stripearrayofkeysbyenv[$status]['publishable_key'] * * @param Societe $object Object thirdparty to check, or create on stripe (create on stripe also update the stripe_account table for current entity) * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect @@ -246,8 +247,8 @@ class Stripe extends CommonObject } // Create customer in Dolibarr - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)"; - $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer->id)."', 'stripe', ".$status.", ".$conf->entity.", '".$this->db->idate(dol_now())."', ".$user->id.")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)"; + $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer->id)."', 'stripe', '".$this->db->escape($stripearrayofkeysbyenv[$status]['publishable_key'])."', ".$status.", ".$conf->entity.", '".$this->db->idate(dol_now())."', ".$user->id.")"; $resql = $this->db->query($sql); if (!$resql) { @@ -416,7 +417,8 @@ class Stripe extends CommonObject "currency" => $currency_code, "payment_method_types" => array("card"), "description" => $description, - "statement_descriptor" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + //"save_payment_method" => true, "setup_future_usage" => "on_session", "metadata" => $metadata ); @@ -559,7 +561,7 @@ class Stripe extends CommonObject { global $conf; - dol_syslog("getSetupIntent", LOG_INFO, 1); + dol_syslog("getSetupIntent description=".$description.' confirmnow='.$confirmnow, LOG_INFO, 1); $error = 0; @@ -601,6 +603,8 @@ class Stripe extends CommonObject global $stripearrayofkeysbyenv; \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']); + dol_syslog("getSetupIntent ".$stripearrayofkeysbyenv[$status]['publishable_key'], LOG_DEBUG); + // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent. if (empty($key)) { // If the Stripe connect account not set, we use common API usage //$setupintent = \Stripe\SetupIntent::create($dataforintent, array("idempotency_key" => "$description")); @@ -666,14 +670,14 @@ class Stripe extends CommonObject } } - dol_syslog("getSetupIntent return error=".$error, LOG_INFO, -1); - if (!$error) { + dol_syslog("getSetupIntent ".(is_object($setupintent) ? $setupintent->id : ''), LOG_INFO, -1); return $setupintent; } else { + dol_syslog("getSetupIntent return error=".$error, LOG_INFO, -1); return null; } } @@ -956,7 +960,7 @@ class Stripe extends CommonObject $charge = \Stripe\Charge::create(array( "amount" => "$stripeamount", "currency" => "$currency", - "statement_descriptor" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "description" => "Stripe payment: ".$description, "capture" => $capture, "metadata" => $metadata, @@ -966,7 +970,7 @@ class Stripe extends CommonObject $paymentarray = array( "amount" => "$stripeamount", "currency" => "$currency", - "statement_descriptor" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "description" => "Stripe payment: ".$description, "capture" => $capture, "metadata" => $metadata, @@ -993,10 +997,10 @@ class Stripe extends CommonObject if (!in_array($currency, $arrayzerounitcurrency)) $stripefee = round($fee * 100); else $stripefee = round($fee); - $paymentarray = array( + $paymentarray = array( "amount" => "$stripeamount", "currency" => "$currency", - "statement_descriptor" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) + "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description) "description" => "Stripe payment: ".$description, "capture" => $capture, "metadata" => $metadata, diff --git a/htdocs/stripe/config.php b/htdocs/stripe/config.php index 0226c724165..65d80f9587b 100644 --- a/htdocs/stripe/config.php +++ b/htdocs/stripe/config.php @@ -55,4 +55,4 @@ else \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']); \Stripe\Stripe::setAppInfo("Dolibarr Stripe", DOL_VERSION, "https://www.dolibarr.org"); // add dolibarr version -\Stripe\Stripe::setApiVersion(empty($conf->global->STRIPE_FORCE_VERSION) ? "2019-05-16" : $conf->global->STRIPE_FORCE_VERSION); // force version API +\Stripe\Stripe::setApiVersion(empty($conf->global->STRIPE_FORCE_VERSION) ? "2019-09-09" : $conf->global->STRIPE_FORCE_VERSION); // force version API diff --git a/htdocs/stripe/payment.php b/htdocs/stripe/payment.php deleted file mode 100644 index b6bc81a91e2..00000000000 --- a/htdocs/stripe/payment.php +++ /dev/null @@ -1,1147 +0,0 @@ - - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005 Marc Barilley / Ocebo - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2012 Cédric Salvador - * Copyright (C) 2014 Raphaël Doursenaud - * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> - * Copyright (C) 2015 Juanjo Menent - * Copyright (C) 2018-2019 Thibault FOUCART - * 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/stripe/payment.php - * \ingroup stripe - * \brief Payment page for customers invoices. @todo Seems deprecated and bugged and not used (no link to this page) ! - */ - -// Load Dolibarr environment -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; -require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; - -// Load translation files required by the page -$langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency', 'stripe')); - -$action = GETPOST('action', 'alpha'); -$confirm = GETPOST('confirm'); - -$facid = GETPOST('facid', 'int'); -$socname = GETPOST('socname'); -$source = GETPOST('source_id'); -$accountid = GETPOST('accountid'); -$paymentnum = GETPOST('num_paiement'); - -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); - -$amounts=array(); -$amountsresttopay=array(); -$addwarning=0; - -$multicurrency_amounts=array(); -$multicurrency_amountsresttopay=array(); - -// Security check -$socid=0; -if ($user->socid > 0) -{ - $socid = $user->socid; -} - -$object=new Facture($db); -$stripe=new Stripe($db); - -// Load object -if ($facid > 0) -{ - $ret=$object->fetch($facid); -} - -if (empty($conf->stripe->enabled)) -{ - accessforbidden(); -} - -if (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha')) -{ - $service = 'StripeTest'; - $servicestatus = '0'; - dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); -} -else -{ - $service = 'StripeLive'; - $servicestatus = '1'; -} -$stripeacc = $stripe->getStripeAccount($service); -/*if (empty($stripeaccount)) -{ - print $langs->trans('ErrorStripeAccountNotDefined'); -}*/ - -// Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('paiementcard', 'globalcard')); - -/* - * 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)) -{ - if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) - { - $error = 0; - - $datepaye = dol_now(); - $paiement_id = 0; - $totalpayment = 0; - $multicurrency_totalpayment = 0; - $atleastonepaymentnotnull = 0; - - // Generate payment array and check if there is payment higher than invoice and payment date before invoice date - $tmpinvoice = new Facture($db); - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { - $cursorfacid = substr($key, 7); - $amounts[$cursorfacid] = price2num(trim(GETPOST($key))); - $totalpayment = $totalpayment + $amounts[$cursorfacid]; - if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++; - $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); - $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); - if ($amounts[$cursorfacid]) - { - // Check amount - if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) - { - $addwarning = 1; - $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay"); - } - // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { - $langs->load("errors"); - //$error++; - setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); - } - } - - $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]); - } - elseif (substr($key, 0, 21) == 'multicurrency_amount_') - { - $cursorfacid = substr($key, 21); - $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key))); - $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; - if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; - $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); - $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1)); - if ($multicurrency_amounts[$cursorfacid]) - { - // Check amount - if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) - { - $addwarning = 1; - $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay"); - } - // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { - $langs->load("errors"); - //$error++; - setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); - } - } - - $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int')); - } - } - - // Check parameters - /*if (! GETPOST('paiementcode')) - { - setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->transnoentities('PaymentMode')), null, 'errors'); - $error++; - }*/ - - if (!empty($conf->banque->enabled)) - { - // If bank module is on, account is required to enter a payment - if (GETPOST('accountid') <= 0) - { - setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); - $error++; - } - } - - if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) - { - setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors'); - $error++; - } - - /*if (empty($datepaye)) - { - setEventMessages($langs->transnoentities('ErrorFieldRequired',$langs->transnoentities('Date')), null, 'errors'); - $error++; - }*/ - - // Check if payments in both currency - if ($totalpayment > 0 && $multicurrency_totalpayment > 0) - { - setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors'); - $error++; - } - } - - /* - * Action add_paiement - */ - if ($action == 'add_paiement') { - if ($error) { - $action = 'create'; - if (!$source) { - setEventMessages($langs->transnoentities('NoSource'), null, 'errors'); - } - $error++; - } - // Le reste propre a cette action s'affiche en bas de page. - } - - /* - * Action confirm_paiement - */ - if ($action == 'confirm_paiement' && $confirm == 'yes') - { - $error = 0; - - $datepaye = dol_now(); - - $db->begin(); - - // Clean parameters amount if payment is for a credit note - if (GETPOST('type') == 2) - { - foreach ($amounts as $key => $value) // How payment is dispatch - { - $newvalue = price2num($value, 'MT'); - $amounts[$key] = -$newvalue; - } - - foreach ($multicurrency_amounts as $key => $value) // How payment is dispatch - { - $newvalue = price2num($value, 'MT'); - $multicurrency_amounts[$key] = -$newvalue; - } - } - - if (!empty($conf->banque->enabled)) - { - // Si module bank actif, un compte est obligatoire lors de la saisie d'un paiement - if (GETPOST('accountid') <= 0) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); - $error++; - } - } - - $facture = new Facture($db); - $facture->fetch($facid); - $facture->fetch_thirdparty(); - - $error = 0; - - if (is_object($stripe) && $stripeacc) - { - $customerstripe = $stripe->customerStripe($facture->thirdparty, $stripeacc, $servicestatus); - - if ($customerstripe->id) { - $listofsources = $customerstripe->sources->data; - } - } - - $stripeamount = 0; - foreach ($amounts as $key => $value) // How payment is dispatch - { - $stripeamount += price2num($value, 'MT'); - } - - if (preg_match('/acct_/i', $source)) - { - $paiementcode = "VIR"; - } - elseif (preg_match('/card_/i', $source)) - { - $paiementcode = "CB"; - } - elseif (preg_match('/src_/i', $source)) - { - $customer2 = $customerstripe = $stripe->customerStripe($facture->thirdparty, $stripeacc, $servicestatus); - $src = $customer2->sources->retrieve("$source"); - if ($src->type == 'card') - { - $paiementcode = "CB"; - } - } - - - - $societe = new Societe($db); - $societe->fetch($facture->socid); - dol_syslog("Create charge", LOG_DEBUG, 0, '_stripe'); - - $stripecu = $stripe->getStripeCustomerAccount($societe->id, $servicestatus); // Get thirdparty cu_... - - $charge = $stripe->createPaymentStripe($stripeamount, $facture->multicurrency_code, "invoice", $facid, $source, $stripecu, $stripeacc, $servicestatus); - - if (!$error) - { - // Creation of payment line - $paiement = new Paiement($db); - $paiement->datepaye = $datepaye; - $paiement->amounts = $amounts; // Array with all payments dispatching - $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = dol_getIdFromCode($db, $paiementcode, 'c_paiement'); - $paiement->num_paiement = $charge->message; - $paiement->note = GETPOST('comment'); - $paiement->ext_payment_id = $charge->id; - $paiement->ext_payment_site = $service; - } - - if (!$error) - { - $paiement_id = $paiement->create($user, 0); - if ($paiement_id < 0) - { - setEventMessages($paiement->error, $paiement->errors, 'errors'); - $error++; - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($facture->lines)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $facture->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $facture->modelpdf; - $ret = $facture->fetch($facid); // Reload to get new records - - $facture->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - } - - if (!$error) - { - $label = '(CustomerInvoicePayment)'; - if (GETPOST('type') == 2) $label = '(CustomerInvoicePaymentBack)'; - $result = $paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), '', ''); - if ($result < 0) - { - setEventMessages($paiement->error, $paiement->errors, 'errors'); - $error++; - } - elseif (GETPOST('closepaidinvoices') == 'on') { - $facture->set_paid($user); - } - } - - if (!$error) - { - $db->commit(); - - // If payment dispatching on more than one invoice, we keep on summary page, otherwise go on invoice card - $invoiceid = 0; - foreach ($paiement->amounts as $key => $amount) - { - $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { - if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment - else $invoiceid = $facid; - } - } - if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id; - header('Location: '.$loc); - exit; - } - else - { - $loc = DOL_URL_ROOT.'/stripe/payment.php?facid='.$facid.'&action=create&error='.$charge->message; - $db->rollback(); - - header('Location: '.$loc); - exit; - } - } -} - - -/* - * View - */ - -$form = new Form($db); - -llxHeader(); - -if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) { - $service = 'StripeLive'; - $servicestatus = 0; -} else { - dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning'); -} - -if (GETPOST('error')) { - setEventMessages(GETPOST('error'), null, 'errors'); -} - -if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') -{ - $facture = new Facture($db); - $result = $facture->fetch($facid); - - if ($result >= 0) - { - $facture->fetch_thirdparty(); - - $title = ''; - if ($facture->type != 2) $title .= $langs->trans("EnterPaymentReceivedFromCustomer"); - if ($facture->type == 2) $title .= $langs->trans("EnterPaymentDueToCustomer"); - print load_fiche_titre($title); - - // Initialize data for confirmation (this is used because data can be change during confirmation) - if ($action == 'add_paiement') - { - $i = 0; - - $formquestion[$i++] = array('type' => 'hidden', 'name' => 'facid', 'value' => $facture->id); - $formquestion[$i++] = array('type' => 'hidden', 'name' => 'socid', 'value' => $facture->socid); - $formquestion[$i++] = array('type' => 'hidden', 'name' => 'type', 'value' => $facture->type); - } - - - // Add realtime total information - if ($conf->use_javascript_ajax) - { - print "\n".''."\n"; - } - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - dol_fiche_head(); - - print '
'.$langs->trans("NameOnCard").'
'.$langs->trans("CardNumber").'
'.$langs->trans("CardNumber").'
'.$langs->trans("ExpiryDate").'
'.$langs->trans("CVN").'
'.$langs->trans("CVN").'
'.$langs->trans("StripeID")." ('card_....')
'.$langs->trans("NameOnCard").'
'.$langs->trans("CardNumber").'
'.$langs->trans("CardNumber").'
'.$langs->trans("ExpiryDate").'
'.$langs->trans("CVN").'
'.$langs->trans("CVN").'
'.$langs->trans("StripeID")." ('card_....')
'; - - // Invoice - /*if ($facture->id > 0) - { - print '\n"; - }*/ - - // Third party - print '\n"; - - // Bank account - if (!empty($conf->banque->enabled)) - { - //$form->select_comptes($accountid,'accountid',0,'',2); - print ''; - } - else - { - print ''; - } - - // Cheque number - //print ''; - //print ''; - - // Check transmitter - //print ''; - //print ''; - - // Bank name - //print ''; - //print ''; - - // Comments - print ''; - print ''; - - print '
'.$langs->trans('Invoice').''.$facture->getNomUrl(4)."
'.$langs->trans('Company').''.$facture->thirdparty->getNomUrl(4)."
'.$langs->trans('Numero'); - //print ' ('.$langs->trans("ChequeOrTransferNumber").')'; - //print '
'.$langs->trans('CheckTransmitter'); - //print ' ('.$langs->trans("ChequeMaker").')'; - //print '
'.$langs->trans('Bank'); - //print ' ('.$langs->trans("ChequeBank").')'; - //print '
'.$langs->trans('Comments').''; - print '
'; - - dol_fiche_end(); - - - $customerstripe = $stripe->customerStripe($facture->thirdparty, $stripeacc, $servicestatus); - - print '
'; - print_barre_liste($langs->trans('StripeSourceList').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, '', ''); - - print ''."\n"; - // Titles with sort buttons - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - foreach ($customerstripe->sources->data as $src) { - print ''; - - print ''; - - print ''; - print ''; - // Default - print ''; - print ''; - } - // TODO more dolibarize with new stripe function and stripeconnect - //if ($stripe->getStripeCustomerAccount($facture->socid)) { - // $account=\Stripe\Account::retrieve("".$stripe->getStripeCustomerAccount($facture->socid).""); - //} - - if (($account->type == 'custom' or $account->type == 'express') && $entity == 1) { - print ''; - - print ''; - - print ''; - // Default - print ''; - print ''; - } - if (empty($input) && !$stripe->getStripeCustomerAccount($facture->socid)) { - print ''; - } - - print "
'.$langs->trans('Type').''.$langs->trans('Informations').'
id != $source) or ($src->object == 'source' && $src->card->three_d_secure == 'required')) { - print'class="opacitymedium"'; - } - print '>id != $source) or ($src->object == 'source' && $src->card->three_d_secure == 'required')) { - print ' disabled'; - } elseif (($customerstripe->default_source == $src->id && $action != 'add_paiement') or ($source == $src->id && $action == 'add_paiement')) { - print ' checked'; - } - print '>id != $source) or ($src->object == 'source' && $src->card->three_d_secure == 'required')) { - print'class="opacitymedium"'; - } - - print' >'; - if ($src->object == 'card') { - print img_credit_card($src->brand); - } elseif ($src->object == 'source' && $src->type == 'card') { - print img_credit_card($src->card->brand); - } elseif ($src->object == 'source' && $src->type == 'sepa_debit') { - print ''; - } - print 'id != $source) or ($src->object == 'source' && $src->card->three_d_secure == 'required')) { - print'class="opacitymedium"'; - } - print' >'; - if ($src->object == 'card') { - print '....'.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.''; - print ''; - if ($src->country) { - $img = picto_from_langcode($src->country); - print $img ? $img.' ' : ''; - print getCountry($src->country, 1); - } else { - print img_warning().' '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).''; - } - } elseif ($src->object == 'source' && $src->type == 'card') { - print $src->owner->name.'
....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.''; - print '
'; - if ($src->card->country) { - $img = picto_from_langcode($src->card->country); - print $img ? $img.' ' : ''; - print getCountry($src->card->country, 1); - } else { - print img_warning().' '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).''; - } - } elseif ($src->object == 'source' && $src->type == 'sepa_debit') { - print 'info sepa'; - print ''; - if ($src->sepa_debit->country) { - $img = picto_from_langcode($src->sepa_debit->country); - print $img ? $img.' ' : ''; - print getCountry($src->sepa_debit->country, 1); - } else { - print img_warning().' '.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).''; - } - } - print 'id != $source) or ($src->object == 'source' && $src->card->three_d_secure == 'required')) { - print'class="opacitymedium"'; - } - print'>'; - if (($customerstripe->default_source == $src->id)) { - print ""; - } - print '
getStripeCustomerAccount($facture->socid) != $source) { - print'class="opacitymedium"'; - } - print'>global->STRIPE_EXTERNAL_ACCOUNT && $action == 'add_paiement')) { - print ' checked'; - } elseif ($action == 'add_paiement' && $conf->global->STRIPE_EXTERNAL_ACCOUNT != $source) { - print ' disabled'; - } - print '>getStripeCustomerAccount($facture->socid) != $source) { - print'class="opacitymedium"'; - } - print '>getStripeCustomerAccount($facture->socid) != $source) { - print'class="opacitymedium"'; - } - print'>'.$langs->trans('sold'); - print'id != $source) { - print'class="opacitymedium"'; - } - print'>'; - - print 'id != $source) { - print'class="opacitymedium"'; - } - print'>'; - //if (($customer->default_source!=$src->id)) { - // print img_picto($langs->trans("Disabled"),'off'); - //} else { - // print img_picto($langs->trans("Default"),'on'); - //} - print '
'.$langs->trans("None").'
"; - - - /* - * List of unpaid invoices - */ - - $sql = 'SELECT f.rowid as facid, f.ref, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type, '; - $sql .= ' f.datef as df, f.fk_soc as socid'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - - if (!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS)) { - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON (f.fk_soc = s.rowid)'; - } - - $sql .= ' WHERE f.entity IN ('.getEntity('invoice').")"; - $sql .= ' AND (f.fk_soc = '.$facture->socid; - - if (!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) { - $sql .= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')'; - } - - $sql .= ') AND f.paye = 0'; - $sql .= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled - if ($facture->type != 2) - { - $sql .= ' AND type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation - } - else - { - $sql .= ' AND type = 2'; // If paying back a credit note, we show all credit notes - } - - // Sort invoices by date and serial number: the older one comes first - $sql .= ' ORDER BY f.datef ASC, f.ref ASC'; - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - if ($num > 0) - { - $sign = 1; - if ($facture->type == 2) $sign = -1; - - $arraytitle = $langs->trans('Invoice'); - if ($facture->type == 2) $arraytitle = $langs->trans("CreditNotes"); - $alreadypayedlabel = $langs->trans('Received'); - $multicurrencyalreadypayedlabel = $langs->trans('MulticurrencyReceived'); - if ($facture->type == 2) { $alreadypayedlabel = $langs->trans("PaidBack"); $multicurrencyalreadypayedlabel = $langs->trans("MulticurrencyPaidBack"); } - $remaindertopay = $langs->trans('RemainderToTake'); - $multicurrencyremaindertopay = $langs->trans('MulticurrencyRemainderToTake'); - if ($facture->type == 2) { $remaindertopay = $langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay = $langs->trans("MulticurrencyRemainderToPayBack"); } - - $i = 0; - - print '
'; - - print_barre_liste($langs->trans('StripeInvoiceList').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, '', ''); - - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - print ''; - print ''; - print ''; - } - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - - $tmpinvoice = new Facture($db); - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $tmpinvoice, $action); // Note that $action and $object may have been modified by hook - - print ''; - print "\n"; - - $total = 0; - $totalrecu = 0; - $totalrecucreditnote = 0; - $totalrecudeposits = 0; - - while ($i < $num) - { - $objp = $db->fetch_object($resql); - - $soc = new Societe($db); - $soc->fetch($objp->socid); - - $invoice = new Facture($db); - $invoice->fetch($objp->facid); - $paiement = $invoice->getSommePaiement(); - $creditnotes = $invoice->getSumCreditNotesUsed(); - $deposits = $invoice->getSumDepositsUsed(); - $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); - $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); - - // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { - $multicurrency_payment = $invoice->getSommePaiement(1); - $multicurrency_creditnotes = $invoice->getSumCreditNotesUsed(1); - $multicurrency_deposits = $invoice->getSumDepositsUsed(1); - $multicurrency_alreadypayed = price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT'); - $multicurrency_remaintopay = price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT'); - } - - print ''; - - print '\n"; - - // Date - print '\n"; - - // Currency - if (!empty($conf->multicurrency->enabled)) print '\n"; - - // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { - print ''; - - // Multicurrency Price - print ''; - - // Multicurrency Price - print ''; - } - - // Price - print ''; - - // Received or paid back - print ''; - - // Remain to take or to pay back - print ''; - //$test= price(price2num($objp->total_ttc - $paiement - $creditnotes - $deposits)); - - // Amount - print '"; - - // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { - print '"; - } - - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook - - // Warning - print ''; - - print "\n"; - - $total += $objp->total; - $total_ttc += $objp->total_ttc; - $totalrecu += $paiement; - $totalrecucreditnote += $creditnotes; - $totalrecudeposits += $deposits; - $i++; - } - if ($i > 1) - { - $amount = round(price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')) * 100); - - // Print total - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - print ''; - print ''; - } - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - print ''; - print "\n"; - } - print "
'.$arraytitle.''.$langs->trans('Date').''.$langs->trans('Currency').''.$langs->trans('MulticurrencyAmountTTC').''.$multicurrencyalreadypayedlabel.''.$multicurrencyremaindertopay.''.$langs->trans('AmountTTC').''.$alreadypayedlabel.''.$remaindertopay.''.$langs->trans('PaymentAmount').''.$langs->trans('MulticurrencyPaymentAmount').' 
'; - print $invoice->getNomUrl(1, ''); - if ($objp->socid != $facture->thirdparty->id) print ' - '.$soc->getNomUrl(1).' '; - print "'.dol_print_date($db->jdate($objp->df), 'day')."'.$objp->multicurrency_code."'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $objp->multicurrency_total_ttc); - print ''; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { - print price($sign * $multicurrency_payment); - if ($multicurrency_creditnotes) print '+'.price($multicurrency_creditnotes); - if ($multicurrency_deposits) print '+'.price($multicurrency_deposits); - } - print ''; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $multicurrency_remaintopay); - print ''.price($sign * $objp->total_ttc).''.price($sign * $paiement); - if ($creditnotes) print '+'.price($creditnotes); - if ($deposits) print '+'.price($deposits); - print ''.price($sign * $remaintopay).''; - - // Add remind amount - $namef = 'amount_'.$objp->facid; - $nameRemain = 'remain_'.$objp->facid; - - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) - print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'"); - print ''; - print ''; - } - else - { - print ''; - print ''; - } - print "'; - - // Add remind multicurrency amount - $namef = 'multicurrency_amount_'.$objp->facid; - $nameRemain = 'multicurrency_remain_'.$objp->facid; - - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) - print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'"); - print ''; - print ''; - } - else - { - print ''; - print ''; - } - } - print "'; - //print "xx".$amounts[$invoice->id]."-".$amountsresttopay[$invoice->id]."
"; - if ($amounts[$invoice->id] && (abs($amounts[$invoice->id]) > abs($amountsresttopay[$invoice->id])) - || $multicurrency_amounts[$invoice->id] && (abs($multicurrency_amounts[$invoice->id]) > abs($multicurrency_amountsresttopay[$invoice->id]))) - { - print ' '.img_warning($langs->trans("PaymentHigherThanReminderToPay")); - } - print '
'.$langs->trans('TotalTTC').''.price($sign * $total_ttc).''.price($sign * $totalrecu); - if ($totalrecucreditnote) print '+'.price($totalrecucreditnote); - if ($totalrecudeposits) print '+'.price($totalrecudeposits); - print ''.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'
"; - //print "
'; - print ''; - print_liste_field_titre('Invoice', $_SERVER["PHP_SELF"], 'ref', '', '', '', $sortfield, $sortorder); - print_liste_field_titre('Date', $_SERVER["PHP_SELF"], 'dp', '', '', '', $sortfield, $sortorder); - print_liste_field_titre('Type', $_SERVER["PHP_SELF"], 'libelle', '', '', '', $sortfield, $sortorder); - print_liste_field_titre('Amount', $_SERVER["PHP_SELF"], 'fa_amount', '', '', '', $sortfield, $sortorder, 'right '); - - $tmpobject = new Paiement($db); - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $tmpobject, $action); // Note that $action and $object may have been modified by hook - - print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; - - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); - - print ''; - print '\n"; - print '\n"; - print '\n"; - print ''; - - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook - - print ''; - print ''; - $i++; - } - print '
'.$objp->ref."'.dol_print_date($db->jdate($objp->dp))."'.$objp->paiement_type.' '.$objp->num_paiement."'.price($objp->amount).' 
'; - } -} - -// End of page -llxFooter(); -$db->close(); diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index e881eeb3b78..35adc33c749 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -34,12 +34,12 @@ * \brief File of class to manage supplier proposals */ -require_once DOL_DOCUMENT_ROOT .'/fourn/class/fournisseur.product.class.php'; -require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; -require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php'; -require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** * Class to manage price ask supplier @@ -49,27 +49,27 @@ class SupplierProposal extends CommonObject /** * @var string ID to identify managed object */ - public $element='supplier_proposal'; + public $element = 'supplier_proposal'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='supplier_proposal'; + public $table_element = 'supplier_proposal'; /** * @var int Name of subtable line */ - public $table_element_line='supplier_proposaldet'; + public $table_element_line = 'supplier_proposaldet'; /** * @var int Field with ID of parent key if this field has a parent */ - public $fk_element='fk_supplier_proposal'; + public $fk_element = 'fk_supplier_proposal'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ - public $picto='propal'; + public $picto = 'propal'; /** * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe @@ -88,7 +88,7 @@ class SupplierProposal extends CommonObject */ protected $table_ref_field = 'ref'; - public $socid; // Id client + public $socid; // Id client /** * @deprecated @@ -96,9 +96,9 @@ class SupplierProposal extends CommonObject */ public $author; - public $ref_fourn; //Reference saisie lors de l'ajout d'une ligne à la demande - public $ref_supplier; //Reference saisie lors de l'ajout d'une ligne à la demande - public $statut; // 0 (draft), 1 (validated), 2 (signed), 3 (not signed), 4 (processed/billed) + public $ref_fourn; //Reference saisie lors de l'ajout d'une ligne à la demande + public $ref_supplier; //Reference saisie lors de l'ajout d'une ligne à la demande + public $statut; // 0 (draft), 1 (validated), 2 (signed), 3 (not signed), 4 (processed/billed) /** * @var integer|string Date of proposal @@ -161,14 +161,14 @@ class SupplierProposal extends CommonObject public $remise_percent = 0; public $remise_absolue = 0; - public $products=array(); - public $extraparams=array(); + public $products = array(); + public $extraparams = array(); public $lines = array(); public $line; - public $labelStatus=array(); - public $labelStatusShort=array(); + public $labelStatus = array(); + public $labelStatusShort = array(); public $nbtodo; public $nbtodolate; @@ -223,7 +223,7 @@ class SupplierProposal extends CommonObject */ public function __construct($db, $socid = "", $supplier_proposalid = 0) { - global $conf,$langs; + global $conf, $langs; $this->db = $db; @@ -252,24 +252,24 @@ class SupplierProposal extends CommonObject // phpcs:enable global $conf, $mysoc; - if (! $qty) $qty = 1; + if (!$qty) $qty = 1; dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); if ($idproduct > 0) { - $prod=new Product($this->db); + $prod = new Product($this->db); $prod->fetch($idproduct); $productdesc = $prod->description; $tva_tx = get_default_tva($mysoc, $this->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $this->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; + if (empty($tva_tx)) $tva_npr = 0; $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $this->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $this->thirdparty, $tva_npr); // multiprix - if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) + if ($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) { $price = $prod->multiprices[$this->thirdparty->price_level]; } @@ -280,14 +280,14 @@ class SupplierProposal extends CommonObject $line = new SupplierProposalLine($this->db); - $line->fk_product=$idproduct; - $line->desc=$productdesc; - $line->qty=$qty; - $line->subprice=$price; - $line->remise_percent=$remise_percent; - $line->tva_tx=$tva_tx; + $line->fk_product = $idproduct; + $line->desc = $productdesc; + $line->qty = $qty; + $line->subprice = $price; + $line->remise_percent = $remise_percent; + $line->tva_tx = $tva_tx; - $this->lines[]=$line; + $this->lines[] = $line; } } @@ -308,39 +308,39 @@ class SupplierProposal extends CommonObject $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_facture) // Protection against multiple submission { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; } - $supplier_proposalligne=new SupplierProposalLine($this->db); - $supplier_proposalligne->fk_supplier_proposal=$this->id; - $supplier_proposalligne->fk_remise_except=$remise->id; - $supplier_proposalligne->desc=$remise->description; // Description ligne - $supplier_proposalligne->tva_tx=$remise->tva_tx; - $supplier_proposalligne->subprice=-$remise->amount_ht; - $supplier_proposalligne->fk_product=0; // Id produit predefini - $supplier_proposalligne->qty=1; - $supplier_proposalligne->remise=0; - $supplier_proposalligne->remise_percent=0; - $supplier_proposalligne->rang=-1; - $supplier_proposalligne->info_bits=2; + $supplier_proposalligne = new SupplierProposalLine($this->db); + $supplier_proposalligne->fk_supplier_proposal = $this->id; + $supplier_proposalligne->fk_remise_except = $remise->id; + $supplier_proposalligne->desc = $remise->description; // Description ligne + $supplier_proposalligne->tva_tx = $remise->tva_tx; + $supplier_proposalligne->subprice = -$remise->amount_ht; + $supplier_proposalligne->fk_product = 0; // Id produit predefini + $supplier_proposalligne->qty = 1; + $supplier_proposalligne->remise = 0; + $supplier_proposalligne->remise_percent = 0; + $supplier_proposalligne->rang = -1; + $supplier_proposalligne->info_bits = 2; $supplier_proposalligne->total_ht = -$remise->amount_ht; $supplier_proposalligne->total_tva = -$remise->amount_tva; $supplier_proposalligne->total_ttc = -$remise->amount_ttc; - $result=$supplier_proposalligne->insert(); + $result = $supplier_proposalligne->insert(); if ($result > 0) { - $result=$this->update_price(1); + $result = $this->update_price(1); if ($result > 0) { $this->db->commit(); @@ -354,7 +354,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$supplier_proposalligne->error; + $this->error = $supplier_proposalligne->error; $this->db->rollback(); return -2; } @@ -411,28 +411,28 @@ class SupplierProposal extends CommonObject include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent=0; - if (empty($qty)) $qty=0; - if (empty($info_bits)) $info_bits=0; - if (empty($rang)) $rang=0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; - if (empty($pu_ht)) $pu_ht=0; + if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) $qty = 0; + if (empty($info_bits)) $info_bits = 0; + if (empty($rang)) $rang = 0; + if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; + if (empty($pu_ht)) $pu_ht = 0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu_ht=price2num($pu_ht); - $pu_ttc=price2num($pu_ttc); - $txtva=price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if ($price_base_type=='HT') + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); + $pu_ht = price2num($pu_ht); + $pu_ttc = price2num($pu_ttc); + $txtva = price2num($txtva); + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + $pa_ht = price2num($pa_ht); + if ($price_base_type == 'HT') { - $pu=$pu_ht; + $pu = $pu_ht; } else { - $pu=$pu_ttc; + $pu = $pu_ttc; } // Check parameters @@ -444,7 +444,7 @@ class SupplierProposal extends CommonObject if ($fk_product > 0) { - if (! empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) + if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) { // Check quantity is enough dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." fk_fournprice=".$fk_fournprice." qty=".$qty." ref_supplier=".$ref_supplier); @@ -457,19 +457,19 @@ class SupplierProposal extends CommonObject // We use 'none' instead of $ref_supplier, because fourn_ref may not exists anymore. So we will take the first supplier price ok. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price. - $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc?$this->fk_soc:$this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc + $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) { - $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice - $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice + $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent !=0) - $remise_percent =$prod->remise_percent; + if ($remise_percent == 0 && $prod->remise_percent != 0) + $remise_percent = $prod->remise_percent; } if ($result == 0) // If result == 0, we failed to found the supplier reference price { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $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 @@ -479,14 +479,14 @@ class SupplierProposal extends CommonObject if ($result == -1) { $langs->load("errors"); - $this->error = "Ref " . $prod->ref . " " . $langs->trans("ErrorQtyTooLowForThisSupplier"); + $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->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); return -1; @@ -494,7 +494,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$prod->error; + $this->error = $prod->error; $this->db->rollback(); return -1; } @@ -510,14 +510,14 @@ class SupplierProposal extends CommonObject // 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, $this->thirdparty, $mysoc); - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. if ($conf->multicurrency->enabled && $pu_ht_devise > 0) { $pu = 0; } - $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); + $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]; @@ -550,33 +550,33 @@ class SupplierProposal extends CommonObject } // Insert line - $this->line=new SupplierProposalLine($this->db); + $this->line = new SupplierProposalLine($this->db); - $this->line->fk_supplier_proposal=$this->id; - $this->line->label=$label; - $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->fk_supplier_proposal = $this->id; + $this->line->label = $label; + $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->remise_percent=$remise_percent; - $this->line->subprice=$pu_ht; - $this->line->rang=$ranktouse; - $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=$special_code; - $this->line->fk_parent_line=$fk_parent_line; - $this->line->fk_unit=$fk_unit; - $this->line->origin=$origin; - $this->line->origin_id=$origin_id; + $this->line->fk_product = $fk_product; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->rang = $ranktouse; + $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 = $special_code; + $this->line->fk_parent_line = $fk_parent_line; + $this->line->fk_unit = $fk_unit; + $this->line->origin = $origin; + $this->line->origin_id = $origin_id; $this->line->ref_fourn = $this->db->escape($ref_supplier); $this->line->date_start = $date_start; $this->line->date_end = $date_end; @@ -589,34 +589,34 @@ class SupplierProposal extends CommonObject $productFournisseur->find_min_price_product_fournisseur($fk_product); $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id; } else { - $this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0); // If fk_fournprice is -1, we will not use fk_fournprice + $this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0); // If fk_fournprice is -1, we will not use fk_fournprice } $this->line->pa_ht = $pa_ht; //var_dump($this->line->fk_fournprice);exit; // Multicurrency - $this->line->fk_multicurrency = $this->fk_multicurrency; - $this->line->multicurrency_code = $this->multicurrency_code; + $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; // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code=3; + if (empty($qty) && empty($special_code)) $this->line->special_code = 3; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; + if (is_array($array_option) && count($array_option) > 0) { + $this->line->array_options = $array_option; } - $result=$this->line->insert(); + $result = $this->line->insert(); if ($result > 0) { // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); // Mise a jour informations denormalisees au niveau de la propale meme - $result=$this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. + $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(); @@ -624,14 +624,14 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } } else { - $this->error=$this->line->error; + $this->error = $this->line->error; $this->db->rollback(); return -2; } @@ -672,21 +672,21 @@ class SupplierProposal extends CommonObject */ public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $array_options = 0, $ref_supplier = '', $fk_unit = '', $pu_ht_devise = 0) { - global $conf,$user,$langs, $mysoc; + global $conf, $user, $langs, $mysoc; dol_syslog(get_class($this)."::updateLine $rowid, $pu, $qty, $remise_percent, $txtva, $desc, $price_base_type, $info_bits"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); + $remise_percent = price2num($remise_percent); + $qty = price2num($qty); $pu = price2num($pu); $txtva = price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag - if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag + $txlocaltax1 = price2num($txlocaltax1); + $txlocaltax2 = price2num($txlocaltax2); + $pa_ht = price2num($pa_ht); + if (empty($qty) && empty($special_code)) $special_code = 3; // Set option tag + if (!empty($qty) && $special_code == 3) $special_code = 0; // Remove option tag if ($this->statut == 0) { @@ -697,18 +697,18 @@ class SupplierProposal extends CommonObject // 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 $reg = array(); - $vat_src_code=''; + $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + $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); + $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]; @@ -733,20 +733,20 @@ class SupplierProposal extends CommonObject $this->line->context = $this->context; // Reorder if fk_parent_line change - if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) + if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } $this->line->id = $rowid; - $this->line->label = $label; - $this->line->desc = $desc; + $this->line->label = $label; + $this->line->desc = $desc; $this->line->qty = $qty; - $this->line->product_type = $type; + $this->line->product_type = $type; - $this->line->vat_src_code = $vat_src_code; - $this->line->tva_tx = $txtva; + $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]; @@ -759,11 +759,11 @@ class SupplierProposal extends CommonObject $this->line->total_localtax1 = $total_localtax1; $this->line->total_localtax2 = $total_localtax2; $this->line->total_ttc = $total_ttc; - $this->line->special_code = $special_code; + $this->line->special_code = $special_code; $this->line->fk_parent_line = $fk_parent_line; - $this->line->skip_update_total = $skip_update_total; - $this->line->ref_fourn = $ref_supplier; - $this->line->fk_unit = $fk_unit; + $this->line->skip_update_total = $skip_update_total; + $this->line->ref_fourn = $ref_supplier; + $this->line->fk_unit = $fk_unit; // infos marge if (!empty($fk_product) && empty($fk_fournprice) && empty($pa_ht)) { @@ -777,9 +777,9 @@ class SupplierProposal extends CommonObject } $this->line->pa_ht = $pa_ht; - if (is_array($array_options) && count($array_options)>0) { + 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) { + foreach ($array_options as $key => $value) { $this->line->array_options[$key] = $array_options[$key]; } } @@ -790,11 +790,11 @@ class SupplierProposal extends CommonObject $this->line->multicurrency_total_tva = $multicurrency_total_tva; $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $result=$this->line->update(); + $result = $this->line->update(); if ($result > 0) { // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); $this->update_price(1); @@ -805,7 +805,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -828,7 +828,7 @@ class SupplierProposal extends CommonObject { if ($this->statut == 0) { - $line=new SupplierProposalLine($this->db); + $line = new SupplierProposalLine($this->db); // For triggers $line->fetch($lineid); @@ -862,28 +862,28 @@ class SupplierProposal extends CommonObject public function create($user, $notrigger = 0) { global $langs, $conf, $mysoc, $hookmanager; - $error=0; + $error = 0; - $now=dol_now(); + $now = dol_now(); dol_syslog(get_class($this)."::create"); // Check parameters - $result=$this->fetch_thirdparty(); + $result = $this->fetch_thirdparty(); if ($result < 0) { - $this->error="Failed to fetch company"; + $this->error = "Failed to fetch company"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } // Check parameters - if (! empty($this->ref)) // We check that ref is not already used + if (!empty($this->ref)) // We check that ref is not already used { - $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used + $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used if ($result > 0) { - $this->error='ErrorRefAlreadyExists'; + $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); return -1; @@ -891,7 +891,7 @@ class SupplierProposal extends CommonObject } // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); + 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; @@ -903,87 +903,87 @@ class SupplierProposal extends CommonObject // Insert into database $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal ("; - $sql.= "fk_soc"; - $sql.= ", price"; - $sql.= ", remise"; - $sql.= ", remise_percent"; - $sql.= ", remise_absolue"; - $sql.= ", tva"; - $sql.= ", total"; - $sql.= ", datec"; - $sql.= ", ref"; - $sql.= ", fk_user_author"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", model_pdf"; - $sql.= ", fk_cond_reglement"; - $sql.= ", fk_mode_reglement"; - $sql.= ", fk_account"; - $sql.= ", date_livraison"; - $sql.= ", fk_shipping_method"; - $sql.= ", fk_projet"; - $sql.= ", entity"; - $sql.= ", fk_multicurrency"; - $sql.= ", multicurrency_code"; - $sql.= ", multicurrency_tx"; - $sql.= ") "; - $sql.= " VALUES ("; - $sql.= $this->socid; - $sql.= ", 0"; - $sql.= ", ".$this->remise; - $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'null'); - $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'null'); - $sql.= ", 0"; - $sql.= ", 0"; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", '(PROV)'"; - $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null"); - $sql.= ", '".$this->db->escape($this->note_private)."'"; - $sql.= ", '".$this->db->escape($this->note_public)."'"; - $sql.= ", '".$this->db->escape($this->modelpdf)."'"; - $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->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"null"); - $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); - $sql.= ", ".($this->fk_project?$this->fk_project:"null"); - $sql.= ", ".$conf->entity; - $sql.= ", ".(int) $this->fk_multicurrency; - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".(double) $this->multicurrency_tx; - $sql.= ")"; + $sql .= "fk_soc"; + $sql .= ", price"; + $sql .= ", remise"; + $sql .= ", remise_percent"; + $sql .= ", remise_absolue"; + $sql .= ", tva"; + $sql .= ", total"; + $sql .= ", datec"; + $sql .= ", ref"; + $sql .= ", fk_user_author"; + $sql .= ", note_private"; + $sql .= ", note_public"; + $sql .= ", model_pdf"; + $sql .= ", fk_cond_reglement"; + $sql .= ", fk_mode_reglement"; + $sql .= ", fk_account"; + $sql .= ", date_livraison"; + $sql .= ", fk_shipping_method"; + $sql .= ", fk_projet"; + $sql .= ", entity"; + $sql .= ", fk_multicurrency"; + $sql .= ", multicurrency_code"; + $sql .= ", multicurrency_tx"; + $sql .= ") "; + $sql .= " VALUES ("; + $sql .= $this->socid; + $sql .= ", 0"; + $sql .= ", ".$this->remise; + $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null'); + $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null'); + $sql .= ", 0"; + $sql .= ", 0"; + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '(PROV)'"; + $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null"); + $sql .= ", '".$this->db->escape($this->note_private)."'"; + $sql .= ", '".$this->db->escape($this->note_public)."'"; + $sql .= ", '".$this->db->escape($this->modelpdf)."'"; + $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->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "null"); + $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL'); + $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); + $sql .= ", ".$conf->entity; + $sql .= ", ".(int) $this->fk_multicurrency; + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".(double) $this->multicurrency_tx; + $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal"); if ($this->id) { - $this->ref='(PROV'.$this->id.')'; + $this->ref = '(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $error++; + $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 + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) { - foreach($this->linked_objects as $origin => $tmp_origin_id) + 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) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) + if (!$ret) { dol_print_error($this->db); $error++; @@ -996,12 +996,12 @@ class SupplierProposal extends CommonObject /* * Insertion du detail des produits dans la base */ - if (! $error) + if (!$error) { - $fk_parent_line=0; - $num=count($this->lines); + $fk_parent_line = 0; + $num = count($this->lines); - for ($i=0;$i<$num;$i++) + for ($i = 0; $i < $num; $i++) { // Reset fk_parent_line for no child products and special product if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { @@ -1037,7 +1037,7 @@ class SupplierProposal extends CommonObject if ($result < 0) { $error++; - $this->error=$this->db->error; + $this->error = $this->db->error; dol_print_error($this->db); break; } @@ -1048,46 +1048,46 @@ class SupplierProposal extends CommonObject } } - if (! $error) + if (!$error) { // Mise a jour infos denormalisees - $resql=$this->update_price(1); + $resql = $this->update_price(1); if ($resql) { - $action='update'; + $action = 'update'; // Actions on extra fields - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) + if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('PROPAL_SUPPLIER_CREATE', $user); + $result = $this->call_trigger('PROPAL_SUPPLIER_CREATE', $user); if ($result < 0) { $error++; } // End call triggers } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } - if (! $error) + if (!$error) { $this->db->commit(); dol_syslog(get_class($this)."::create done id=".$this->id); @@ -1101,7 +1101,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1119,7 +1119,7 @@ class SupplierProposal extends CommonObject public function create_from($user) { // phpcs:enable - $this->products=$this->lines; + $this->products = $this->lines; return $this->create($user); } @@ -1133,31 +1133,31 @@ class SupplierProposal extends CommonObject */ public function createFromClone(User $user, $fromid = 0) { - global $conf,$hookmanager; + global $conf, $hookmanager; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); $this->db->begin(); // get extrafields so they will be clone - foreach($this->lines as $line) + foreach ($this->lines as $line) $line->fetch_optionals(); // Load source object $objFrom = clone $this; - $objsoc=new Societe($this->db); + $objsoc = new Societe($this->db); // Change socid if needed - if (! empty($fromid) && $fromid != $this->socid) + if (!empty($fromid) && $fromid != $this->socid) { if ($objsoc->fetch($fromid) > 0) { - $this->socid = $objsoc->id; - $this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $this->fk_project = ''; + $this->socid = $objsoc->id; + $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $this->fk_project = ''; } // TODO Change product price if multi-prices @@ -1167,39 +1167,39 @@ class SupplierProposal extends CommonObject $objsoc->fetch($this->socid); } - $this->id=0; - $this->statut=0; + $this->id = 0; + $this->statut = 0; - if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT ."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) + if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php")) { - $this->error='ErrorSetupNotComplete'; + $this->error = 'ErrorSetupNotComplete'; return -1; } // Clear fields - $this->user_author = $user->id; - $this->user_valid = ''; - $this->date = $now; + $this->user_author = $user->id; + $this->user_valid = ''; + $this->date = $now; // Set ref - require_once DOL_DOCUMENT_ROOT ."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php'; + require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php'; $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON; $modSupplierProposal = new $obj; $this->ref = $modSupplierProposal->getNextValue($objsoc, $this); // Create clone $this->context['createfromclone'] = 'createfromclone'; - $result=$this->create($user); + $result = $this->create($user); if ($result < 0) $error++; - if (! $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 + $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++; } } @@ -1207,7 +1207,7 @@ class SupplierProposal extends CommonObject unset($this->context['createfromclone']); // End - if (! $error) + if (!$error) { $this->db->commit(); return $this->id; @@ -1231,32 +1231,32 @@ class SupplierProposal extends CommonObject global $conf; $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; - $sql.= ", p.datec"; - $sql.= ", p.date_valid as datev"; - $sql.= ", p.date_livraison as date_livraison"; - $sql.= ", p.model_pdf, p.extraparams"; - $sql.= ", p.note_private, p.note_public"; - $sql.= ", p.fk_projet as fk_project, p.fk_statut"; - $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; - $sql.= ", p.fk_cond_reglement"; - $sql.= ", p.fk_mode_reglement"; - $sql.= ', p.fk_account'; - $sql.= ", p.fk_shipping_method"; - $sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; - $sql.= ", c.label as statut_label"; - $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; - $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; - $sql.= " WHERE p.fk_statut = c.id"; - $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; - if ($ref) $sql.= " AND p.ref='".$ref."'"; - else $sql.= " AND p.rowid=".$rowid; + $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql .= ", p.datec"; + $sql .= ", p.date_valid as datev"; + $sql .= ", p.date_livraison as date_livraison"; + $sql .= ", p.model_pdf, p.extraparams"; + $sql .= ", p.note_private, p.note_public"; + $sql .= ", p.fk_projet as fk_project, p.fk_statut"; + $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; + $sql .= ", p.fk_cond_reglement"; + $sql .= ", p.fk_mode_reglement"; + $sql .= ', p.fk_account'; + $sql .= ", p.fk_shipping_method"; + $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; + $sql .= ", c.label as statut_label"; + $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; + $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; + $sql .= " WHERE p.fk_statut = c.id"; + $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")"; + if ($ref) $sql .= " AND p.ref='".$ref."'"; + else $sql .= " AND p.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) @@ -1286,21 +1286,21 @@ class SupplierProposal extends CommonObject $this->statut_libelle = $obj->statut_label; $this->datec = $this->db->jdate($obj->datec); // TODO deprecated $this->datev = $this->db->jdate($obj->datev); // TODO deprecated - $this->date_creation = $this->db->jdate($obj->datec); //Creation date - $this->date_validation = $this->db->jdate($obj->datev); //Validation date + $this->date_creation = $this->db->jdate($obj->datec); //Creation date + $this->date_validation = $this->db->jdate($obj->datev); //Validation date $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; + $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement; - $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; + $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement; $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); $this->user_author_id = $obj->fk_user_author; $this->user_valid_id = $obj->fk_user_valid; @@ -1308,9 +1308,9 @@ class SupplierProposal extends CommonObject // Multicurrency $this->fk_multicurrency = $obj->fk_multicurrency; - $this->multicurrency_code = $obj->multicurrency_code; + $this->multicurrency_code = $obj->multicurrency_code; $this->multicurrency_tx = $obj->multicurrency_tx; - $this->multicurrency_total_ht = $obj->multicurrency_total_ht; + $this->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; @@ -1329,14 +1329,14 @@ class SupplierProposal extends CommonObject // Lines of supplier proposals $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,"; - $sql.= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; - $sql.= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; - $sql.= ' d.ref_fourn as ref_produit_fourn,'; - $sql.= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit'; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; - $sql.= " WHERE d.fk_supplier_proposal = ".$this->id; - $sql.= " ORDER by d.rang"; + $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,"; + $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,'; + $sql .= ' d.ref_fourn as ref_produit_fourn,'; + $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit'; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; + $sql .= " WHERE d.fk_supplier_proposal = ".$this->id; + $sql .= " ORDER by d.rang"; $result = $this->db->query($sql); if ($result) @@ -1350,13 +1350,13 @@ class SupplierProposal extends CommonObject $line = new SupplierProposalLine($this->db); - $line->rowid = $objp->rowid; // deprecated - $line->id = $objp->rowid; - $line->fk_supplier_proposal = $objp->fk_supplier_proposal; - $line->fk_parent_line = $objp->fk_parent_line; + $line->rowid = $objp->rowid; // deprecated + $line->id = $objp->rowid; + $line->fk_supplier_proposal = $objp->fk_supplier_proposal; + $line->fk_parent_line = $objp->fk_parent_line; $line->product_type = $objp->product_type; $line->label = $objp->custom_label; - $line->desc = $objp->description; // Description ligne + $line->desc = $objp->description; // Description ligne $line->qty = $objp->qty; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; @@ -1372,8 +1372,8 @@ class SupplierProposal extends CommonObject $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; $line->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); - $line->pa_ht = $marginInfos[0]; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); + $line->pa_ht = $marginInfos[0]; $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->special_code = $objp->special_code; @@ -1381,25 +1381,25 @@ class SupplierProposal extends CommonObject $line->fk_product = $objp->fk_product; - $line->ref = $objp->product_ref; // deprecated - $line->product_ref = $objp->product_ref; - $line->libelle = $objp->product_label; // deprecated - $line->product_label = $objp->product_label; - $line->product_desc = $objp->product_desc; // Description produit + $line->ref = $objp->product_ref; // deprecated + $line->product_ref = $objp->product_ref; + $line->libelle = $objp->product_label; // deprecated + $line->product_label = $objp->product_label; + $line->product_desc = $objp->product_desc; // Description produit $line->fk_product_type = $objp->fk_product_type; - $line->ref_fourn = $objp->ref_produit_fourn; + $line->ref_fourn = $objp->ref_produit_fourn; // Multicurrency - $line->fk_multicurrency = $objp->fk_multicurrency; - $line->multicurrency_code = $objp->multicurrency_code; + $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->fk_unit = $objp->fk_unit; + $line->fk_unit = $objp->fk_unit; - $this->lines[$i] = $line; + $this->lines[$i] = $line; $i++; } @@ -1407,7 +1407,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } @@ -1418,12 +1418,12 @@ class SupplierProposal extends CommonObject return 1; } - $this->error="Record Not Found"; + $this->error = "Record Not Found"; return 0; } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1439,13 +1439,13 @@ class SupplierProposal extends CommonObject { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - global $conf,$langs; + global $conf, $langs; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->supplier_proposal->validate_advance))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer)) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance))) { $this->db->begin(); @@ -1454,7 +1454,7 @@ class SupplierProposal extends CommonObject $soc->fetch($this->socid); // Define new ref - if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life { $num = $this->getNextNumRef($soc); } @@ -1465,28 +1465,28 @@ class SupplierProposal extends CommonObject $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql.= " SET ref = '".$this->db->escape($num)."',"; - $sql.= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; dol_syslog(get_class($this)."::valid", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + $resql = $this->db->query($sql); + if (!$resql) { dol_print_error($this->db); $error++; } // Trigger calls - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PROPOSAL_VALIDATE', $user); + $result = $this->call_trigger('SUPPLIER_PROPOSAL_VALIDATE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $this->oldref = $this->ref; @@ -1494,41 +1494,41 @@ class SupplierProposal extends CommonObject if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index - $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref)+1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'"; - $sql.= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'supplier_proposal/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->supplier_proposal->dir_output.'/'.$oldref; $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref; - if (! $error && file_exists($dirsource)) + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->supplier_proposal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach($listoffiles as $fileentry) + $listoffiles = dol_dir_list($conf->supplier_proposal->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; + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } } } - $this->ref=$num; - $this->brouillon=0; + $this->ref = $num; + $this->brouillon = 0; $this->statut = 1; - $this->user_valid_id=$user->id; - $this->datev=$now; + $this->user_valid_id = $user->id; + $this->datev = $now; $this->db->commit(); return 1; @@ -1557,11 +1557,11 @@ class SupplierProposal extends CommonObject public function set_date_livraison($user, $date_livraison) { // phpcs:enable - if (! empty($user->rights->supplier_proposal->creer)) + if (!empty($user->rights->supplier_proposal->creer)) { $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; - $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null'); + $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { @@ -1570,7 +1570,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_syslog(get_class($this)."::set_date_livraison Erreur SQL"); return -1; } @@ -1588,16 +1588,16 @@ class SupplierProposal extends CommonObject public function set_remise_percent($user, $remise) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; - if (! empty($user->rights->supplier_proposal->creer)) + if (!empty($user->rights->supplier_proposal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql) ) + if ($this->db->query($sql)) { $this->remise_percent = $remise; $this->update_price(1); @@ -1605,7 +1605,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1623,17 +1623,17 @@ class SupplierProposal extends CommonObject public function set_remise_absolue($user, $remise) { // phpcs:enable - $remise=trim($remise)?trim($remise):0; + $remise = trim($remise) ?trim($remise) : 0; - if (! empty($user->rights->supplier_proposal->creer)) + if (!empty($user->rights->supplier_proposal->creer)) { $remise = price2num($remise); $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal "; - $sql.= " SET remise_absolue = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql .= " SET remise_absolue = ".$remise; + $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql) ) + if ($this->db->query($sql)) { $this->remise_absolue = $remise; $this->update_price(1); @@ -1641,7 +1641,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -1660,30 +1660,30 @@ class SupplierProposal extends CommonObject */ public function reopen($user, $statut, $note = '', $notrigger = 0) { - global $langs,$conf; + global $langs, $conf; $this->statut = $statut; - $error=0; + $error = 0; $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql.= " SET fk_statut = ".$this->statut.","; - if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',"; - $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".$this->statut.","; + if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',"; + $sql .= " date_cloture=NULL, fk_user_cloture=NULL"; + $sql .= " WHERE rowid = ".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (! $error) + if (!$error) { - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PROPOSAL_REOPEN', $user); + $result = $this->call_trigger('SUPPLIER_PROPOSAL_REOPEN', $user); if ($result < 0) { $error++; } // End call triggers } @@ -1694,14 +1694,14 @@ class SupplierProposal extends CommonObject { if (!empty($this->errors)) { - foreach($this->errors as $errmsg) + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } } $this->db->rollback(); - return -1*$error; + return -1 * $error; } else { @@ -1721,46 +1721,46 @@ class SupplierProposal extends CommonObject */ public function cloture($user, $status, $note) { - global $langs,$conf; + global $langs, $conf; $this->statut = $status; - $error=0; - $now=dol_now(); + $error = 0; + $now = dol_now(); $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql.= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql .= " WHERE rowid = ".$this->id; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $modelpdf=$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED?$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED:$this->modelpdf; + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf; $triggerName = 'SUPPLIER_PROPOSAL_CLOSE_REFUSED'; if ($status == 2) { - $triggerName='SUPPLIER_PROPOSAL_CLOSE_SIGNED'; - $modelpdf=$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL?$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL:$this->modelpdf; + $triggerName = 'SUPPLIER_PROPOSAL_CLOSE_SIGNED'; + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf; - if (! empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists + if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists { $result = $this->updateOrCreatePriceFournisseur($user); } } if ($status == 4) { - $triggerName='SUPPLIER_PROPOSAL_CLASSIFY_BILLED'; + $triggerName = 'SUPPLIER_PROPOSAL_CLASSIFY_BILLED'; } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + if (!empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang=(GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); + $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } //$ret=$object->fetch($id); // Reload to get new records @@ -1768,11 +1768,11 @@ class SupplierProposal extends CommonObject } // Call trigger - $result=$this->call_trigger($triggerName, $user); + $result = $this->call_trigger($triggerName, $user); if ($result < 0) { $error++; } // End call triggers - if ( ! $error ) + if (!$error) { $this->db->commit(); return 1; @@ -1785,8 +1785,8 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $this->error = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); $this->db->rollback(); return -1; } @@ -1834,14 +1834,14 @@ class SupplierProposal extends CommonObject */ public function updatePriceFournisseur($idProductFournPrice, $product, $user) { - $price=price2num($product->subprice*$product->qty, 'MU'); + $price = price2num($product->subprice * $product->qty, 'MU'); $unitPrice = price2num($product->subprice, 'MU'); $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$product->ref_fourn.'", ' : '').' price ='.$price.', unitprice ='.$unitPrice.' WHERE rowid = '.$idProductFournPrice; $resql = $this->db->query($sql); if (!$resql) { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1856,10 +1856,10 @@ class SupplierProposal extends CommonObject */ public function createPriceFournisseur($product, $user) { - $price=price2num($product->subprice*$product->qty, 'MU'); - $qty=price2num($product->qty); + $price = price2num($product->subprice * $product->qty, 'MU'); + $qty = price2num($product->qty); $unitPrice = price2num($product->subprice, 'MU'); - $now=dol_now(); + $now = dol_now(); $values = array( "'".$this->db->idate($now)."'", @@ -1878,7 +1878,7 @@ class SupplierProposal extends CommonObject $resql = $this->db->query($sql); if (!$resql) { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -1; } @@ -1894,7 +1894,7 @@ class SupplierProposal extends CommonObject public function setDraft($user) { // phpcs:enable - global $conf,$langs; + global $conf, $langs; $error = 0; @@ -1905,8 +1905,8 @@ class SupplierProposal extends CommonObject } $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal"; - $sql.= " SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET fk_statut = ".self::STATUS_DRAFT; + $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) { @@ -1916,12 +1916,12 @@ class SupplierProposal extends CommonObject if (!$error) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PROPOSAL_UNVALIDATE', $user); + $result = $this->call_trigger('SUPPLIER_PROPOSAL_UNVALIDATE', $user); if ($result < 0) $error++; } if (!$error) { - $this->statut=self::STATUS_DRAFT; + $this->statut = self::STATUS_DRAFT; $this->brouillon = 1; $this->db->commit(); return 1; @@ -1954,30 +1954,30 @@ class SupplierProposal extends CommonObject public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC') { // phpcs:enable - global $conf,$user; + global $conf, $user; $ga = array(); $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql.= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; - $sql.= " p.datep as dp, p.fin_validite as datelimite"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.entity IN (".getEntity('supplier_proposal').")"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.fk_statut = c.id"; - if (! $user->rights->societe->client->voir && ! $socid) //restriction + $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; + $sql .= " p.datep as dp, p.fin_validite as datelimite"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + $sql .= " AND p.fk_statut = c.id"; + if (!$user->rights->societe->client->voir && !$socid) //restriction { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($draft) $sql.= " AND p.fk_statut = 0"; - if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; - $sql.= $this->db->order($sortfield, $sortorder); - $sql.= $this->db->plimit($limit, $offset); + if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($draft) $sql .= " AND p.fk_statut = 0"; + if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id; + $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->plimit($limit, $offset); - $result=$this->db->query($sql); + $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); @@ -1998,7 +1998,7 @@ class SupplierProposal extends CommonObject } else { - $ga[$i]['id'] = $obj->supplier_proposalid; + $ga[$i]['id'] = $obj->supplier_proposalid; $ga[$i]['ref'] = $obj->ref; $ga[$i]['name'] = $obj->name; } @@ -2024,22 +2024,22 @@ class SupplierProposal extends CommonObject */ public function delete($user, $notrigger = 0) { - global $conf,$langs; + global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error = 0; $this->db->begin(); - if (! $notrigger) + if (!$notrigger) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PROPOSAL_DELETE', $user); + $result = $this->call_trigger('SUPPLIER_PROPOSAL_DELETE', $user); if ($result < 0) { $error++; } // End call triggers } - if (! $error) + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id; if ($this->db->query($sql)) @@ -2051,33 +2051,33 @@ class SupplierProposal extends CommonObject $res = $this->deleteObjectLinked(); if ($res < 0) $error++; - if (! $error) + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); if ($conf->supplier_proposal->dir_output && !empty($this->ref)) { - $dir = $conf->supplier_proposal->dir_output . "/" . $ref ; - $file = $dir . "/" . $ref . ".pdf"; + $dir = $conf->supplier_proposal->dir_output."/".$ref; + $file = $dir."/".$ref.".pdf"; if (file_exists($file)) { dol_delete_preview($this); - if (! dol_delete_file($file, 0, 0, 0, $this)) // For triggers + if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers { - $this->error='ErrorFailToDeleteFile'; - $this->errors=array('ErrorFailToDeleteFile'); + $this->error = 'ErrorFailToDeleteFile'; + $this->errors = array('ErrorFailToDeleteFile'); $this->db->rollback(); return 0; } } if (file_exists($dir)) { - $res=@dol_delete_dir_recursive($dir); - if (! $res) + $res = @dol_delete_dir_recursive($dir); + if (!$res) { - $this->error='ErrorFailToDeleteDir'; - $this->errors=array('ErrorFailToDeleteDir'); + $this->error = 'ErrorFailToDeleteDir'; + $this->errors = array('ErrorFailToDeleteDir'); $this->db->rollback(); return 0; } @@ -2086,21 +2086,21 @@ class SupplierProposal extends CommonObject } // Removed extrafields - if (! $error) + if (!$error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; - $errorflag=-4; + $errorflag = -4; dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); } } } - if (! $error) + if (!$error) { dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); $this->db->commit(); @@ -2108,21 +2108,21 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -3; } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -2; } @@ -2143,10 +2143,10 @@ class SupplierProposal extends CommonObject public function info($id) { $sql = "SELECT c.rowid, "; - $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; - $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; - $sql.= " WHERE c.rowid = ".$id; + $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; + $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c"; + $sql .= " WHERE c.rowid = ".$id; $result = $this->db->query($sql); @@ -2164,20 +2164,20 @@ class SupplierProposal extends CommonObject $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $this->user_creation = $cuser; if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; + $this->user_validation = $vuser; } if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; + $this->user_cloture = $cluser; } } $this->db->free($result); @@ -2217,24 +2217,24 @@ class SupplierProposal extends CommonObject { global $langs; $langs->load("supplier_proposal"); - $this->labelStatus[self::STATUS_DRAFT]=$langs->trans("SupplierProposalStatusDraft"); - $this->labelStatus[self::STATUS_VALIDATED]=$langs->trans("SupplierProposalStatusValidated"); - $this->labelStatus[self::STATUS_SIGNED]=$langs->trans("SupplierProposalStatusSigned"); - $this->labelStatus[self::STATUS_NOTSIGNED]=$langs->trans("SupplierProposalStatusNotSigned"); - $this->labelStatus[self::STATUS_CLOSE]=$langs->trans("SupplierProposalStatusClosed"); - $this->labelStatusShort[self::STATUS_DRAFT]=$langs->trans("SupplierProposalStatusDraftShort"); - $this->labelStatusShort[self::STATUS_VALIDATED]=$langs->trans("Opened"); - $this->labelStatusShort[self::STATUS_SIGNED]=$langs->trans("SupplierProposalStatusSignedShort"); - $this->labelStatusShort[self::STATUS_NOTSIGNED]=$langs->trans("SupplierProposalStatusNotSignedShort"); - $this->labelStatusShort[self::STATUS_CLOSE]=$langs->trans("SupplierProposalStatusClosedShort"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraft"); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans("SupplierProposalStatusValidated"); + $this->labelStatus[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSigned"); + $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSigned"); + $this->labelStatus[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosed"); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraftShort"); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans("Opened"); + $this->labelStatusShort[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSignedShort"); + $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSignedShort"); + $this->labelStatusShort[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosedShort"); } - $statusnew=''; - if ($status==self::STATUS_DRAFT) $statusnew='status0'; - elseif ($status==self::STATUS_VALIDATED) $statusnew='status1'; - elseif ($status==self::STATUS_SIGNED) $statusnew='status3'; - elseif ($status==self::STATUS_NOTSIGNED) $statusnew='status5'; - elseif ($status==self::STATUS_CLOSE) $statusnew='status6'; + $statusnew = ''; + if ($status == self::STATUS_DRAFT) $statusnew = 'status0'; + elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1'; + elseif ($status == self::STATUS_SIGNED) $statusnew = 'status3'; + elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status5'; + elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6'; return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode); } @@ -2253,51 +2253,51 @@ class SupplierProposal extends CommonObject // phpcs:enable global $conf, $user, $langs; - $now=dol_now(); + $now = dol_now(); - $this->nbtodo=$this->nbtodolate=0; + $this->nbtodo = $this->nbtodolate = 0; $clause = " WHERE"; $sql = "SELECT p.rowid, p.ref, p.datec as datec"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; if (!$user->rights->societe->client->voir && !$user->socid) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; + $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; } - $sql.= $clause." p.entity IN (".getEntity('supplier_proposal').")"; - if ($mode == 'opened') $sql.= " AND p.fk_statut = 1"; - if ($mode == 'signed') $sql.= " AND p.fk_statut = 2"; - if ($user->socid) $sql.= " AND p.fk_soc = ".$user->socid; + $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")"; + if ($mode == 'opened') $sql .= " AND p.fk_statut = 1"; + if ($mode == 'signed') $sql .= " AND p.fk_statut = 2"; + if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $label = $labelShort = ''; $status = ''; if ($mode == 'opened') { - $delay_warning=$conf->supplier_proposal->cloture->warning_delay; + $delay_warning = $conf->supplier_proposal->cloture->warning_delay; $status = self::STATUS_VALIDATED; $label = $langs->trans("SupplierProposalsToClose"); $labelShort = $langs->trans("ToAcceptRefuse"); } if ($mode == 'signed') { - $delay_warning=$conf->supplier_proposal->facturation->warning_delay; + $delay_warning = $conf->supplier_proposal->facturation->warning_delay; $status = self::STATUS_SIGNED; - $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered + $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered $labelShort = $langs->trans("ToClose"); } $response = new WorkboardResponse(); - $response->warning_delay = $delay_warning/60/60/24; + $response->warning_delay = $delay_warning / 60 / 60 / 24; $response->label = $label; $response->labelShort = $labelShort; $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?viewstatut='.$status; $response->img = img_object('', "propal"); // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; if ($mode == 'opened') @@ -2315,7 +2315,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -2330,14 +2330,14 @@ class SupplierProposal extends CommonObject */ public function initAsSpecimen() { - global $user,$langs,$conf; + global $user, $langs, $conf; // 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 .= " FROM ".MAIN_DB_PREFIX."product"; + $sql .= " WHERE entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); if ($resql) { @@ -2352,51 +2352,51 @@ class SupplierProposal extends CommonObject } // Initialise parametres - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->socid = 1; $this->date = time(); $this->cond_reglement_id = 1; $this->cond_reglement_code = 'RECEP'; $this->mode_reglement_id = 7; $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)'; // Lines $nbp = 5; $xnbp = 0; while ($xnbp < $nbp) { - $line=new SupplierProposalLine($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->tva_tx=19.6; - $line->localtax1_tx=0; - $line->localtax2_tx=0; + $line = new SupplierProposalLine($this->db); + $line->desc = $langs->trans("Description")." ".$xnbp; + $line->qty = 1; + $line->subprice = 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; + $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->total_ht = 100; + $line->total_ttc = 119.6; + $line->total_tva = 19.6; + $line->remise_percent = 00; } if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; + $line->fk_product = $prodids[$prodid]; } - $this->lines[$xnbp]=$line; + $this->lines[$xnbp] = $line; $this->total_ht += $line->total_ht; $this->total_tva += $line->total_tva; @@ -2417,27 +2417,27 @@ class SupplierProposal extends CommonObject // phpcs:enable global $conf, $user; - $this->nb=array(); + $this->nb = array(); $clause = "WHERE"; $sql = "SELECT count(p.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$user->socid) { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; + $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." p.entity IN (".getEntity('supplier_proposal').")"; + $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")"; - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) + while ($obj = $this->db->fetch_object($resql)) { - $this->nb["askprice"]=$obj->nb; + $this->nb["askprice"] = $obj->nb; } $this->db->free($resql); return 1; @@ -2445,7 +2445,7 @@ class SupplierProposal extends CommonObject else { dol_print_error($this->db); - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); return -1; } } @@ -2463,9 +2463,9 @@ class SupplierProposal extends CommonObject global $conf, $db, $langs; $langs->load("supplier_proposal"); - if (! empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) + if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON)) { - $mybool=false; + $mybool = false; $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php"; $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON; @@ -2476,10 +2476,10 @@ class SupplierProposal extends CommonObject $dir = dol_buildpath($reldir."core/modules/supplier_proposal/"); // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; + $mybool |= @include_once $dir.$file; } - if (! $mybool) + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; @@ -2495,7 +2495,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$obj->error; + $this->error = $obj->error; return ""; } } @@ -2522,58 +2522,58 @@ class SupplierProposal extends CommonObject { global $langs, $conf, $user; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips - $url=''; - $result=''; + $url = ''; + $result = ''; - $label=''.$langs->trans("ShowSupplierProposal").''; - if (! empty($this->ref)) - $label.= '
'.$langs->trans('Ref').': '.$this->ref; - if (! empty($this->ref_fourn)) - $label.= '
'.$langs->trans('RefSupplier').': '.$this->ref_fourn; - 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); + $label = ''.$langs->trans("ShowSupplierProposal").''; + if (!empty($this->ref)) + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->ref_fourn)) + $label .= '
'.$langs->trans('RefSupplier').': '.$this->ref_fourn; + 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 ($option == '') { - $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params; } if ($option == 'document') { - $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id. $get_params; + $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params; } 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'; + $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=''; + $linkclose = ''; if (empty($notooltip) && $user->rights->propal->lire) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowSupplierProposal"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowSupplierProposal"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; } $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $linkend = ''; - $picto='supplier_proposal'; + $picto = 'supplier_proposal'; $result .= $linkstart; - if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); - if ($withpicto != 2) $result.= $this->ref; + if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + if ($withpicto != 2) $result .= $this->ref; $result .= $linkend; if ($addlinktonotes) @@ -2605,16 +2605,16 @@ class SupplierProposal extends CommonObject // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; - $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; - $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; - $sql.= ' pt.product_type, pt.rang, pt.fk_parent_line,'; - $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; - $sql.= ' p.description as product_desc, pt.ref_fourn as ref_supplier,'; - $sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; - $sql.= ' WHERE pt.fk_supplier_proposal = '.$this->id; - $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; + $sql .= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; + $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; + $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,'; + $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; + $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,'; + $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; + $sql .= ' WHERE pt.fk_supplier_proposal = '.$this->id; + $sql .= ' ORDER BY pt.rang ASC, pt.rowid'; dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); $resql = $this->db->query($sql); @@ -2627,46 +2627,46 @@ class SupplierProposal extends CommonObject { $obj = $this->db->fetch_object($resql); - $this->lines[$i] = new SupplierProposalLine($this->db); - $this->lines[$i]->id = $obj->rowid; // for backward compatibility + $this->lines[$i] = new SupplierProposalLine($this->db); + $this->lines[$i]->id = $obj->rowid; // for backward compatibility $this->lines[$i]->rowid = $obj->rowid; $this->lines[$i]->label = $obj->custom_label; - $this->lines[$i]->description = $obj->description; - $this->lines[$i]->fk_product = $obj->fk_product; - $this->lines[$i]->ref = $obj->ref; - $this->lines[$i]->product_label = $obj->product_label; + $this->lines[$i]->description = $obj->description; + $this->lines[$i]->fk_product = $obj->fk_product; + $this->lines[$i]->ref = $obj->ref; + $this->lines[$i]->product_label = $obj->product_label; $this->lines[$i]->product_desc = $obj->product_desc; - $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated + $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated $this->lines[$i]->product_type = $obj->product_type; - $this->lines[$i]->qty = $obj->qty; - $this->lines[$i]->subprice = $obj->subprice; - $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; - $this->lines[$i]->remise_percent = $obj->remise_percent; - $this->lines[$i]->tva_tx = $obj->tva_tx; + $this->lines[$i]->qty = $obj->qty; + $this->lines[$i]->subprice = $obj->subprice; + $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; + $this->lines[$i]->remise_percent = $obj->remise_percent; + $this->lines[$i]->tva_tx = $obj->tva_tx; $this->lines[$i]->info_bits = $obj->info_bits; - $this->lines[$i]->total_ht = $obj->total_ht; + $this->lines[$i]->total_ht = $obj->total_ht; $this->lines[$i]->total_tva = $obj->total_tva; $this->lines[$i]->total_ttc = $obj->total_ttc; - $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; - $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); - $this->lines[$i]->pa_ht = $marginInfos[0]; - $this->lines[$i]->marge_tx = $marginInfos[1]; - $this->lines[$i]->marque_tx = $marginInfos[2]; - $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; - $this->lines[$i]->special_code = $obj->special_code; - $this->lines[$i]->rang = $obj->rang; + $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; + $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); + $this->lines[$i]->pa_ht = $marginInfos[0]; + $this->lines[$i]->marge_tx = $marginInfos[1]; + $this->lines[$i]->marque_tx = $marginInfos[2]; + $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; + $this->lines[$i]->special_code = $obj->special_code; + $this->lines[$i]->rang = $obj->rang; - $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated - $this->lines[$i]->ref_supplier = $obj->ref_supplier; + $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated + $this->lines[$i]->ref_supplier = $obj->ref_supplier; // Multicurrency - $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; - $this->lines[$i]->multicurrency_code = $obj->multicurrency_code; + $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; + $this->lines[$i]->multicurrency_code = $obj->multicurrency_code; $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice; $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht; $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $this->lines[$i]->fk_unit = $obj->fk_unit; + $this->lines[$i]->fk_unit = $obj->fk_unit; $i++; } @@ -2676,7 +2676,7 @@ class SupplierProposal extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); return -1; } } @@ -2698,12 +2698,12 @@ class SupplierProposal extends CommonObject $langs->load("supplier_proposal"); - if (! dol_strlen($modele)) { + if (!dol_strlen($modele)) { $modele = 'aurore'; if ($this->modelpdf) { $modele = $this->modelpdf; - } elseif (! empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) { + } elseif (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) { $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF; } } @@ -2746,17 +2746,17 @@ class SupplierProposalLine extends CommonObjectLine /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string ID to identify managed object */ - public $element='supplier_proposaldet'; + public $element = 'supplier_proposaldet'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='supplier_proposaldet'; + public $table_element = 'supplier_proposaldet'; public $oldline; @@ -2775,12 +2775,12 @@ class SupplierProposalLine extends CommonObjectLine */ public $fk_parent_line; - public $desc; // Description ligne + public $desc; // Description ligne /** * @var int ID */ - public $fk_product; // Id produit predefini + public $fk_product; // Id produit predefini /** * @deprecated @@ -2815,18 +2815,18 @@ class SupplierProposalLine extends CommonObjectLine public $marge_tx; public $marque_tx; - public $special_code; // Tag for special lines (exlusive tags) + public $special_code; // Tag for special lines (exlusive tags) // 1: frais de port // 2: ecotaxe // 3: option line (when qty = 0) - public $info_bits = 0; // Liste d'options cumulables: + public $info_bits = 0; // Liste d'options cumulables: // Bit 0: 0 si TVA normal - 1 si TVA NPR // Bit 1: 0 ligne normale - 1 si ligne de remise fixe - public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne - public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne - public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne + public $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne + public $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne + public $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne public $date_start; public $date_end; @@ -2862,12 +2862,12 @@ class SupplierProposalLine extends CommonObjectLine */ public $product_desc; - public $localtax1_tx; // Local tax 1 - public $localtax2_tx; // Local tax 2 - public $localtax1_type; // Local tax 1 type - public $localtax2_type; // Local tax 2 type - public $total_localtax1; // Line total local tax 1 - public $total_localtax2; // Line total local tax 2 + public $localtax1_tx; // Local tax 1 + public $localtax2_tx; // Local tax 2 + public $localtax1_type; // Local tax 1 type + public $localtax2_type; // Local tax 2 type + public $total_localtax1; // Line total local tax 1 + public $total_localtax2; // Line total local tax 2 public $skip_update_total; // Skip update price total for special lines @@ -2893,7 +2893,7 @@ class SupplierProposalLine extends CommonObjectLine */ public function __construct($db) { - $this->db= $db; + $this->db = $db; } /** @@ -2905,31 +2905,31 @@ class SupplierProposalLine extends CommonObjectLine public function fetch($rowid) { $sql = 'SELECT pd.rowid, pd.fk_supplier_proposal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.tva_tx,'; - $sql.= ' pd.date_start, pd.date_end,'; - $sql.= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,'; - $sql.= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,'; - $sql.= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,'; - $sql.= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; - $sql.= ' pd.product_type, pd.ref_fourn as ref_produit_fourn,'; - $sql.= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc, pd.fk_unit'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pd'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid'; - $sql.= ' WHERE pd.rowid = '.$rowid; + $sql .= ' pd.date_start, pd.date_end,'; + $sql .= ' pd.remise, pd.remise_percent, pd.fk_remise_except, pd.subprice,'; + $sql .= ' pd.info_bits, pd.total_ht, pd.total_tva, pd.total_ttc, pd.fk_product_fournisseur_price as fk_fournprice, pd.buy_price_ht as pa_ht, pd.special_code, pd.rang,'; + $sql .= ' pd.localtax1_tx, pd.localtax2_tx, pd.total_localtax1, pd.total_localtax2,'; + $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; + $sql .= ' pd.product_type, pd.ref_fourn as ref_produit_fourn,'; + $sql .= ' pd.fk_multicurrency, pd.multicurrency_code, pd.multicurrency_subprice, pd.multicurrency_total_ht, pd.multicurrency_total_tva, pd.multicurrency_total_ttc, pd.fk_unit'; + $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pd'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pd.fk_product = p.rowid'; + $sql .= ' WHERE pd.rowid = '.$rowid; $result = $this->db->query($sql); if ($result) { $objp = $this->db->fetch_object($result); - $this->id = $objp->rowid; - $this->fk_supplier_proposal = $objp->fk_supplier_proposal; - $this->fk_parent_line = $objp->fk_parent_line; + $this->id = $objp->rowid; + $this->fk_supplier_proposal = $objp->fk_supplier_proposal; + $this->fk_parent_line = $objp->fk_parent_line; $this->label = $objp->custom_label; $this->desc = $objp->description; - $this->qty = $objp->qty; - $this->subprice = $objp->subprice; - $this->tva_tx = $objp->tva_tx; - $this->remise_percent = $objp->remise_percent; + $this->qty = $objp->qty; + $this->subprice = $objp->subprice; + $this->tva_tx = $objp->tva_tx; + $this->remise_percent = $objp->remise_percent; $this->fk_remise_except = $objp->fk_remise_except; $this->fk_product = $objp->fk_product; $this->info_bits = $objp->info_bits; @@ -2940,7 +2940,7 @@ class SupplierProposalLine extends CommonObjectLine $this->total_tva = $objp->total_tva; $this->total_ttc = $objp->total_ttc; - $this->fk_fournprice = $objp->fk_fournprice; + $this->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); $this->pa_ht = $marginInfos[0]; @@ -2949,24 +2949,24 @@ class SupplierProposalLine extends CommonObjectLine $this->special_code = $objp->special_code; $this->product_type = $objp->product_type; - $this->rang = $objp->rang; + $this->rang = $objp->rang; - $this->ref = $objp->product_ref; // deprecated - $this->product_ref = $objp->product_ref; - $this->libelle = $objp->product_label; // deprecated + $this->ref = $objp->product_ref; // deprecated + $this->product_ref = $objp->product_ref; + $this->libelle = $objp->product_label; // deprecated $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; - $this->ref_fourn = $objp->ref_produit_forun; + $this->ref_fourn = $objp->ref_produit_forun; // Multicurrency - $this->fk_multicurrency = $objp->fk_multicurrency; - $this->multicurrency_code = $objp->multicurrency_code; + $this->fk_multicurrency = $objp->fk_multicurrency; + $this->multicurrency_code = $objp->multicurrency_code; $this->multicurrency_subprice = $objp->multicurrency_subprice; $this->multicurrency_total_ht = $objp->multicurrency_total_ht; $this->multicurrency_total_tva = $objp->multicurrency_total_tva; $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $this->fk_unit = $objp->fk_unit; + $this->fk_unit = $objp->fk_unit; $this->db->free($result); } @@ -2984,31 +2984,31 @@ class SupplierProposalLine extends CommonObjectLine */ public function insert($notrigger = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; - $error=0; + $error = 0; dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->localtax1_type)) $this->localtax1_type=0; - if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->rang)) $this->rang=0; - if (empty($this->remise)) $this->remise=0; - if (empty($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; - if (empty($this->fk_unit)) $this->fk_unit=0; - if (empty($this->subprice)) $this->subprice=0; + if (empty($this->tva_tx)) $this->tva_tx = 0; + if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; + if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; + if (empty($this->localtax1_type)) $this->localtax1_type = 0; + if (empty($this->localtax2_type)) $this->localtax2_type = 0; + if (empty($this->total_localtax1)) $this->total_localtax1 = 0; + if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->rang)) $this->rang = 0; + if (empty($this->remise)) $this->remise = 0; + if (empty($this->remise_percent)) $this->remise_percent = 0; + if (empty($this->info_bits)) $this->info_bits = 0; + if (empty($this->special_code)) $this->special_code = 0; + if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; + if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; + if (empty($this->fk_unit)) $this->fk_unit = 0; + if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->pa_ht)) $this->pa_ht=0; + if (empty($this->pa_ht)) $this->pa_ht = 0; // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0) @@ -3030,70 +3030,70 @@ class SupplierProposalLine extends CommonObjectLine // Insert line into database $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'supplier_proposaldet'; - $sql.= ' (fk_supplier_proposal, fk_parent_line, label, description, fk_product, product_type,'; - $sql.= ' date_start, date_end,'; - $sql.= ' fk_remise_except, qty, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql.= ' subprice, remise_percent, '; - $sql.= ' info_bits, '; - $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; - $sql.= ' ref_fourn,'; - $sql.= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc, fk_unit)'; - $sql.= " VALUES (".$this->fk_supplier_proposal.","; - $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)."',"; - $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; - $sql.= " '".$this->db->escape($this->product_type)."',"; - $sql.= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").","; - $sql.= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").","; - $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; - $sql.= " ".price2num($this->qty).","; - $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->subprice)?price2num($this->subprice):"null").","; - $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; - $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.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; - $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; - $sql.= ' '.$this->special_code.','; - $sql.= ' '.$this->rang.','; - $sql.= " '".$this->db->escape($this->ref_fourn)."'"; - $sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null'); - $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; - $sql.= ", ".$this->multicurrency_subprice; - $sql.= ", ".$this->multicurrency_total_ht; - $sql.= ", ".$this->multicurrency_total_tva; - $sql.= ", ".$this->multicurrency_total_ttc; - $sql.= ", ".($this->fk_unit?$this->fk_unit:'null'); - $sql.= ')'; + $sql .= ' (fk_supplier_proposal, fk_parent_line, label, description, fk_product, product_type,'; + $sql .= ' date_start, date_end,'; + $sql .= ' fk_remise_except, qty, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql .= ' subprice, remise_percent, '; + $sql .= ' info_bits, '; + $sql .= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; + $sql .= ' ref_fourn,'; + $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc, fk_unit)'; + $sql .= " VALUES (".$this->fk_supplier_proposal.","; + $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)."',"; + $sql .= " ".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : "null").","; + $sql .= " '".$this->db->escape($this->product_type)."',"; + $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").","; + $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").","; + $sql .= " ".($this->fk_remise_except ? "'".$this->db->escape($this->fk_remise_except)."'" : "null").","; + $sql .= " ".price2num($this->qty).","; + $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->subprice) ?price2num($this->subprice) : "null").","; + $sql .= " ".price2num($this->remise_percent).","; + $sql .= " ".(isset($this->info_bits) ? "'".$this->db->escape($this->info_bits)."'" : "null").","; + $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 .= " ".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null").","; + $sql .= " ".(isset($this->pa_ht) ? "'".price2num($this->pa_ht)."'" : "null").","; + $sql .= ' '.$this->special_code.','; + $sql .= ' '.$this->rang.','; + $sql .= " '".$this->db->escape($this->ref_fourn)."'"; + $sql .= ", ".($this->fk_multicurrency > 0 ? $this->fk_multicurrency : 'null'); + $sql .= ", '".$this->db->escape($this->multicurrency_code)."'"; + $sql .= ", ".$this->multicurrency_subprice; + $sql .= ", ".$this->multicurrency_total_ht; + $sql .= ", ".$this->multicurrency_total_tva; + $sql .= ", ".$this->multicurrency_total_ttc; + $sql .= ", ".($this->fk_unit ? $this->fk_unit : 'null'); + $sql .= ')'; dol_syslog(get_class($this).'::insert', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'supplier_proposaldet'); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'supplier_proposaldet'); if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINESUPPLIER_PROPOSAL_INSERT', $user); + $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_INSERT', $user); if ($result < 0) { $this->db->rollback(); @@ -3107,7 +3107,7 @@ class SupplierProposalLine extends CommonObjectLine } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } @@ -3120,19 +3120,19 @@ class SupplierProposalLine extends CommonObjectLine */ public function delete() { - global $conf,$langs,$user; + global $conf, $langs, $user; - $error=0; + $error = 0; $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE rowid = ".$this->id; dol_syslog("SupplierProposalLine::delete", LOG_DEBUG); - if ($this->db->query($sql) ) + if ($this->db->query($sql)) { // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used { - $result=$this->deleteExtraFields(); + $result = $this->deleteExtraFields(); if ($result < 0) { $error++; @@ -3141,7 +3141,7 @@ class SupplierProposalLine extends CommonObjectLine } // Call trigger - $result=$this->call_trigger('LINESUPPLIER_PROPOSAL_DELETE', $user); + $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_DELETE', $user); if ($result < 0) { $this->db->rollback(); @@ -3155,7 +3155,7 @@ class SupplierProposalLine extends CommonObjectLine } else { - $this->error=$this->db->error()." sql=".$sql; + $this->error = $this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } @@ -3169,29 +3169,29 @@ class SupplierProposalLine extends CommonObjectLine */ public function update($notrigger = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; - $error=0; + $error = 0; // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->localtax1_type)) $this->localtax1_type=0; - if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->marque_tx)) $this->marque_tx=0; - if (empty($this->marge_tx)) $this->marge_tx=0; - if (empty($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; - if (empty($this->fk_unit)) $this->fk_unit=0; - if (empty($this->subprice)) $this->subprice=0; + if (empty($this->tva_tx)) $this->tva_tx = 0; + if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; + if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; + if (empty($this->total_localtax1)) $this->total_localtax1 = 0; + if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->localtax1_type)) $this->localtax1_type = 0; + if (empty($this->localtax2_type)) $this->localtax2_type = 0; + if (empty($this->marque_tx)) $this->marque_tx = 0; + if (empty($this->marge_tx)) $this->marge_tx = 0; + if (empty($this->remise_percent)) $this->remise_percent = 0; + if (empty($this->info_bits)) $this->info_bits = 0; + if (empty($this->special_code)) $this->special_code = 0; + if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; + if (empty($this->fk_fournprice)) $this->fk_fournprice = 0; + if (empty($this->fk_unit)) $this->fk_unit = 0; + if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->pa_ht)) $this->pa_ht=0; + if (empty($this->pa_ht)) $this->pa_ht = 0; // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0) @@ -3210,61 +3210,61 @@ class SupplierProposalLine extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= " , product_type=".$this->product_type; - $sql.= " , date_start=".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null"); - $sql.= " , date_end=".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null"); - $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.= " , subprice=".price2num($this->subprice).""; - $sql.= " , remise_percent=".price2num($this->remise_percent).""; - $sql.= " , info_bits='".$this->db->escape($this->info_bits)."'"; + $sql .= " description='".$this->db->escape($this->desc)."'"; + $sql .= " , label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); + $sql .= " , product_type=".$this->product_type; + $sql .= " , date_start=".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null"); + $sql .= " , date_end=".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null"); + $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 .= " , subprice=".price2num($this->subprice).""; + $sql .= " , remise_percent=".price2num($this->remise_percent).""; + $sql .= " , info_bits='".$this->db->escape($this->info_bits)."'"; if (empty($this->skip_update_total)) { - $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 .= " , 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); - if (strlen($this->special_code)) $sql.= " , special_code=".$this->special_code; - $sql.= " , fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); - if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= " , ref_fourn=".(! empty($this->ref_fourn)?"'".$this->db->escape($this->ref_fourn)."'":"null"); - $sql.= " , fk_unit=".($this->fk_unit?$this->fk_unit:'null'); + $sql .= " , fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); + $sql .= " , buy_price_ht=".price2num($this->pa_ht); + if (strlen($this->special_code)) $sql .= " , special_code=".$this->special_code; + $sql .= " , fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); + if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + $sql .= " , ref_fourn=".(!empty($this->ref_fourn) ? "'".$this->db->escape($this->ref_fourn)."'" : "null"); + $sql .= " , fk_unit=".($this->fk_unit ? $this->fk_unit : 'null'); // 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_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)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); + $result = $this->insertExtraFields(); if ($result < 0) { $error++; } } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Call trigger - $result=$this->call_trigger('LINESUPPLIER_PROPOSAL_UPDATE', $user); + $result = $this->call_trigger('LINESUPPLIER_PROPOSAL_UPDATE', $user); if ($result < 0) { $this->db->rollback(); @@ -3278,7 +3278,7 @@ class SupplierProposalLine extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } @@ -3298,14 +3298,14 @@ class SupplierProposalLine extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposaldet SET"; - $sql.= " total_ht=".price2num($this->total_ht, 'MT'); - $sql.= ",total_tva=".price2num($this->total_tva, 'MT'); - $sql.= ",total_ttc=".price2num($this->total_ttc, 'MT'); - $sql.= " WHERE rowid = ".$this->id; + $sql .= " total_ht=".price2num($this->total_ht, 'MT'); + $sql .= ",total_tva=".price2num($this->total_tva, 'MT'); + $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT'); + $sql .= " WHERE rowid = ".$this->id; dol_syslog("SupplierProposalLine::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { $this->db->commit(); @@ -3313,7 +3313,7 @@ class SupplierProposalLine extends CommonObjectLine } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); $this->db->rollback(); return -2; } diff --git a/htdocs/takepos/admin/setup.php b/htdocs/takepos/admin/setup.php index ba066241d1f..f1308d8c309 100644 --- a/htdocs/takepos/admin/setup.php +++ b/htdocs/takepos/admin/setup.php @@ -75,11 +75,15 @@ if (GETPOST('action', 'alpha') == 'set') $res = dolibarr_set_const($db, "TAKEPOS_ORDER_PRINTERS", GETPOST('TAKEPOS_ORDER_PRINTERS', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_ORDER_NOTES", GETPOST('TAKEPOS_ORDER_NOTES', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_PHONE_BASIC_LAYOUT", GETPOST('TAKEPOS_PHONE_BASIC_LAYOUT', 'alpha'), 'chaine', 0, '', $conf->entity); + $res = dolibarr_set_const($db, "TAKEPOS_SUPPLEMENTS", GETPOST('TAKEPOS_SUPPLEMENTS', 'alpha'), 'chaine', 0, '', $conf->entity); + $res = dolibarr_set_const($db, "TAKEPOS_SUPPLEMENTS_CATEGORY", GETPOST('TAKEPOS_SUPPLEMENTS_CATEGORY', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_AUTO_PRINT_TICKETS", GETPOST('TAKEPOS_AUTO_PRINT_TICKETS', 'int'), 'int', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_NUMPAD", GETPOST('TAKEPOS_NUMPAD', 'alpha'), 'chaine', 0, '', $conf->entity); + $res = dolibarr_set_const($db, "TAKEPOS_COLOR_THEME", GETPOST('TAKEPOS_COLOR_THEME', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_NUM_TERMINALS", GETPOST('TAKEPOS_NUM_TERMINALS', 'alpha'), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_DIRECT_PAYMENT", GETPOST('TAKEPOS_DIRECT_PAYMENT', 'int'), 'int', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_CUSTOM_RECEIPT", GETPOST('TAKEPOS_CUSTOM_RECEIPT', 'int'), 'int', 0, '', $conf->entity); + //$res = dolibarr_set_const($db, "TAKEPOS_HEAD_BAR", GETPOST('TAKEPOS_HEAD_BAR', 'int'), 'int', 0, '', $conf->entity); $res = dolibarr_set_const($db, "TAKEPOS_EMAIL_TEMPLATE_INVOICE", GETPOST('TAKEPOS_EMAIL_TEMPLATE_INVOICE', 'alpha'), 'chaine', 0, '', $conf->entity); if (!empty($conf->global->TAKEPOS_ENABLE_SUMUP)) { $res = dolibarr_set_const($db, "TAKEPOS_SUMUP_AFFILIATE", GETPOST('TAKEPOS_SUMUP_AFFILIATE', 'alpha'), 'chaine', 0, '', $conf->entity); @@ -222,6 +226,22 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) print '
'; print $form->selectyesno("TAKEPOS_PHONE_BASIC_LAYOUT", $conf->global->TAKEPOS_PHONE_BASIC_LAYOUT, 1); print '
'; + print $langs->trans("ProductSupplements"); + print ''; + print $form->selectyesno("TAKEPOS_SUPPLEMENTS", $conf->global->TAKEPOS_SUPPLEMENTS, 1); + print '
'; + print $langs->trans("SupplementCategory"); + print ''; + print $form->select_all_categories(Categorie::TYPE_PRODUCT, $conf->global->TAKEPOS_SUPPLEMENTS_CATEGORY, 'TAKEPOS_SUPPLEMENTS_CATEGORY', 64, 0, 0); + print ajax_combobox('TAKEPOS_SUPPLEMENTS_CATEGORY'); + print "
'; @@ -238,6 +258,14 @@ $array = array(0=>$langs->trans("Numberspad"), 1=>$langs->trans("BillsCoinsPad") print $form->selectarray('TAKEPOS_NUMPAD', $array, (empty($conf->global->TAKEPOS_NUMPAD) ? '0' : $conf->global->TAKEPOS_NUMPAD), 0); print "
'; +print $langs->trans("ColorTheme"); +print ''; +$array = array(0=>"eldy", 1=>$langs->trans("Colorful")); +print $form->selectarray('TAKEPOS_COLOR_THEME', $array, (empty($conf->global->TAKEPOS_COLOR_THEME) ? '0' : $conf->global->TAKEPOS_COLOR_THEME), 0); +print "
'; print $langs->trans('DirectPaymentButton'); @@ -252,6 +280,14 @@ print ''; print $form->selectyesno("TAKEPOS_CUSTOM RECEIPT", $conf->global->TAKEPOS_CUSTOM_RECEIPT, 1); print "
'; +print $langs->trans('HeadBar'); +print ''; +print $form->selectyesno("TAKEPOS_HEAD_BAR", $conf->global->TAKEPOS_HEAD_BAR, 1); +print "
'; print $langs->trans('EmailTemplate'); diff --git a/htdocs/takepos/ajax/ajax.php b/htdocs/takepos/ajax/ajax.php index 7e3049f9f6e..74b24d78570 100644 --- a/htdocs/takepos/ajax/ajax.php +++ b/htdocs/takepos/ajax/ajax.php @@ -45,6 +45,7 @@ $id = GETPOST('id', 'int'); if ($action == 'getProducts') { $object = new Categorie($db); + if ($category=="supplements") $category=$conf->global->TAKEPOS_SUPPLEMENTS_CATEGORY; $result = $object->fetch($category); if ($result > 0) { diff --git a/htdocs/takepos/css/colorful.css b/htdocs/takepos/css/colorful.css new file mode 100644 index 00000000000..3cfd18e72f1 --- /dev/null +++ b/htdocs/takepos/css/colorful.css @@ -0,0 +1,25 @@ +button.calcbutton { + background-color: #008000 !important; +} + +button.calcbutton.poscolorblue { + background-color: #0000FF !important; +} + +button.calcbutton2 { + background-color: #0000FF !important; +} + +button.calcbutton2.poscolordelete { + background-color: #FF0000 !important; + color: #FFFFFF !important; +} + +button.actionbutton { + background: #FFB100 !important; +} + +tr.selected, tr.selected td { + background-color: #0000FF !important; + color: #FFFFFF !important; +} \ No newline at end of file diff --git a/htdocs/takepos/css/pos.css b/htdocs/takepos/css/pos.css.php similarity index 60% rename from htdocs/takepos/css/pos.css rename to htdocs/takepos/css/pos.css.php index e8e53a0c8bf..a847b5e6e47 100644 --- a/htdocs/takepos/css/pos.css +++ b/htdocs/takepos/css/pos.css.php @@ -1,17 +1,76 @@ + + * Copyright (C) 2006 Rodolphe Quiedeville + * Copyright (C) 2007-2017 Regis Houssin + * Copyright (C) 2011 Philippe Grand + * Copyright (C) 2012 Juanjo Menent + * Copyright (C) 2018 Ferran Marcet + * + * 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/theme/eldy/style.css.php + * \brief File for CSS style sheet Eldy + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url. +if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); +if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); + + +define('ISLOADEDBYSTEELSHEET', '1'); + + +session_cache_limiter('public'); + +require_once __DIR__.'/../../main.inc.php'; // __DIR__ allow this script to be included in custom themes +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + +// Define css type +top_httphead('text/css'); +// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. +if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); +else header('Cache-Control: no-cache'); + + +require DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; +if (defined('THEME_ONLY_CONSTANT')) return; + +?> + html,body { box-sizing: border-box; - padding:3px; + padding:0px; margin:0; height:100%; width:100%; } .bodytakepos { - background-color: #EEE; + background-color: #EEE; } .center { - text-align: center; + text-align: center; } button.calcbutton.poscolorblue { @@ -35,7 +94,7 @@ button.calcbutton { text-align: center; overflow: visible; /* removes extra width in IE */ width: calc(25% - 2px); - height: 24%; + height: calc(25% - 2px); font-weight: bold; background-color: #8c907e; color: #fff; @@ -57,7 +116,7 @@ button.calcbutton2 { text-align: center; overflow: visible; /* removes extra width in IE */ width: calc(25% - 2px); - height: 24%; + height: calc(25% - 2px); font-weight: bold; } @@ -72,7 +131,7 @@ button.calcbutton3 { font-size:120%; overflow: visible; /* removes extra width in IE */ width: calc(25% - 2px); - height: 24%; + height: calc(25% - 2px); } button.actionbutton { @@ -91,11 +150,11 @@ button.actionbutton { text-align: center; overflow: visible; /* removes extra width in IE */ width:33%; - height:24%; + height: calc(25% - 2px); } .takepospay { - font-size: 1.5em; + font-size: 1.5em; } .fa.fa-trash:before { @@ -107,7 +166,7 @@ div.wrapper{ float:left; /* important */ position:relative; /* important(so we can absolutely position the description div */ width:25%; - height:25%; + height:33%; margin:0; padding:1px; border: 2px solid #EEE; @@ -121,7 +180,7 @@ div.wrapper2{ float:left; /* important */ position:relative; /* important(so we can absolutely position the description div */ width:12.5%; - height:25%; + height:33%; margin:0; /* padding:1px; */ border: 2px solid #EEE; @@ -151,7 +210,7 @@ div.description{ opacity:1; /* transparency */ /*filter:alpha(opacity=80); IE transparency */ text-align:center; - + padding-top: 30px; background: -webkit-linear-gradient(top, rgba(255,255,255,0), rgba(255,255,255,0.98), rgba(255,255,255,1)); } @@ -180,9 +239,9 @@ table.postablelines tr td { div.paymentbordline { - width:50%; - background-color:#888; - border-radius: 8px; + width:50%; + background-color:#888; + border-radius: 8px; margin-bottom: 4px; } @@ -206,12 +265,25 @@ div.paymentbordline height: 34%; } +.row1withhead{ + margin: 0 auto; + width: 100%; + height: calc(50% - 35px); + padding-top: 5px; +} + .row2{ margin: 0 auto; width: 100%; height: 66%; } +.row2withhead{ + margin: 0 auto; + width: 100%; + height: 50%; +} + .div1{ height:100%; width: 34%; @@ -221,9 +293,10 @@ div.paymentbordline overflow: auto; /* background-color:white; */ padding-top: 0; - padding-bottom: 10px; + padding-bottom: 0; padding-right: 5px; padding-left: 5px; + min-height: 180px; } .div2{ @@ -233,7 +306,7 @@ div.paymentbordline float: left; box-sizing: border-box; padding-top: 0; - padding-bottom: 10px; + padding-bottom: 0; padding-right: 5px; padding-left: 5px; min-height: 180px; @@ -245,7 +318,7 @@ div.paymentbordline float: left; box-sizing: border-box; padding-top: 0; - padding-bottom: 10px; + padding-bottom: 0; padding-right: 5px; padding-left: 5px; } @@ -325,6 +398,46 @@ div.description_content { padding-right: 2px; } +.header{ + margin: 0 auto; + width: 100%; + height: 35px; + background: rgb(60,70,100); +} + +.topnav{ + background: rgb(); + background-image: linear-gradient(-45deg, , rgb()); + overflow: hidden; + height: 100%; +} + +.topnav a{ + float: left; + color: #f2f2f2; + padding: 6px 16px; + text-decoration: none; + font-size: 17px; +} + +.topnav a:hover{ + background-color: #ddd; + color: black; +} + +.topnav-right{ + float: right; +} + +.topnav input[type="text"] { + background-color: #fff; + color: #000; + float: left; + border-bottom: none !important; + margin-top: 4px; + margin-left: 6px; +} + @media screen and (min-width: 892px) { .calcbutton{ font-size: 18px; @@ -382,6 +495,12 @@ div.description_content { /* For small screens */ @media screen and (max-width: 767px) { + .topnav-right { + float: unset; + } + .header { + height: unset; + } div.container { overflow-x: scroll; } @@ -391,25 +510,33 @@ div.description_content { div.wrapper2 { width: 25%; } - + + div.div1 { + padding-bottom: 0; + margin-bottom: 10px; + } div.div1, div.div2, div.div3 { width: 100%; } - + div.row1 { height: unset; } - + div.div2 { min-height: unset; } - + + div.div3 { + height: unset; + } + button.calcbutton, button.calcbutton2 { min-height: 30px; } - + .takepospay { - font-size: 1.2em; + font-size: 1.2em; } - + } diff --git a/htdocs/takepos/floors.php b/htdocs/takepos/floors.php index 7fcd7a5f9d0..8624948e6ff 100644 --- a/htdocs/takepos/floors.php +++ b/htdocs/takepos/floors.php @@ -25,68 +25,68 @@ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); +if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); +if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); +if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -require '../main.inc.php'; // Load $user and permissions +require '../main.inc.php'; // Load $user and permissions -$langs->loadLangs(array("bills","orders","commercial","cashdesk")); +$langs->loadLangs(array("bills", "orders", "commercial", "cashdesk")); -$floor=GETPOST('floor', 'int'); -if ($floor=="") $floor=1; +$floor = GETPOST('floor', 'int'); +if ($floor == "") $floor = 1; $id = GETPOST('id', 'int'); $action = GETPOST('action', 'alpha'); $left = GETPOST('left', 'alpha'); $top = GETPOST('top', 'alpha'); -$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant +$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant $newname = GETPOST('newname', 'alpha'); $mode = GETPOST('mode', 'alpha'); -if ($action=="getTables") +if ($action == "getTables") { - $sql="SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables where floor=".$floor; + $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables where floor=".$floor; $resql = $db->query($sql); $rows = array(); - while($row = $db->fetch_array($resql)){ + while ($row = $db->fetch_array($resql)) { $rows[] = $row; } echo json_encode($rows); exit; } -if ($action=="update") +if ($action == "update") { - if ($left>95) $left=95; - if ($top>95) $top=95; - if ($left>3 or $top>4) $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'"); + if ($left > 95) $left = 95; + if ($top > 95) $top = 95; + if ($left > 3 or $top > 4) $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'"); else $db->query("DELETE from ".MAIN_DB_PREFIX."takepos_floor_tables where rowid='".$place."'"); } -if ($action=="updatename") +if ($action == "updatename") { $newname = preg_replace("/[^a-zA-Z0-9\s]/", "", $newname); // Only English chars if (strlen($newname) > 3) $newname = substr($newname, 0, 3); // Only 3 chars $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set label='".$db->escape($newname)."' WHERE rowid='".$place."'"); } -if ($action=="add") +if ($action == "add") { - $sql="INSERT INTO ".MAIN_DB_PREFIX."takepos_floor_tables(entity, label, leftpos, toppos, floor) VALUES (".$conf->entity.", '', '45', '45', ".$floor.")"; - $asdf=$db->query($sql); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."takepos_floor_tables(entity, label, leftpos, toppos, floor) VALUES (".$conf->entity.", '', '45', '45', ".$floor.")"; + $asdf = $db->query($sql); $db->query("update ".MAIN_DB_PREFIX."takepos_floor_tables set label=rowid where label=''"); // No empty table names } // Title -$title='TakePOS - Dolibarr '.DOL_VERSION; -if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title='TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; +$title = 'TakePOS - Dolibarr '.DOL_VERSION; +if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE; top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); ?> - +