diff --git a/.travis.yml b/.travis.yml index a3e35dcfdab..3009ff69c01 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,6 +50,9 @@ jobs: - if: type = push AND branch = develop php: nightly env: DB=mysql + - if: type = push AND branch = 14.0 + php: nightly + env: DB=mysql notifications: email: @@ -268,7 +271,7 @@ script: # Ensure we catch errors set -e #parallel-lint --exclude htdocs/includes --blame . - parallel-lint --exclude dev/namespacemig --exclude htdocs/includes/composer --exclude htdocs/includes/myclabs --exclude htdocs/includes/phpspec --exclude dev/initdata/dbf/includes \ + parallel-lint --exclude dev/tools/test/namespacemig --exclude htdocs/includes/composer --exclude htdocs/includes/myclabs --exclude htdocs/includes/phpspec --exclude dev/initdata/dbf/includes \ --exclude htdocs/includes/sabre --exclude htdocs/includes/phpoffice/PhpSpreadsheet --exclude htdocs/includes/sebastian \ --exclude htdocs/includes/squizlabs/php_codesniffer --exclude htdocs/includes/jakub-onderka --exclude htdocs/includes/php-parallel-lint --exclude htdocs/includes/symfony \ --exclude htdocs/includes/mike42/escpos-php/example --exclude htdocs/includes/maximebf \ @@ -398,9 +401,13 @@ script: php upgrade.php 12.0.0 13.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade12001300.log php upgrade2.php 12.0.0 13.0.0 > $TRAVIS_BUILD_DIR/upgrade12001300-2.log php step5.php 12.0.0 13.0.0 > $TRAVIS_BUILD_DIR/upgrade12001300-3.log + php upgrade.php 13.0.0 14.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade13001400.log + php upgrade2.php 13.0.0 14.0.0 > $TRAVIS_BUILD_DIR/upgrade13001400-2.log + php step5.php 13.0.0 14.0.0 > $TRAVIS_BUILD_DIR/upgrade13001400-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_TICKET,MAIN_MODULE_ACCOUNTING,MAIN_MODULE_MRP,MAIN_MODULE_RECRUITMENT > $TRAVIS_BUILD_DIR/enablemodule.log + php upgrade2.php 0.0.0 0.0.0 MAIN_MODULE_API,MAIN_MODULE_PRODUCTBATCH,MAIN_MODULE_SUPPLIERPROPOSAL,MAIN_MODULE_WEBSITE,MAIN_MODULE_TICKET,MAIN_MODULE_ACCOUNTING,MAIN_MODULE_MRP > $TRAVIS_BUILD_DIR/enablemodule.log + php upgrade2.php 0.0.0 0.0.0 MAIN_MODULE_RECEPTION,MAIN_MODULE_RECRUITMENT > $TRAVIS_BUILD_DIR/enablemodule.log echo $? cd - set +e diff --git a/COPYRIGHT b/COPYRIGHT index 10b06b86811..4f4bc3dff6d 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -29,7 +29,7 @@ PHPoAuthLib 0.8.2 MIT License Yes PHPPrintIPP 1.3 GPL-2+ Yes Library to send print IPP requests PSR/Logs 1.0 Library for logs (used by DebugBar) PSR/simple-cache ? Library for cache (used by PHPSpreadSheet) -Restler 3.0.0RC6 LGPL-3+ Yes Library to develop REST Web services (+ swagger-ui js lib into dir explorer) +Restler 3.1.1 LGPL-3+ Yes Library to develop REST Web services (+ swagger-ui js lib into dir explorer) Sabre 3.2.2 BSD Yes DAV support Swift Mailer 5.4.2-DEV MIT license Yes Comprehensive mailing tools for PHP Stripe 6.43.1 MIT licence Yes Library for Stripe module diff --git a/ChangeLog b/ChangeLog index 82f82c0b051..4877363e6be 100644 --- a/ChangeLog +++ b/ChangeLog @@ -18,6 +18,7 @@ NEW: Accountancy - change menu disposition NEW: Accountancy - on transfers, select the periodicity by default NEW: Accountancy - Add export for Gestinum (v3 & v5) NEW: new currency rate editor +NEW: Solve blocking feature. Can increase stock of a Kit without changing subproduct stock. NEW: add a widget to show the customers with outstanding limits reached NEW: add 2 rules for emailcollector: Message send/not sent from Dolibarr NEW: add a counter of number of words for pages in website module @@ -181,8 +182,8 @@ NEW: Add option "If the feature to manage kits of module Stock is used, show det For developers: --------------- -NEW: add __MEMBER_TYPE__ substitution key -NEW: add __TYPE__ substitution key +NEW: add substitution key __MEMBER_TYPE__ +NEW: add substitution key __TYPE__ NEW: add function dolButtonToOpenUrlInDialogPopup() to be able to open page into a popup NEW: show line number on intervention card (via MAIN_VIEW_LINE_NUMBER) NEW: Add some fields to link website page to an other object @@ -192,14 +193,9 @@ NEW: can use THEME_DARKMODEENABLED=2 for a preview of theme in dark mode NEW: can force the antivirus from conf file or autoprepend ini setup NEW: can add event to log into blockedlog module with a constant NEW: add property cssview when declaring fields of an object -NEW: Can use dynamic code into the 'enabled' property of DAO fields -NEW: allow to edit "demand reason" field though API -NEW: fetch contact by email with REST API +NEW: can use dynamic code into the 'enabled' property of DAO fields NEW: field ref_ext in llx_commandedet -NEW: fields ref_ext for Attributes and Combinations -NEW: get state by REST API -NEW: get state dictionnary by REST API -NEW: improve Product API for variant products +NEW: field ref_ext for Attributes and Combinations NEW: OAuth SCOPE for Admin SDK NEW: retrieve discount from invoice from API NEW: standardizes API thirdparties by email like other object @@ -220,6 +216,11 @@ NEW: API can update a payment NEW: API get member by thirdparty NEW: API get thirdparty by barcode NEW: API get users by email / login +NEW: allow to edit field "demand reason" through API +NEW: fetch contact by email with REST API +NEW: get state by REST API +NEW: get state dictionary by REST API +NEW: improve Product API for product variants HOOKs NEW: Hook on propal card diff --git a/SECURITY.md b/SECURITY.md index bcc1bd7d9e0..6dc6e0f33b5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,18 +60,19 @@ ONLY vulnerabilities discovered, when the following setup on test platform is us * ONLY security reports on modules provided by default and with the "stable" status are valid (troubles into "experimental", "developement" or external modules are not valid vulnerabilities). * The root of web server must link to htdocs and the documents directory must be outside of the web server root (this is the default when using the default installer but may differs with external installer). * The web server setup must be done so only the documents directory is in write mode. The root directory called htdocs must be readonly. -* CSRF attacks are accepted for all when using a POST URL, but when using GET URL, they are validated only for creating or updating data resctricted to the admin user. +* CSRF attacks are accepted when using a POST URL, but when using GET URL, they are validated only for creating, updating or deleting data resctricted from pages restricted to admin users. * Ability for a high level user to edit web site pages into the CMS by including HTML or Javascript is an expected feature. Vulnerabilities into the website module are validated only if HTML or Javascript injection can be done by a non allowed user. Scope is the web application (back office) and the APIs. ## Qualifying vulnerabilities for Bug bounty programs + * Remote code execution (RCE) * Local files access and manipulation (LFI, RFI, XXE, SSRF, XSPA) * Code injections (HTML, JS, SQL, PHP, ...) * Cross-Site Scripting (XSS) -* Cross-Site Requests Forgery (CSRF) with real security impact +* Cross-Site Requests Forgery (CSRF) with real security impact (when using GET URLs, CSRF are qualified only for creating, updating or deleting data from pages restricted to admin users) * Open redirect * Broken authentication & session management * Insecure direct object references @@ -83,6 +84,7 @@ Scope is the web application (back office) and the APIs. ## Non-qualifying vulnerabilities for Bug bounty programs, but qualified for reporting + * "Self" XSS * SSL/TLS best practices * Denial of Service attacks diff --git a/build/rpm/dolibarr_generic.spec b/build/rpm/dolibarr_generic.spec index f3c86419f8e..4541868a04f 100755 --- a/build/rpm/dolibarr_generic.spec +++ b/build/rpm/dolibarr_generic.spec @@ -292,6 +292,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/product %_datadir/dolibarr/htdocs/projet %_datadir/dolibarr/htdocs/public +%_datadir/dolibarr/htdocs/recruitment %_datadir/dolibarr/htdocs/reception %_datadir/dolibarr/htdocs/resource %_datadir/dolibarr/htdocs/salaries diff --git a/build/rpm/dolibarr_mandriva.spec b/build/rpm/dolibarr_mandriva.spec index 3c2b8adeb5b..d618b5729d5 100755 --- a/build/rpm/dolibarr_mandriva.spec +++ b/build/rpm/dolibarr_mandriva.spec @@ -209,6 +209,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/product %_datadir/dolibarr/htdocs/projet %_datadir/dolibarr/htdocs/public +%_datadir/dolibarr/htdocs/recruitment %_datadir/dolibarr/htdocs/reception %_datadir/dolibarr/htdocs/resource %_datadir/dolibarr/htdocs/salaries diff --git a/build/rpm/dolibarr_opensuse.spec b/build/rpm/dolibarr_opensuse.spec index 71db3f43445..230a8946e99 100755 --- a/build/rpm/dolibarr_opensuse.spec +++ b/build/rpm/dolibarr_opensuse.spec @@ -220,6 +220,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/product %_datadir/dolibarr/htdocs/projet %_datadir/dolibarr/htdocs/public +%_datadir/dolibarr/htdocs/recruitment %_datadir/dolibarr/htdocs/reception %_datadir/dolibarr/htdocs/resource %_datadir/dolibarr/htdocs/salaries diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 3db28d1f98e..f3374c43234 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -50,6 +50,13 @@ Replace call to serialize_val with no bugged value * In all files, replace constructor names into __construct. Replace also parent::constructor_name with parent::__construct +* Line 4222 of file nusoap.php + + $rev = array(); + preg_match('/\$Revision: ([^ ]+)/', $this->revision, $rev); + $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".(isset($rev[1]) ? $rev[1] : '').")"; + + TCPDF: @@ -229,11 +236,21 @@ Change content of file htdocs/includes/restler/framework/Luracast/Restler/explor public static function getShortName($className) { // @CHANGE LDR - if (! is_string($className)) return; + if (!is_string($className)) return; //var_dump($className); - - +* Add line into Data/Text.php to complete function + + public static function endsWith($haystack, $needle) + { + $length = strlen($needle); + if ($length == 0) { + return true; + } + // @CHANGE LDR + if (!is_string($haystack)) return false; + + PARSEDOWN --------- @@ -299,7 +316,7 @@ SELECT2 Edit CSS to restore line removed between 4.0.5 and 4.0.6. It generates this bug: https://github.com/select2/select2/issues/5832 .select2-hidden-accessible { - margin: -1px !important; /* line to restore */ + margin: -10000px !important; /* line to restore */ } diff --git a/dev/initdemo/README b/dev/initdemo/README index 89e21b9337a..5e0f610d82e 100644 --- a/dev/initdemo/README +++ b/dev/initdemo/README @@ -12,6 +12,11 @@ The script initdemo.sh will erase current database with data into mysqldump_doli Do a chmod 700 initdemo.sh then run ./initdemo.sh to launch Graphic User Interface. +After loading the demo files, admin login may be: +- admin / admin +or +- admin / adminadmin + *** Save demo diff --git a/dev/initdemo/initdemopassword.sh b/dev/initdemo/initdemopassword.sh index d5aa9c1ef0e..84d50f0dcc3 100755 --- a/dev/initdemo/initdemopassword.sh +++ b/dev/initdemo/initdemopassword.sh @@ -53,7 +53,7 @@ then DIALOG="$DIALOG --ascii-lines" fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ trap "rm -f $fichtemp" 0 1 2 5 15 - $DIALOG --title "Init Dolibarr with demo values" --clear \ + $DIALOG --title "Reset login password" --clear \ --inputbox "Mysql database name :" 16 55 dolibarrdemo 2> $fichtemp valret=$? case $valret in @@ -70,7 +70,7 @@ then DIALOG=${DIALOG=dialog} fichtemp=`tempfile 2>/dev/null` || fichtemp=/tmp/test$$ trap "rm -f $fichtemp" 0 1 2 5 15 - $DIALOG --title "Init Dolibarr with demo values" --clear \ + $DIALOG --title "Reset login password" --clear \ --inputbox "Mysql port (ex: 3306):" 16 55 3306 2> $fichtemp valret=$? @@ -128,7 +128,7 @@ then # ---------------------------- confirmation DIALOG=${DIALOG=dialog} - $DIALOG --title "Init demo login with demo values" --clear \ + $DIALOG --title "Reset login password" --clear \ --yesno "Do you confirm ? \n Mysql database : '$base' \n Mysql port : '$port' \n Demo login: '$demologin' \n Demo password : '$demopass'" 15 55 case $? in diff --git a/dev/resources/intracommreport/manuelDebXml1.2.pdf b/dev/resources/intracommreport/manuelDebXml1.2.pdf new file mode 100644 index 00000000000..50544632a0f Binary files /dev/null and b/dev/resources/intracommreport/manuelDebXml1.2.pdf differ diff --git a/dev/resources/intracommreport/schema_deb.xsd b/dev/resources/intracommreport/schema_deb.xsd new file mode 100644 index 00000000000..5379932fa29 --- /dev/null +++ b/dev/resources/intracommreport/schema_deb.xsd @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index bf283993628..db4945a654c 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -6,7 +6,7 @@ build/html build/aps - dev/namespacemig + dev/tools/test/namespacemig dev/initdata/dbf/includes documents htdocs/core/class/lessc.class.php diff --git a/dev/namespacemig/README.md b/dev/tools/test/namespacemig/README.md similarity index 100% rename from dev/namespacemig/README.md rename to dev/tools/test/namespacemig/README.md diff --git a/dev/namespacemig/aaa.class.php b/dev/tools/test/namespacemig/aaa.class.php similarity index 92% rename from dev/namespacemig/aaa.class.php rename to dev/tools/test/namespacemig/aaa.class.php index d7578b78e40..84d936479f2 100644 --- a/dev/namespacemig/aaa.class.php +++ b/dev/tools/test/namespacemig/aaa.class.php @@ -15,6 +15,9 @@ function faaa() return 'faaa'; } +/** + * Class Aaa + */ class Aaa { const AAA='aaa'; diff --git a/dev/namespacemig/bbb.class.php b/dev/tools/test/namespacemig/bbb.class.php similarity index 93% rename from dev/namespacemig/bbb.class.php rename to dev/tools/test/namespacemig/bbb.class.php index f68b3b2f36c..ea3c1b18d61 100644 --- a/dev/namespacemig/bbb.class.php +++ b/dev/tools/test/namespacemig/bbb.class.php @@ -12,6 +12,9 @@ function fbbb() return 'fbbb'; } +/** + * Class Bbb + */ class Bbb { const BBB='bbb'; diff --git a/dev/namespacemig/bbb.php b/dev/tools/test/namespacemig/bbb.php similarity index 100% rename from dev/namespacemig/bbb.php rename to dev/tools/test/namespacemig/bbb.php diff --git a/dev/namespacemig/main.inc.php b/dev/tools/test/namespacemig/main.inc.php similarity index 100% rename from dev/namespacemig/main.inc.php rename to dev/tools/test/namespacemig/main.inc.php diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 232444b7d97..b0e813be970 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -314,7 +314,6 @@ if ($action != 'export_csv') if (empty($accountingaccountstatic->account_number)) { $link = ''.img_edit_add().''; } - print ''; if (!empty($show_subgroup)) { @@ -343,6 +342,7 @@ if ($action != 'export_csv') } } + print ''; print ''.$accounting_account.''; print ''.price($opening_balance).''; print ''.price($line->debit).''; diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 92de49d66ed..ebd768de1dc 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -642,6 +642,7 @@ if (empty($reshook)) { $newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly')); $url = './card.php?action=create'; if (!empty($socid)) $url .= '&socid='.$socid; @@ -936,6 +937,11 @@ while ($i < min($num, $limit)) $filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + } elseif ($line->doc_type == 'bank') + { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $objectstatic = new AccountLine($db); + $objectstatic->fetch($line->fk_doc); } else { // Other type } @@ -950,6 +956,10 @@ while ($i < min($num, $limit)) { print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); print $documentlink; + } elseif ($line->doc_type == 'bank') { + print $objectstatic->getNomUrl(1); + $bank_ref = strstr($line->doc_ref, '-'); + print " " . $bank_ref; } else { print $line->doc_ref; } diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index 18661f8a887..5ee0989c97c 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -39,8 +39,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array("accountancy", "compta")); $action = GETPOST('action', 'aZ09'); -$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); -$search_date_end = dol_mktime(0, 0, 0, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); +$search_date_startyear = GETPOST('search_date_startyear', 'int'); +$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); +$search_date_startday = GETPOST('search_date_startday', 'int'); +$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); +$search_date_endday = GETPOST('search_date_endday', 'int'); +$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); +$search_date_end = dol_mktime(0, 0, 0, $search_date_endmonth, $search_date_endday, $search_date_endyear); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); $search_accountancy_code = GETPOST("search_accountancy_code"); @@ -126,9 +132,24 @@ $arrayfields = array( if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']); +if ($search_date_start && empty($search_date_startyear)) { + $tmparray = dol_getdate($search_date_start); + $search_date_startyear = $tmparray['year']; + $search_date_startmonth = $tmparray['mon']; + $search_date_startday = $tmparray['mday']; +} +if ($search_date_end && empty($search_date_endyear)) { + $tmparray = dol_getdate($search_date_end); + $search_date_endyear = $tmparray['year']; + $search_date_endmonth = $tmparray['mon']; + $search_date_endday = $tmparray['mday']; +} + + /* * Action */ + if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } @@ -172,11 +193,11 @@ if (empty($reshook)) if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; - $param .= '&search_date_startmonth='.GETPOST('search_date_startmonth', 'int').'&search_date_startday='.GETPOST('search_date_startday', 'int').'&search_date_startyear='.GETPOST('search_date_startyear', 'int'); + $param .= '&search_date_startmonth='.$search_date_startmonth.'&search_date_startday='.$search_date_startday.'&search_date_startyear='.$search_date_startyear; } if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; - $param .= '&search_date_endmonth='.GETPOST('search_date_endmonth', 'int').'&search_date_endday='.GETPOST('search_date_endday', 'int').'&search_date_endyear='.GETPOST('search_date_endyear', 'int'); + $param .= '&search_date_endmonth='.$search_date_endmonth.'&search_date_endday='.$search_date_endday.'&search_date_endyear='.$search_date_endyear; } if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; @@ -242,7 +263,7 @@ if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->suppri } // Make a redirect to avoid to launch the delete later after a back button - header("Location: listbyaccount.php".($param ? '?'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"].($param ? '?'.$param : '')); exit; } } @@ -267,7 +288,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme } // Make a redirect to avoid to launch the delete later after a back button - header("Location: listbyaccount.php".($param ? '?'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"].($param ? '?'.$param : '')); exit; } else { setEventMessages("NoRecordDeleted", null, 'warnings'); @@ -284,7 +305,7 @@ if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->suppri setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } - header("Location: listbyaccount.php?noreset=1".($param ? '&'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"]."?noreset=1".($param ? '&'.$param : '')); exit; } } @@ -303,7 +324,6 @@ $title_page = $langs->trans("Operations").' - '.$langs->trans("VueByAccountAccou llxHeader('', $title_page); - // List $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -380,10 +400,8 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { $newcardbutton = dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); - $newcardbutton .= dolGetButtonTitle($langs->trans('VueByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); - - $newcardbutton .= '   '; - + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly')); $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?action=create'); } @@ -524,8 +542,15 @@ while ($i < min($num, $limit)) // Is it a break ? if ($accountg != $displayed_account_number || !isset($displayed_account_number)) { - $colspan = $totalarray['nbfield'] - 3; - $colspanend = $totalarray['nbfield'] - 7; + if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { + $colnumber = 3; + $colnumberend = 7; + } else { + $colnumber = 4; + $colnumberend = 7; + } + $colspan = $totalarray['nbfield'] - $colnumber; + $colspanend = $totalarray['nbfield'] - $colnumberend; // Show a subtotal by accounting account if (isset($displayed_account_number)) { print ''; @@ -642,20 +667,29 @@ while ($i < min($num, $limit)) $filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + } elseif ($line->doc_type == 'bank') + { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $objectstatic = new AccountLine($db); + $objectstatic->fetch($line->fk_doc); } else { // Other type } - print ''; + print ''; print ''; // Picto + Ref - print ''; print ''; print ''; diff --git a/htdocs/accountancy/bookkeeping/listbysubaccount.php b/htdocs/accountancy/bookkeeping/listbysubaccount.php index 3bc0351b09b..e54d20cd647 100644 --- a/htdocs/accountancy/bookkeeping/listbysubaccount.php +++ b/htdocs/accountancy/bookkeeping/listbysubaccount.php @@ -39,8 +39,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array("accountancy", "compta")); $action = GETPOST('action', 'aZ09'); -$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); -$search_date_end = dol_mktime(0, 0, 0, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); +$search_date_startyear = GETPOST('search_date_startyear', 'int'); +$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); +$search_date_startday = GETPOST('search_date_startday', 'int'); +$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); +$search_date_endday = GETPOST('search_date_endday', 'int'); +$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); +$search_date_end = dol_mktime(0, 0, 0, $search_date_endmonth, $search_date_endday, $search_date_endyear); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); $search_accountancy_code = GETPOST("search_accountancy_code"); @@ -126,6 +132,20 @@ $arrayfields = array( if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']); +if ($search_date_start && empty($search_date_startyear)) { + $tmparray = dol_getdate($search_date_start); + $search_date_startyear = $tmparray['year']; + $search_date_startmonth = $tmparray['mon']; + $search_date_startday = $tmparray['mday']; +} +if ($search_date_end && empty($search_date_endyear)) { + $tmparray = dol_getdate($search_date_end); + $search_date_endyear = $tmparray['year']; + $search_date_endmonth = $tmparray['mon']; + $search_date_endday = $tmparray['mday']; +} + + /* * Action */ @@ -172,11 +192,11 @@ if (empty($reshook)) if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; - $param .= '&search_date_startmonth='.GETPOST('search_date_startmonth', 'int').'&search_date_startday='.GETPOST('search_date_startday', 'int').'&search_date_startyear='.GETPOST('search_date_startyear', 'int'); + $param .= '&search_date_startmonth='.$search_date_startmonth.'&search_date_startday='.$search_date_startday.'&search_date_startyear='.$search_date_startyear; } if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; - $param .= '&search_date_endmonth='.GETPOST('search_date_endmonth', 'int').'&search_date_endday='.GETPOST('search_date_endday', 'int').'&search_date_endyear='.GETPOST('search_date_endyear', 'int'); + $param .= '&search_date_endmonth='.$search_date_endmonth.'&search_date_endday='.$search_date_endday.'&search_date_endyear='.$search_date_endyear; } if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; @@ -242,7 +262,7 @@ if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->suppri } // Make a redirect to avoid to launch the delete later after a back button - header("Location: listbyaccount.php".($param ? '?'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"].($param ? '?'.$param : '')); exit; } } @@ -380,14 +400,19 @@ print ''; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { - $newcardbutton = dolGetButtonTitle($langs->trans('ViewAccountList'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php', '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); + $newcardbutton = dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php', '', 1, array('morecss' => 'marginleftonly')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); + $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?action=create'); } if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); + +print info_admin($langs->trans("WarningRecordWithoutSubledgerAreExcluded")); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -521,8 +546,15 @@ while ($i < min($num, $limit)) // Is it a break ? if ($accountg != $displayed_account_number || !isset($displayed_account_number)) { - $colspan = $totalarray['nbfield'] - 3; - $colspanend = $totalarray['nbfield'] - 7; + if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { + $colnumber = 3; + $colnumberend = 7; + } else { + $colnumber = 4; + $colnumberend = 7; + } + $colspan = $totalarray['nbfield'] - $colnumber; + $colspanend = $totalarray['nbfield'] - $colnumberend; // Show a subtotal by accounting account if (isset($displayed_account_number)) { print ''; @@ -554,8 +586,16 @@ while ($i < min($num, $limit)) // Show the break account print ""; print ''; print ''; @@ -639,20 +679,29 @@ while ($i < min($num, $limit)) $filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + } elseif ($line->doc_type == 'bank') + { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $objectstatic = new AccountLine($db); + $objectstatic->fetch($line->fk_doc); } else { // Other type } - print '
'; + print ''; if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') { print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); print $documentlink; + } elseif ($line->doc_type == 'bank') { + print $objectstatic->getNomUrl(1); + $bank_ref = strstr($line->doc_ref, '-'); + print " " . $bank_ref; } else { print $line->doc_ref; } @@ -725,8 +759,15 @@ while ($i < min($num, $limit)) } // Show sub-total of last shown account -$colspan = $totalarray['nbfield'] - 3; -$colspanend = $totalarray['nbfield'] - 8; +if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { + $colnumber = 3; + $colnumberend = 7; +} else { + $colnumber = 4; + $colnumberend = 7; +} +$colspan = $totalarray['nbfield'] - $colnumber; +$colspanend = $totalarray['nbfield'] - $colnumberend; print '
'.$langs->trans("TotalForAccount").' '.$accountg.':'.price($sous_total_debit).'
'; - if ($line->subledger_account != "" && $line->subledger_account != '-1') print length_accounta($line->subledger_account).' : '.$object->get_compte_desc($line->numero_compte); - else print ''.$langs->trans("Unknown").''; + if ($line->subledger_account != "" && $line->subledger_account != '-1') { + print $object->get_compte_desc($line->numero_compte).' : '.length_accounta($line->subledger_account); + } else { + // Should not happen: subledger account must be null or a non empty value + print ''.$langs->trans("Unknown"); + if ($line->subledger_label) print ' ('.$line->subledger_label.')'; + $htmltext = 'EmptyStringForSubledgerAccountButSubledgerLabelDefined'; + print $form->textwithpicto('', $htmltext); + print ''; + } print '
'; + print ''; print ''; // Picto + Ref - print ''; print ''; print ''; diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index f15a2a0c704..1bcc4129821 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -60,6 +60,7 @@ class AccountancyExport public static $EXPORT_TYPE_GESTINUMV3 = 130; public static $EXPORT_TYPE_GESTINUMV5 = 135; public static $EXPORT_TYPE_FEC = 1000; + public static $EXPORT_TYPE_FEC2 = 1010; /** @@ -121,6 +122,7 @@ class AccountancyExport self::$EXPORT_TYPE_GESTINUMV3 => $langs->trans('Modelcsv_Gestinum_v3'), self::$EXPORT_TYPE_GESTINUMV5 => $langs->trans('Modelcsv_Gestinum_v5'), self::$EXPORT_TYPE_FEC => $langs->trans('Modelcsv_FEC'), + self::$EXPORT_TYPE_FEC2 => $langs->trans('Modelcsv_FEC2'), ); ksort($listofexporttypes, SORT_NUMERIC); @@ -155,6 +157,7 @@ class AccountancyExport self::$EXPORT_TYPE_GESTINUMV3 => 'gestinumv3', self::$EXPORT_TYPE_GESTINUMV5 => 'gestinumv5', self::$EXPORT_TYPE_FEC => 'fec', + self::$EXPORT_TYPE_FEC2 => 'fec2', ); return $formatcode[$type]; @@ -234,6 +237,10 @@ class AccountancyExport 'label' => $langs->trans('Modelcsv_FEC'), 'ACCOUNTING_EXPORT_FORMAT' => 'txt', ), + self::$EXPORT_TYPE_FEC2 => array( + 'label' => $langs->trans('Modelcsv_FEC2'), + 'ACCOUNTING_EXPORT_FORMAT' => 'txt', + ), ), 'cr'=> array( '1' => $langs->trans("Unix"), @@ -322,6 +329,9 @@ class AccountancyExport case self::$EXPORT_TYPE_FEC : $this->exportFEC($TData); break; + case self::$EXPORT_TYPE_FEC2 : + $this->exportFEC2($TData); + break; default: $this->errors[] = $langs->trans('accountancy_error_modelnotfound'); break; @@ -505,9 +515,9 @@ class AccountancyExport $end_line = "\r\n"; - //We should use dol_now function not time however this is wrong date to transfert in accounting - //$date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy - //$date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy + // We should use dol_now function not time however this is wrong date to transfert in accounting + // $date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy + // $date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy foreach ($TData as $data) { $code_compta = $data->numero_compte; if (!empty($data->subledger_account)) @@ -519,36 +529,46 @@ class AccountancyExport $Tab['code_journal'] = str_pad(self::trunc($data->code_journal, 2), 2); $Tab['folio'] = '000'; - //We use invoice date $data->doc_date not $date_ecriture which is the transfert date - //maybe we should set an option for customer who prefer to keep in accounting software the tranfert date instead of invoice date ? + // We use invoice date $data->doc_date not $date_ecriture which is the transfert date + // maybe we should set an option for customer who prefer to keep in accounting software the tranfert date instead of invoice date ? //$Tab['date_ecriture'] = $date_ecriture; $Tab['date_ecriture'] = dol_print_date($data->doc_date, '%d%m%y'); $Tab['filler'] = ' '; $Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 20), 20); - $Tab['sens'] = $data->sens; // C or D - $Tab['signe_montant'] = '+'; - //elarifr le montant doit etre en centimes sans point decimal ! - $Tab['montant'] = str_pad(abs($data->montant * 100), 12, '0', STR_PAD_LEFT); // TODO manage negative amount - // $Tab['montant'] = str_pad(abs($data->montant), 12, '0', STR_PAD_LEFT); // TODO manage negative amount + // Credit invoice - invert sens + if ($data->montant < 0) { + if ($data->sens == 'C') { + $Tab['sens'] = 'D'; + } else { + $Tab['sens'] = 'C'; + } + $Tab['signe_montant'] = '-'; + } else { + $Tab['sens'] = $data->sens; // C or D + $Tab['signe_montant'] = '+'; + } + + // The amount must be in centimes without decimal points. + $Tab['montant'] = str_pad(abs($data->montant * 100), 12, '0', STR_PAD_LEFT); $Tab['contrepartie'] = str_repeat(' ', 8); - // elarifr: date format must be fixed format : 6 char ddmmyy = %d%m%yand not defined by user / dolibarr setting + // Force date format : %d%m%y if (!empty($data->date_echeance)) { //$Tab['date_echeance'] = dol_print_date($data->date_echeance, $conf->global->ACCOUNTING_EXPORT_DATE); - $Tab['date_echeance'] = dol_print_date($data->date_echeance, '%d%m%y'); // elarifr: format must be ddmmyy + $Tab['date_echeance'] = dol_print_date($data->date_echeance, '%d%m%y'); // Format must be ddmmyy } else { $Tab['date_echeance'] = '000000'; } - //elarifr please keep quadra named field lettrage(2) + codestat(3) instead of fake lettrage(5) - //$Tab['lettrage'] = str_repeat(' ', 5); + // Please keep quadra named field lettrage(2) + codestat(3) instead of fake lettrage(5) + // $Tab['lettrage'] = str_repeat(' ', 5); $Tab['lettrage'] = str_repeat(' ', 2); $Tab['codestat'] = str_repeat(' ', 3); $Tab['num_piece'] = str_pad(self::trunc($data->piece_num, 5), 5); - //elarifr keep correct quadra named field instead of anon filler - //$Tab['filler2'] = str_repeat(' ', 20); + // Keep correct quadra named field instead of anon filler + // $Tab['filler2'] = str_repeat(' ', 20); $Tab['affaire'] = str_repeat(' ', 10); $Tab['quantity1'] = str_repeat(' ', 10); $Tab['num_piece2'] = str_pad(self::trunc($data->piece_num, 8), 8); @@ -556,17 +576,17 @@ class AccountancyExport $Tab['code_journal2'] = str_pad(self::trunc($data->code_journal, 3), 3); $Tab['filler3'] = str_repeat(' ', 3); - //elarifr keep correct quadra named field instead of anon filler libelle_ecriture2 is 30 char not 32 !!!! - //as we use utf8, we must remove accent to have only one ascii char instead of utf8 2 chars for specials that report wrong line size that will exceed import format spec - //todo we should filter more than only accent to avoid wrong line size - //TODO: remove invoice number doc_ref in libelle, - //TODO: we should offer an option for customer to build the libelle using invoice number / name / date in accounting software + // Keep correct quadra named field instead of anon filler libelle_ecriture2 is 30 char not 32 !!!! + // as we use utf8, we must remove accent to have only one ascii char instead of utf8 2 chars for specials that report wrong line size that will exceed import format spec + // TODO: we should filter more than only accent to avoid wrong line size + // TODO: remove invoice number doc_ref in libelle, + // TODO: we should offer an option for customer to build the libelle using invoice number / name / date in accounting software //$Tab['libelle_ecriture2'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref) . ' ' . dol_string_unaccent($data->label_operation), 30), 30); $Tab['libelle_ecriture2'] = str_pad(self::trunc(dol_string_unaccent($data->label_operation), 30), 30); $Tab['codetva'] = str_repeat(' ', 2); - //elarifr we need to keep the 10 lastest number of invoice doc_ref not the beginning part that is the unusefull almost same part - //$Tab['num_piece3'] = str_pad(self::trunc($data->piece_num, 10), 10); + // We need to keep the 10 lastest number of invoice doc_ref not the beginning part that is the unusefull almost same part + // $Tab['num_piece3'] = str_pad(self::trunc($data->piece_num, 10), 10); $Tab['num_piece3'] = substr(self::trunc($data->doc_ref, 20), -10); $Tab['filler4'] = str_repeat(' ', 73); @@ -891,6 +911,105 @@ class AccountancyExport } } + /** + * Export format : FEC2 + * + * @param array $objectLines data + * @return void + */ + public function exportFEC2($objectLines) + { + $separator = "\t"; + $end_line = "\r\n"; + + print "JournalCode".$separator; + print "JournalLib".$separator; + print "EcritureNum".$separator; + print "EcritureDate".$separator; + print "CompteNum".$separator; + print "CompteLib".$separator; + print "CompAuxNum".$separator; + print "CompAuxLib".$separator; + print "PieceRef".$separator; + print "PieceDate".$separator; + print "EcritureLib".$separator; + print "Debit".$separator; + print "Credit".$separator; + print "EcritureLet".$separator; + print "DateLet".$separator; + print "ValidDate".$separator; + print "Montantdevise".$separator; + print "Idevise"; + print $end_line; + + foreach ($objectLines as $line) { + if ($line->debit == 0 && $line->credit == 0) { + unset($array[$line]); + } else { + $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); + $date_document = dol_print_date($line->doc_date, '%Y%m%d'); + $date_lettering = dol_print_date($line->date_lettering, '%Y%m%d'); + $date_validation = dol_print_date($line->date_validated, '%Y%m%d'); + + // FEC:JournalCode + print $line->code_journal . $separator; + + // FEC:JournalLib + print $line->journal_label . $separator; + + // FEC:EcritureNum + print $line->piece_num . $separator; + + // FEC:EcritureDate + print $date_creation . $separator; + + // FEC:CompteNum + print $line->numero_compte . $separator; + + // FEC:CompteLib + print dol_string_unaccent($line->label_compte) . $separator; + + // FEC:CompAuxNum + print $line->subledger_account . $separator; + + // FEC:CompAuxLib + print dol_string_unaccent($line->subledger_label) . $separator; + + // FEC:PieceRef + print $line->doc_ref . $separator; + + // FEC:PieceDate + print $date_document . $separator; + + // FEC:EcritureLib + print dol_string_unaccent($line->label_operation) . $separator; + + // FEC:Debit + print price2fec($line->debit) . $separator; + + // FEC:Credit + print price2fec($line->credit) . $separator; + + // FEC:EcritureLet + print $line->lettering_code . $separator; + + // FEC:DateLet + print $date_lettering . $separator; + + // FEC:ValidDate + print $date_validation . $separator; + + // FEC:Montantdevise + print $line->multicurrency_amount . $separator; + + // FEC:Idevise + print $line->multicurrency_code; + + print $end_line; + } + } + } + /** * Export format : SAGE50SWISS * diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 8312b155b8b..72428762459 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -825,6 +825,10 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key.'\''.$this->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'; + } elseif ($key == 't.code_journal' && !empty($value)) { + $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1); } else { $sqlwhere[] = natural_search($key, $value, 0, 1); } diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 418c5cc5674..9e1647d9760 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -1064,7 +1064,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print '
'; + print ''; if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') { print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); print $documentlink; + } elseif ($line->doc_type == 'bank') { + print $objectstatic->getNomUrl(1); + $bank_ref = strstr($line->doc_ref, '-'); + print " " . $bank_ref; } else { print $line->doc_ref; } @@ -722,8 +771,15 @@ while ($i < min($num, $limit)) } // Show sub-total of last shown account -$colspan = $totalarray['nbfield'] - 3; -$colspanend = $totalarray['nbfield'] - 8; +if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { + $colnumber = 3; + $colnumberend = 7; +} else { + $colnumber = 4; + $colnumberend = 7; +} +$colspan = $totalarray['nbfield'] - $colnumber; +$colspanend = $totalarray['nbfield'] - $colnumberend; print '
'.$langs->trans("TotalForAccount").' '.$accountg.':'.price($sous_total_debit).'
'; // Ref - print ''; + print ''; // Login if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { diff --git a/htdocs/adherents/cartes/carte.php b/htdocs/adherents/cartes/carte.php index b62f58117a2..ca194f8d51d 100644 --- a/htdocs/adherents/cartes/carte.php +++ b/htdocs/adherents/cartes/carte.php @@ -63,19 +63,24 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { $arrayofmembers = array(); // request taking into account member with up to date subscriptions - $sql = "SELECT d.rowid, d.firstname, d.lastname, d.login, d.societe as company, d.datefin,"; + $sql = "SELECT d.rowid, d.ref, d.firstname, d.lastname, d.login, d.societe as company, d.datefin,"; $sql .= " d.address, d.zip, d.town, d.country, d.birth, d.email, d.photo,"; $sql .= " t.libelle as type,"; $sql .= " c.code as country_code, c.label as country"; // Add fields from extrafields - if (!empty($extrafields->attributes[$object->table_element]['label'])) - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } + } $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"; - if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent_extrafields as ef on (d.rowid = ef.fk_object)"; + if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent_extrafields as ef on (d.rowid = ef.fk_object)"; + } $sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = 1"; $sql .= " AND d.entity IN (".getEntity('adherent').")"; - if (is_numeric($foruserid)) $sql .= " AND d.rowid=".$foruserid; + if (is_numeric($foruserid)) $sql .= " AND d.rowid=".(int) $foruserid; if ($foruserlogin) $sql .= " AND d.login='".$db->escape($foruserlogin)."'"; $sql .= " ORDER BY d.rowid ASC"; @@ -90,6 +95,7 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { if ($objp->country == '-') $objp->country = ''; $adherentstatic->id = $objp->rowid; + $adherentstatic->ref = $objp->ref; $adherentstatic->lastname = $objp->lastname; $adherentstatic->firstname = $objp->firstname; @@ -110,6 +116,7 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { // List of values to scan for a replacement $substitutionarray = array( '__ID__'=>$objp->rowid, + '__REF__'=>$objp->ref, '__LOGIN__'=>$objp->login, '__FIRSTNAME__'=>$objp->firstname, '__LASTNAME__'=>$objp->lastname, @@ -149,6 +156,7 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { 'textfooter'=>$textfooter, 'textright'=>$textright, 'id'=>$objp->rowid, + 'ref'=>$objp->ref, 'photo'=>$objp->photo ); } @@ -159,6 +167,7 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { 'textfooter'=>$textfooter, 'textright'=>$textright, 'id'=>$objp->rowid, + 'ref'=>$objp->ref, 'photo'=>$objp->photo ); } @@ -172,12 +181,15 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { $textfooter = ''; $textright = ''; - $arrayofmembers[] = array('textleft'=>$textleft, - 'textheader'=>$textheader, - 'textfooter'=>$textfooter, - 'textright'=>$textright, - 'id'=>$objp->rowid, - 'photo'=>$objp->photo); + $arrayofmembers[] = array( + 'textleft'=>$textleft, + 'textheader'=>$textheader, + 'textfooter'=>$textfooter, + 'textright'=>$textright, + 'id'=>$objp->rowid, + 'ref'=>$objp->ref, + 'photo'=>$objp->photo, + ); } $i++; diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 5df6db52f3d..2637612acc0 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -288,6 +288,7 @@ class Adherent extends CommonObject */ public $fields = array( 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10), + 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => 1, 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 12, 'index' => 1), '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), @@ -417,6 +418,7 @@ class Adherent extends CommonObject $infos = ''; if ($this->civility_id) $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; $infos .= $langs->transnoentities("id").": ".$this->id."\n"; + $infos .= $langs->transnoentities("ref").": ".$this->ref."\n"; $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n"; $infos .= $langs->transnoentities("Firstname").": ".$this->firstname."\n"; $infos .= $langs->transnoentities("Company").": ".$this->company."\n"; @@ -438,15 +440,20 @@ class Adherent extends CommonObject // Substitutions $substitutionarray = array( - '__ID__' => $this->id, '__MEMBER_ID__' => $this->id, '__CIVILITY__' => $this->getCivilityLabel(), + '__ID__' => $this->id, + '__REF__' => $this->ref, + '__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 : ''), + '__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 : ''), + '__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 : ''), @@ -519,9 +526,10 @@ 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 .= " (ref, 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 .= " '(PROV)'"; + $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)."'"; @@ -635,7 +643,8 @@ 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 .= " ref = '".$this->db->escape($this->ref)."'"; + $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' @@ -752,6 +761,7 @@ class Adherent extends CommonObject // 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; + $luser->ref = $this->ref; $luser->civility_id = $this->civility_id; $luser->firstname = $this->firstname; $luser->lastname = $this->lastname; @@ -1242,7 +1252,8 @@ 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 = "SELECT d.rowid, d.ref, d.ref_ext, d.civility as civility_code, d.gender, d.firstname, d.lastname,"; + $sql .= " 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,"; @@ -1268,7 +1279,7 @@ class Adherent extends CommonObject } elseif ($ref || $fk_soc) { $sql .= " AND d.entity IN (".getEntity('adherent').")"; if ($ref) { - $sql .= " AND d.rowid='".$this->db->escape($ref)."'"; + $sql .= " AND d.ref='".$this->db->escape($ref)."'"; } elseif ($fk_soc > 0) { $sql .= " AND d.fk_soc=".((int) $fk_soc); } @@ -1283,8 +1294,8 @@ class Adherent extends CommonObject $obj = $this->db->fetch_object($resql); $this->entity = $obj->entity; - $this->ref = $obj->rowid; $this->id = $obj->rowid; + $this->ref = $obj->ref; $this->ref_ext = $obj->ref_ext; $this->civility_id = $obj->civility_code; // Bad. Kept for backard compatibility @@ -2072,7 +2083,7 @@ class Adherent extends CommonObject if ($mode == 'login') { $result .= dol_trunc($this->login, $maxlen); } elseif ($mode == 'ref') { - $result .= $this->id; + $result .= $this->ref; } else { $result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen); } @@ -2317,6 +2328,7 @@ class Adherent extends CommonObject // Initialise parametres $this->id = 0; + $this->ref = 'ABC001'; $this->entity = 1; $this->specimen = 1; $this->civility_id = 0; diff --git a/htdocs/adherents/list.php b/htdocs/adherents/list.php index c9aaa856d22..1da75fdefa5 100644 --- a/htdocs/adherents/list.php +++ b/htdocs/adherents/list.php @@ -101,7 +101,7 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'd.rowid'=>'Ref', + 'd.ref'=>'Ref', 'd.login'=>'Login', 'd.lastname'=>'Lastname', 'd.firstname'=>'Firstname', @@ -146,12 +146,7 @@ $arrayfields = array( 'd.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000) ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; /* @@ -251,7 +246,7 @@ $memberstatic = new Adherent($db); $now = dol_now(); -$sql = "SELECT d.rowid, d.login, d.lastname, d.firstname, d.gender, d.societe as company, d.fk_soc,"; +$sql = "SELECT d.rowid, d.ref, d.login, d.lastname, d.firstname, d.gender, d.societe as company, d.fk_soc,"; $sql .= " d.civility, d.datefin, d.address, d.zip, d.town, d.state_id, d.country,"; $sql .= " d.email, d.phone, d.phone_perso, d.phone_mobile, d.skype, d.birth, d.public, d.photo,"; $sql .= " d.fk_adherent_type as type_id, d.morphy, d.statut, d.datec as date_creation, d.tms as date_update,"; @@ -268,8 +263,13 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; -if (!empty($search_categ) || !empty($catid)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_member as cm ON d.rowid = cm.fk_member"; // We need this table joined to the select in order to filter by categ +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; +} +if (!empty($search_categ) || !empty($catid)) { + // We need this table joined to the select in order to filter by categ + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_member as cm ON d.rowid = cm.fk_member"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = d.country)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = d.state_id)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on (s.rowid = d.fk_soc)"; @@ -285,10 +285,12 @@ if ($search_type > 0) $sql .= " AND t.rowid=".$db->escape($search_type); if ($search_filter == 'withoutsubscription') $sql .= " AND (datefin IS NULL OR t.subscription = 0)"; if ($search_filter == 'uptodate') $sql .= " AND (datefin >= '".$db->idate($now)."' OR t.subscription = 0)"; if ($search_filter == 'outofdate') $sql .= " AND (datefin < '".$db->idate($now)."' AND t.subscription = 1)"; -if ($search_status != '') $sql .= " AND d.statut in (".$db->sanitize($db->escape($search_status)).")"; // Peut valoir un nombre ou liste de nombre separes par virgules +if ($search_status != '') { + // Peut valoir un nombre ou liste de nombre separes par virgules + $sql .= " AND d.statut in (".$db->sanitize($db->escape($search_status)).")"; +} if ($search_ref) { - if (is_numeric($search_ref)) $sql .= " AND (d.rowid = ".$db->escape($search_ref).")"; - else $sql .= " AND 1 = 2"; // Always wrong + $sql .= natural_search("d.ref", $search_ref); } if ($search_civility) $sql .= natural_search("d.civility", $search_civility); if ($search_firstname) $sql .= natural_search("d.firstname", $search_firstname); @@ -607,7 +609,7 @@ print "\n"; print ''; if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) print_liste_field_titre("ID", $_SERVER["PHP_SELF"], '', '', $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.rowid', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.ref', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.civility']['checked'])) print_liste_field_titre($arrayfields['d.civility']['label'], $_SERVER["PHP_SELF"], 'd.civility', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], 'd.firstname', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], 'd.lastname', '', $param, '', $sortfield, $sortorder); @@ -647,7 +649,7 @@ while ($i < min($num, $limit)) { $datefin = $db->jdate($obj->datefin); $memberstatic->id = $obj->rowid; - $memberstatic->ref = $obj->rowid; + $memberstatic->ref = $obj->ref; $memberstatic->civility_id = $obj->civility; $memberstatic->lastname = $obj->lastname; $memberstatic->firstname = $obj->firstname; diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 1c4e42da1fe..a00c52b88e5 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -300,57 +300,75 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! if (!$error) { // Send confirmation Email if ($object->email && $sendalsoemail) { // $object is 'Adherent' - $subject = ''; - $msg = ''; - - // Send subscription email - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - // Set output language - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang); - // Load traductions files required by page - $outputlangs->loadLangs(array("main", "members")); - - // Get email content from template - $arraydefaultmessage = null; - $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION; - - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); - - if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { - $subject = $arraydefaultmessage->topic; - $msg = $arraydefaultmessage->content; + $parameters = array( + 'datesubscription' => $datesubscription, + 'amount' => $amount, + 'ccountid' => $accountid, + 'operation' => $operation, + 'label' => $label, + 'num_chq' => $num_chq, + 'emetteur_nom' => $emetteur_nom, + 'emetteur_banque' => $emetteur_banque, + 'datesubend' => $datesubend + ); + $reshook = $hookmanager->executeHooks('sendMail', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } - $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); - complete_substitutions_array($substitutionarray, $outputlangs, $object); - $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs); - $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs); + if (empty($reshook)) { + $subject = ''; + $msg = ''; - // Attach a file ? - $file = ''; - $listofpaths = array(); - $listofnames = array(); - $listofmimes = array(); - if (is_object($object->invoice) && (!is_object($arraydefaultmessage) || intval($arraydefaultmessage->joinfiles))) { - $invoicediroutput = $conf->facture->dir_output; - $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; + // Send subscription email + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + // Set output language + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang); + // Load traductions files required by page + $outputlangs->loadLangs(array("main", "members")); - $listofpaths = array($file); - $listofnames = array(basename($file)); - $listofmimes = array(dol_mimetype($file)); - } + // Get email content from template + $arraydefaultmessage = null; + $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION; - $moreinheader = 'X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n"; + if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); - $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, '', $moreinheader); - if ($result < 0) { - $errmsg = $object->error; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs'); + if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { + $subject = $arraydefaultmessage->topic; + $msg = $arraydefaultmessage->content; + } + + $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); + complete_substitutions_array($substitutionarray, $outputlangs, $object); + $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs); + $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs); + + // Attach a file ? + $file = ''; + $listofpaths = array(); + $listofnames = array(); + $listofmimes = array(); + if (is_object($object->invoice) && (!is_object($arraydefaultmessage) || intval($arraydefaultmessage->joinfiles))) { + $invoicediroutput = $conf->facture->dir_output; + $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+'); + $file = $fileparams['fullname']; + + $listofpaths = array($file); + $listofnames = array(basename($file)); + $listofmimes = array(dol_mimetype($file)); + } + + $moreinheader = 'X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n"; + + $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, '', $moreinheader); + if ($result < 0) { + $errmsg = $object->error; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("EmailSentToMember", $object->email), null, 'mesgs'); + } } } else { setEventMessages($langs->trans("NoEmailSentToMember"), null, 'mesgs'); diff --git a/htdocs/admin/agenda_reminder.php b/htdocs/admin/agenda_reminder.php index 9da8f89310a..27c6bbeed73 100644 --- a/htdocs/admin/agenda_reminder.php +++ b/htdocs/admin/agenda_reminder.php @@ -187,10 +187,18 @@ print ''."\n"; print ''."\n"; } else { - print ''.img_picto($langs->trans('Enabled'), 'switch_on').''; + if (! getIsHTTPS()) { + $langs->load("errors"); + print img_warning($langs->trans("WarningAvailableOnlyForHTTPSServers"), '', 'valignmiddle size15x').' '; + } + print ''.img_picto($langs->trans('Enabled'), 'switch_on').''; print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php index 25a220e8e2d..cde0253f99a 100644 --- a/htdocs/admin/commande.php +++ b/htdocs/admin/commande.php @@ -111,11 +111,9 @@ if ($action == 'updateMask') } // Activate a model -elseif ($action == 'set') -{ +elseif ($action == 'set') { $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') -{ +} elseif ($action == 'del') { $ret = delDocumentModel($value, $type); if ($ret > 0) { @@ -124,8 +122,7 @@ elseif ($action == 'set') } // Set default model -elseif ($action == 'setdoc') -{ +elseif ($action == 'setdoc') { if (dolibarr_set_const($db, "COMMANDE_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) { // The constant that was read before the new set @@ -139,8 +136,7 @@ elseif ($action == 'setdoc') { $ret = addDocumentModel($value, $type, $label, $scandir); } -} elseif ($action == 'setmod') -{ +} elseif ($action == 'setmod') { // TODO Check if numbering module chosen can be activated // by calling method canBeActivated @@ -254,6 +250,7 @@ print dol_get_fiche_head($head, 'general', $langs->trans("Orders"), -1, 'order') print load_fiche_titre($langs->trans("OrdersNumberingModules"), '', ''); +print '
'; print '
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Ref").''.$object->ref.'
 '."\n"; if (empty($conf->global->AGENDA_REMINDER_BROWSER)) { - print ''.img_picto($langs->trans('Disabled'), 'switch_off').''; + if (! getIsHTTPS()) { + $langs->load("errors"); + print img_warning($langs->trans("WarningAvailableOnlyForHTTPSServers"), '', 'valignmiddle size15x').' '; + } + print ''.img_picto($langs->trans('Disabled'), 'switch_off').''; print '
'; print ''; print ''; @@ -346,7 +343,7 @@ foreach ($dirmodels as $reldir) } } } -print "
'.$langs->trans("Name").'

\n"; +print "

\n"; /* @@ -377,6 +374,7 @@ if ($resql) } +print '
'; print "\n"; print "\n"; print ''; @@ -501,6 +499,7 @@ foreach ($dirmodels as $reldir) } print '
'.$langs->trans("Name").'
'; +print '
'; /* diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index adfaaf4f816..e7149ece88d 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -135,12 +135,13 @@ if ($action == 'deletefilter') { $emailcollectorfilter = new EmailCollectorFilter($db); $emailcollectorfilter->fetch(GETPOST('filterid', 'int')); - $result = $emailcollectorfilter->delete($user); - if ($result > 0) - { - $object->fetchFilters(); - } else { - setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors'); + if ($emailcollectorfilter->id > 0) { + $result = $emailcollectorfilter->delete($user); + if ($result > 0) { + $object->fetchFilters(); + } else { + setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors'); + } } } @@ -153,13 +154,26 @@ if (GETPOST('addoperation', 'alpha')) $emailcollectoroperation->status = 1; $emailcollectoroperation->position = 50; - $result = $emailcollectoroperation->create($user); + if ($emailcollectoroperation->type == '-1') { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Operation")), null, 'errors'); + } - if ($result > 0) - { - $object->fetchActions(); - } else { - setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty')) + && empty($emailcollectoroperation->actionparam)) { + $error++; + setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors'); + } + + if (!$error) { + $result = $emailcollectoroperation->create($user); + + if ($result > 0) { + $object->fetchActions(); + } else { + $error++; + setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + } } } @@ -170,25 +184,35 @@ if ($action == 'updateoperation') $emailcollectoroperation->actionparam = GETPOST('operationparam2', 'restricthtml'); - $result = $emailcollectoroperation->update($user); + if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty')) + && empty($emailcollectoroperation->actionparam)) { + $error++; + setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors'); + } - if ($result > 0) - { - $object->fetchActions(); - } else { - setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + if (!$error) { + $result = $emailcollectoroperation->update($user); + + if ($result > 0) + { + $object->fetchActions(); + } else { + $error++; + setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + } } } if ($action == 'deleteoperation') { $emailcollectoroperation = new EmailCollectorAction($db); $emailcollectoroperation->fetch(GETPOST('operationid', 'int')); - $result = $emailcollectoroperation->delete($user); - if ($result > 0) - { - $object->fetchActions(); - } else { - setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + if ($emailcollectoroperation->id > 0) { + $result = $emailcollectoroperation->delete($user); + if ($result > 0) { + $object->fetchActions(); + } else { + setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors'); + } } } @@ -458,7 +482,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '
'; print ''; print ''; - print ''; + print ''; print ''; // Add filter print ''; @@ -491,7 +515,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea 'isnotanswer'=>array('label'=>'IsNotAnAnswer', 'data-noparam'=>1), 'isanswer'=>array('label'=>'IsAnAnswer', 'data-noparam'=>1) ); - print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth500', 0, '', 2); + print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth500', 1, '', 2); print "\n"; print ''; } else { $html = ' - - - '; + + + '; $html .= ' - - - '; + + + '; $html .= ' - - - '; + + + '; $html .= ''; + if ($(this).text().search(new RegExp(filter, "i")) < 0) { + $(this).addClass("hidden-search-result"); + } else { + $(this).removeClass("hidden-search-result"); + count++; + } + }); + $("#top-bookmark-search-filter-count").text(count); + }); + '; } return $html; diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php index f7098f1d780..f5bbefae3d3 100644 --- a/htdocs/bookmarks/class/bookmark.class.php +++ b/htdocs/bookmarks/class/bookmark.class.php @@ -83,8 +83,14 @@ class Bookmark extends CommonObject */ public $title; + /** + * @var int position of bookmark + */ public $position; + /** + * @var string favicon + */ public $favicon; @@ -116,8 +122,7 @@ class Bookmark extends CommonObject dol_syslog("Bookmark::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -151,7 +156,9 @@ class Bookmark extends CommonObject // Clean parameters $this->url = trim($this->url); $this->title = trim($this->title); - if (empty($this->position)) $this->position = 0; + if (empty($this->position)) { + $this->position = 0; + } $now = dol_now(); @@ -164,17 +171,15 @@ class Bookmark extends CommonObject $sql .= ($this->fk_user > 0 ? $this->fk_user : "0").","; $sql .= " '".$this->db->idate($now)."',"; $sql .= " '".$this->db->escape($this->url)."', '".$this->db->escape($this->target)."',"; - $sql .= " '".$this->db->escape($this->title)."', '".$this->db->escape($this->favicon)."', '".$this->db->escape($this->position)."'"; - $sql .= ", ".$this->db->escape($conf->entity); + $sql .= " '".$this->db->escape($this->title)."', '".$this->db->escape($this->favicon)."', ".(int) $this->position; + $sql .= ", ".(int) $conf->entity; $sql .= ")"; dol_syslog("Bookmark::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."bookmark"); - if ($id > 0) - { + if ($id > 0) { $this->id = $id; $this->db->commit(); return $id; @@ -202,7 +207,9 @@ class Bookmark extends CommonObject // Clean parameters $this->url = trim($this->url); $this->title = trim($this->title); - if (empty($this->position)) $this->position = 0; + if (empty($this->position)) { + $this->position = 0; + } $sql = "UPDATE ".MAIN_DB_PREFIX."bookmark"; $sql .= " SET fk_user = ".($this->fk_user > 0 ? $this->fk_user : "0"); @@ -211,12 +218,11 @@ class Bookmark extends CommonObject $sql .= " ,target = '".$this->db->escape($this->target)."'"; $sql .= " ,title = '".$this->db->escape($this->title)."'"; $sql .= " ,favicon = '".$this->db->escape($this->favicon)."'"; - $sql .= " ,position = '".$this->db->escape($this->position)."'"; + $sql .= " ,position = ".(int) $this->position; $sql .= " WHERE rowid = ".$this->id; dol_syslog("Bookmark::update", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { return 1; } else { $this->error = $this->db->lasterror(); @@ -237,8 +243,7 @@ class Bookmark extends CommonObject dol_syslog("Bookmark::remove", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { return 1; } else { $this->error = $this->db->lasterror(); @@ -288,7 +293,9 @@ class Bookmark extends CommonObject { global $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -298,33 +305,40 @@ class Bookmark extends CommonObject $url = DOL_URL_ROOT.'/bookmarks/card.php?id='.$this->id; - if ($option != 'nolink') - { + if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowBookmark"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -332,8 +346,11 @@ class Bookmark extends CommonObject $hookmanager->initHooks(array('mybookmarkdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index f55b3403546..8e2f07ec4fc 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -98,6 +98,7 @@ class Categorie extends CommonObject 8 => 'bank_line', 9 => 'warehouse', 10 => 'actioncomm', + 11 => 'website_page' ); /** @@ -221,7 +222,6 @@ class Categorie extends CommonObject /** * @var string Category type * - * @see Categorie::TYPE_ACCOUNT * @see Categorie::TYPE_PRODUCT * @see Categorie::TYPE_SUPPLIER * @see Categorie::TYPE_CUSTOMER @@ -229,9 +229,11 @@ class Categorie extends CommonObject * @see Categorie::TYPE_CONTACT * @see Categorie::TYPE_USER * @see Categorie::TYPE_PROJECT + * @see Categorie::TYPE_ACCOUNT * @see Categorie::TYPE_BANK_LINE - * @see Categorie::TYPE_WAREHOUSE - * @see Categorie::TYPE_ACTIONCOMM + * @see Categorie::TYPE_WAREHOUSE + * @see Categorie::TYPE_ACTIONCOMM + * @see Categorie::TYPE_WEBSITE_PAGE */ public $type; @@ -312,7 +314,7 @@ class Categorie extends CommonObject // Check parameters if (empty($id) && empty($label) && empty($ref_ext)) return -1; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_null($type) && !is_numeric($type)) $type = $this->MAP_ID[$type]; $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext"; $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif"; @@ -1058,7 +1060,7 @@ class Categorie extends CommonObject $current_lang = $langs->getDefaultLang(); // Init $this->cats array - $sql = "SELECT DISTINCT c.rowid, c.label, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates + $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ", t.label as label_trans, t.description as description_trans"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c"; if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index f4b7e12cc30..a5578032a3d 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -35,10 +35,10 @@ $langs->load("categories"); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alphanohtml'); -$type = GETPOST('type', 'aZ09'); // Can be int or string $action = (GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'edit'); $confirm = GETPOST('confirm'); $cancel = GETPOST('cancel', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); $socid = (int) GETPOST('socid', 'int'); $label = (string) GETPOST('label', 'alphanohtml'); @@ -56,10 +56,14 @@ if ($id == "") { $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -if ($id > 0) { - $result = $object->fetch($id); +$result = $object->fetch($id, $label); +if ($result <= 0) { + dol_print_error($db, $object->error); exit; } +$type = $object->type; +if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility + $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); @@ -74,8 +78,13 @@ $error = 0; */ if ($cancel) { - header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type); - exit; + if ($backtopage) { + header("Location: ".$backtopage); + exit; + } else { + header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type); + exit; + } } // Action mise a jour d'une categorie @@ -98,9 +107,15 @@ if ($action == 'update' && $user->rights->categorie->creer) { $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) $error++; - if (!$error && $object->update($user) > 0) { - header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type); - exit; + if (!$error && $object->update($user) > 0) + { + if ($backtopage) { + header("Location: ".$backtopage); + exit; + } else { + header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type); + exit; + } } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -131,6 +146,7 @@ print ''; print ''; print ''; print ''; +print ''; print dol_get_fiche_head(''); diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index 5adc7bbb17b..ff897db86a7 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -109,7 +109,7 @@ if (empty($nosearch)) { foreach ($cats as $cat) { - $color = $categstatic->color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #bbb"'; + $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; print "\t".''."\n"; print "\t\t"; } $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; + $li = $categstatic->getNomUrl(1, '', 60, '&backtolist='.urlencode($_SERVER["PHP_SELF"].'?type='.$type.$moreparam)); - $data[] = array( - 'rowid'=>$val['rowid'], - 'fk_menu'=>$val['fk_parent'], - 'entry'=>'
'.$langs->trans("Filters").''.$form->textwithpicto($langs->trans("Filters"), $langs->trans("EmailCollectorFilterDesc")).'
"; @@ -160,26 +160,45 @@ foreach ($fulltree as $key => $val) $categstatic->ref = $val['label']; $categstatic->color = $val['color']; $categstatic->type = $type; - $li = $categstatic->getNomUrl(1, '', 60, $moreparam.'&backtolist='.urlencode($_SERVER["PHP_SELF"].'?type='.$type.$moreparam)); $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; - if ($conf->global->CATEGORY_SHOW_COUNTS) { // we need only a count of the elements, so it is enough to consume only the id's from the database - $elements = $categstatic->getObjectsInCateg($type, 1); + $elements = $type == Categorie::TYPE_ACCOUNT + ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" + : $categstatic->getObjectsInCateg($type, 1); + $counter = "".(is_countable($elements) ? count($elements) : '0')."
'.$counter. - '
'.$li.''.img_view().'
' - ); + $entry = ''; + $entry .= ''; + + $entry .= ''; + + $entry .= $counter; + + $entry .= ''; + $entry .= ''; + $entry .= ''; + + $entry .= ''; + $entry .= '
'; + $entry .= ''.$li.''; + $entry .= ''; + $entry .= ''.img_view().''; + $entry .= ''; + $entry .= ''.img_edit().''; + $entry .= ''; + $entry .= ''.img_delete().''; + $entry .= '
'; + + $data[] = array('rowid' => $val['rowid'], 'fk_menu' => $val['fk_parent'], 'entry' => $entry); } @@ -194,7 +213,6 @@ if (!empty($conf->use_javascript_ajax)) print ''; $nbofentries = (count($data) - 1); - if ($nbofentries > 0) { print ''; diff --git a/htdocs/categories/info.php b/htdocs/categories/info.php index f64f3be8f9e..536b0c20a2c 100644 --- a/htdocs/categories/info.php +++ b/htdocs/categories/info.php @@ -37,16 +37,18 @@ $langs->loadLangs(array('categories', 'sendings')); $socid = 0; $id = GETPOST('id', 'int'); +$label = GETPOST('label', 'alpha'); // Security check if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -if (!$object->fetch($id) > 0) { - dol_print_error($db); - exit; +$result = $object->fetch($id, $label); +if ($result <= 0) { + dol_print_error($db, $object->error); exit; } + $type = $object->type; if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility @@ -63,11 +65,11 @@ llxHeader('', $langs->trans('Categories'), ''); $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); - print dol_get_fiche_head($head, 'info', $langs->trans($title), -1, 'category'); + $backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type); $linkback = ''.$langs->trans("BackToList").''; -$object->next_prev_filter = ' type = '.$type; +$object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index 73c7664f6c2..6bb5d79980c 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -38,7 +38,6 @@ $langs->loadlangs(array('categories', 'bills')); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$type = GETPOST('type'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); @@ -52,18 +51,16 @@ if ($id == '' && $label == '') $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -$result = $object->fetch($id, $label, $type); +$result = $object->fetch($id, $label); if ($result <= 0) { dol_print_error($db, $object->error); exit; } -$object->fetch_optionals(); -if ($result <= 0) { - dol_print_error($db, $object->error); exit; -} -$upload_dir = $conf->categorie->multidir_output[$object->entity]; +$type = $object->type; if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +$upload_dir = $conf->categorie->multidir_output[$object->entity]; + /* * Actions */ @@ -115,8 +112,6 @@ if ($object->id) $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); - - print dol_get_fiche_head($head, 'photos', $langs->trans($title), -1, 'category'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 423819c49ac..898484d0d51 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -39,7 +39,6 @@ $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); -$type = GETPOST('type', 'aZ09'); if ($id == '' && $label == '') { @@ -51,15 +50,12 @@ if ($id == '' && $label == '') $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -$result = $object->fetch($id, $label, $type); -if ($result <= 0) { - dol_print_error($db, $object->error); exit; -} -$object->fetch_optionals(); +$result = $object->fetch($id, $label); if ($result <= 0) { dol_print_error($db, $object->error); exit; } +$type = $object->type; if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility /* diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 864de6e2e98..93b162e4f28 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -38,7 +38,6 @@ $langs->load("categories"); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$type = GETPOST('type', 'aZ09'); $removeelem = GETPOST('removeelem', 'int'); $elemid = GETPOST('elemid', 'int'); @@ -73,19 +72,12 @@ if ($id == "" && $label == "") $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); -$result = $object->fetch($id, $label, $type); -if ($result <= 0) { - dol_print_error($db, $object->error); exit; -} -$object->fetch_optionals(); +$result = $object->fetch($id, $label); if ($result <= 0) { dol_print_error($db, $object->error); exit; } -$objecttype = $object->type; -if (is_numeric($objecttype)) $objecttype = Categorie::$MAP_ID_TO_CODE[$objecttype]; -if ($type === '') $type = $objecttype; - +$type = $object->type; if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility $extrafields = new ExtraFields($db); @@ -94,16 +86,18 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('categorycard', 'globalcard')); -// Protection when type provided is not similare to type of category -if ($objecttype != $type) { - print 'Error: Value for type parameter does not match value of the type of the category with id='.$id; - exit; -} - /* * Actions */ +if ($confirm == 'no') +{ + if ($backtopage) { + header("Location: ".$backtopage); + exit; + } +} + $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Remove element from category @@ -164,8 +158,13 @@ if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confi { if ($object->delete($user) >= 0) { - header("Location: ".DOL_URL_ROOT.'/categories/index.php?type='.$type); - exit; + if ($backtopage) { + header("Location: ".$backtopage); + exit; + } else { + header("Location: ".DOL_URL_ROOT.'/categories/index.php?type='.$type); + exit; + } } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -226,9 +225,8 @@ llxHeader("", $langs->trans("Categories"), $helpurl, '', 0, 0, $arrayofjs, $arra $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); - - print dol_get_fiche_head($head, 'card', $langs->trans($title), -1, 'category'); + $backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type); $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter = ' type = '.$object->type; @@ -250,7 +248,11 @@ dol_banner_tab($object, 'label', $linkback, ($user->socid ? 0 : 1), 'label', 'la if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type, $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 1); + if ($backtopage) { + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&backtopage='.urlencode($backtopage), $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 2); + } else { + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type, $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 1); + } } print '
'; @@ -294,7 +296,7 @@ if ($user->rights->categorie->creer) if ($user->rights->categorie->supprimer) { - print 'id.'&type='.$type.'">'.$langs->trans("Delete").''; + print 'id.'&type='.$type.'&backtolist='.urlencode($backtolist).'">'.$langs->trans("Delete").''; } print "
"; @@ -376,8 +378,7 @@ if ($cats < 0) $categstatic->type = $type; $desc = dol_htmlcleanlastbr($val['description']); - $counter = 0; - + $counter = ''; if ($conf->global->CATEGORY_SHOW_COUNTS) { // we need only a count of the elements, so it is enough to consume only the id's from the database @@ -385,22 +386,29 @@ if ($cats < 0) ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" : $categstatic->getObjectsInCateg($type, 1); - $counter = is_countable($elements) ? count($elements) : 0; + $counter = "".(is_countable($elements) ? count($elements) : '0').""; } - $color = $categstatic->color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"'; + $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; + $li = $categstatic->getNomUrl(1, '', 60, '&backtolist='.urlencode($_SERVER["PHP_SELF"].'?id='.$id.'&type='.$type)); $entry = ''; $entry .= ''; $entry .= ''; - $entry .= ''; + $entry .= $counter; $entry .= ''; + $entry .= ''; + $entry .= ''; $entry .= ''; @@ -409,7 +417,8 @@ if ($cats < 0) $data[] = array('rowid' => $val['rowid'], 'fk_menu' => $val['fk_parent'], 'entry' => $entry); } - if ((count($data) - 1)) + $nbofentries = (count($data) - 1); + if ($nbofentries > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; print ''; diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 510fa67dcdb..2fe47ab39f1 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -141,14 +141,8 @@ $arrayfields = array( 'a.tms'=>array('label'=>'DateModification', 'checked'=>0) ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index fe41203e946..93316384c2a 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -286,7 +286,10 @@ if ($object->id > 0) print ''; print ''; diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 1a3a1c9fe62..e045401bef4 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -23,7 +23,9 @@ * \brief Fiche mailing, onglet general */ -if (!defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); +if (!defined('NOSTYLECHECK')) { + define('NOSTYLECHECK', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; @@ -38,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load translation files required by the page $langs->load("mails"); -if (!$user->rights->mailing->lire || (empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->socid > 0)) accessforbidden(); +if (!$user->rights->mailing->lire || (empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->socid > 0)) { + accessforbidden(); +} $id = (GETPOST('mailid', 'int') ? GETPOST('mailid', 'int') : GETPOST('id', 'int')); $action = GETPOST('action', 'aZ09'); @@ -83,20 +87,18 @@ $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes') - { - if (!GETPOST("clone_content", 'alpha') && !GETPOST("clone_receivers", 'alpha')) - { + if ($action == 'confirm_clone' && $confirm == 'yes') { + if (!GETPOST("clone_content", 'alpha') && !GETPOST("clone_receivers", 'alpha')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { $result = $object->createFromClone($user, $object->id, GETPOST("clone_content", 'alpha'), GETPOST("clone_receivers", 'alpha')); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -107,24 +109,20 @@ if (empty($reshook)) } // Action send emailing for everybody - if ($action == 'sendallconfirmed' && $confirm == 'yes') - { - if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) - { + if ($action == 'sendallconfirmed' && $confirm == 'yes') { + if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) { // As security measure, we don't allow send from the GUI setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings'); setEventMessages('', null, 'warnings'); setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings'); $action = ''; - } elseif ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) - { + } elseif ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) { setEventMessages($langs->trans("NotEnoughPermissions"), null, 'warnings'); $action = ''; } else { $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); - if ($object->statut == 0) - { + if ($object->statut == 0) { dol_print_error('', 'ErrorMailIsNotValidated'); exit; } @@ -137,7 +135,9 @@ if (empty($reshook)) $errorsto = $object->email_errorsto; // Is the message in html $msgishtml = -1; // Unknown by default - if (preg_match('/[\s\t]*/i', $message)) $msgishtml = 1; + if (preg_match('/[\s\t]*/i', $message)) { + $msgishtml = 1; + } // Warning, we must not use begin-commit transaction here // because we want to save update for each mail sent. @@ -153,12 +153,10 @@ if (empty($reshook)) dol_syslog("card.php: select targets", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); // Number of possible recipients - if ($num) - { + if ($num) { dol_syslog("comm/mailing/card.php: nb of targets = ".$num, LOG_DEBUG); $now = dol_now(); @@ -166,16 +164,14 @@ if (empty($reshook)) // Positioning date of start sending $sql = "UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$object->id; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } // Loop on each email and send it $i = 0; - while ($i < $num && $i < $conf->global->MAILING_LIMIT_SENDBYWEB) - { + while ($i < $num && $i < $conf->global->MAILING_LIMIT_SENDBYWEB) { // Here code is common with same loop ino mailing-send.php $res = 1; $now = dol_now(); @@ -215,14 +211,18 @@ if (empty($reshook)) $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; $onlinepaymentenabled = 0; - if (!empty($conf->paypal->enabled)) $onlinepaymentenabled++; - if (!empty($conf->paybox->enabled)) $onlinepaymentenabled++; - if (!empty($conf->stripe->enabled)) $onlinepaymentenabled++; - if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { + if (!empty($conf->paypal->enabled)) { + $onlinepaymentenabled++; + } + if (!empty($conf->paybox->enabled)) { + $onlinepaymentenabled++; + } + if (!empty($conf->stripe->enabled)) { + $onlinepaymentenabled++; + } + if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); @@ -235,21 +235,32 @@ if (empty($reshook)) } } /* For backward compatibility, deprecated */ - if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_SECURITY_TOKEN)) - { + if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { + $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { + $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { + $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2); + } - if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); - else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); + if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) { + $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + } else { + $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2); + } } //$substitutionisok=true; @@ -263,10 +274,8 @@ if (empty($reshook)) $arr_css = array(); $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); - if (count($listofpaths)) - { - foreach ($listofpaths as $key => $val) - { + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { $arr_file[] = $listofpaths[$key]['fullname']; $arr_mime[] = dol_mimetype($listofpaths[$key]['name']); $arr_name[] = $listofpaths[$key]['name']; @@ -277,8 +286,7 @@ if (empty($reshook)) $trackid = 'emailing-'.$obj->fk_mailing.'-'.$obj->rowid; $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $errorsto, $arr_css, $trackid, '', 'emailing'); - if ($mail->error) - { + if ($mail->error) { $res = 0; } /*if (! $substitutionisok) @@ -288,13 +296,11 @@ if (empty($reshook)) }*/ // Send mail - if ($res) - { + if ($res) { $res = $mail->sendfile(); } - if ($res) - { + if ($res) { // Mail successful $nbok++; @@ -303,19 +309,16 @@ if (empty($reshook)) $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sql .= " SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } else { //if cheack read is use then update prospect contact status - if (strpos($message, '__CHECK_READ__') !== false) - { + if (strpos($message, '__CHECK_READ__') !== false) { //Update status communication of thirdparty prospect $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")"; dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG); $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } @@ -324,17 +327,15 @@ if (empty($reshook)) dol_syslog("card.php: set prospect contact status", LOG_DEBUG); $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } } } - if (!empty($conf->global->MAILING_DELAY)) - { + if (!empty($conf->global->MAILING_DELAY)) { dol_syslog("Wait a delay of MAILING_DELAY=".$conf->global->MAILING_DELAY); - sleep($conf->global->MAILING_DELAY); + usleep((float) $conf->global->MAILING_DELAY * 1000000); } //test if CHECK READ change statut prospect contact @@ -347,8 +348,7 @@ if (empty($reshook)) $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sql .= " SET statut=-1, error_text='".$db->escape($mail->error)."', date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } } @@ -360,14 +360,15 @@ if (empty($reshook)) } // Loop finished, set global statut of mail - if ($nbko > 0) - { + if ($nbko > 0) { $statut = 2; // Status 'sent partially' (because at least one error) - if ($nbok > 0) setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); - else setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); + if ($nbok > 0) { + setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); + } } else { - if ($nbok >= $num) - { + if ($nbok >= $num) { $statut = 3; // Send to everybody setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs'); } else { @@ -379,8 +380,7 @@ if (empty($reshook)) $sql = "UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$object->id; dol_syslog("comm/mailing/card.php: update global status", LOG_DEBUG); $resql2 = $db->query($sql); - if (!$resql2) - { + if (!$resql2) { dol_print_error($db); } } else { @@ -393,24 +393,23 @@ if (empty($reshook)) } // Action send test emailing - if ($action == 'send' && empty($_POST["cancel"])) - { + if ($action == 'send' && empty($_POST["cancel"])) { $error = 0; $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); $object->sendto = $_POST["sendto"]; - if (!$object->sendto) - { + if (!$object->sendto) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTo")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { // Is the message in html $msgishtml = -1; // Unknow by default - if (preg_match('/[\s\t]*/i', $object->body)) $msgishtml = 1; + if (preg_match('/[\s\t]*/i', $object->body)) { + $msgishtml = 1; + } // other are set at begin of page $object->substitutionarrayfortest['__EMAIL__'] = $object->sendto; @@ -427,15 +426,17 @@ if (empty($reshook)) $arr_css = array(); // Add CSS - if (!empty($object->bgcolor)) $arr_css['bgcolor'] = (preg_match('/^#/', $object->bgcolor) ? '' : '#').$object->bgcolor; - if (!empty($object->bgimage)) $arr_css['bgimage'] = $object->bgimage; + if (!empty($object->bgcolor)) { + $arr_css['bgcolor'] = (preg_match('/^#/', $object->bgcolor) ? '' : '#').$object->bgcolor; + } + if (!empty($object->bgimage)) { + $arr_css['bgimage'] = $object->bgimage; + } // Attached files $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); - if (count($listofpaths)) - { - foreach ($listofpaths as $key => $val) - { + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { $arr_file[] = $listofpaths[$key]['fullname']; $arr_mime[] = dol_mimetype($listofpaths[$key]['name']); $arr_name[] = $listofpaths[$key]['name']; @@ -446,8 +447,7 @@ if (empty($reshook)) $mailfile = new CMailFile($tmpsujet, $object->sendto, $object->email_from, $tmpbody, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $object->email_errorsto, $arr_css, $trackid, '', 'emailing'); $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { setEventMessages($langs->trans("MailSuccessfulySent", $mailfile->getValidAddress($object->email_from, 2), $mailfile->getValidAddress($object->sendto, 2)), null, 'mesgs'); $action = ''; } else { @@ -458,18 +458,17 @@ if (empty($reshook)) } // Action add emailing - if ($action == 'add') - { + if ($action == 'add') { $mesgs = array(); - $object->email_from = GETPOST("from", "none"); // Must allow 'name ' - $object->email_replyto = GETPOST("replyto", "none"); // Must allow 'name ' - $object->email_errorsto = GETPOST("errorsto", "none"); // Must allow 'name ' - $object->title = GETPOST("title"); - $object->sujet = GETPOST("sujet"); - $object->body = GETPOST("bodyemail", 'restricthtml'); - $object->bgcolor = GETPOST("bgcolor"); - $object->bgimage = GETPOST("bgimage"); + $object->email_from = (string) GETPOST("from", "none"); // Must allow 'name ' + $object->email_replyto = (string) GETPOST("replyto", "none"); // Must allow 'name ' + $object->email_errorsto = (string) GETPOST("errorsto", "none"); // Must allow 'name ' + $object->title = (string) GETPOST("title"); + $object->sujet = (string) GETPOST("sujet"); + $object->body = (string) GETPOST("bodyemail", 'restricthtml'); + $object->bgcolor = (string) GETPOST("bgcolor"); + $object->bgimage = (string) GETPOST("bgimage"); if (!$object->title) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle")); @@ -481,10 +480,8 @@ if (empty($reshook)) $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage")); } - if (!count($mesgs)) - { - if ($object->create($user) >= 0) - { + if (!count($mesgs)) { + if ($object->create($user) >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } @@ -496,24 +493,25 @@ if (empty($reshook)) } // Action update description of emailing - if ($action == 'settitle' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto') - { + if ($action == 'settitle' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto') { $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); - if ($action == 'settitle') $object->title = trim(GETPOST('title', 'alpha')); - elseif ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from', 'none')); // Must allow 'name ' - elseif ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto', 'none')); // Must allow 'name ' - elseif ($action == 'setemail_errorsto') $object->email_errorsto = trim(GETPOST('email_errorsto', 'none')); // Must allow 'name ' - elseif ($action == 'settitle' && empty($object->title)) { + if ($action == 'settitle') { + $object->title = trim(GETPOST('title', 'alpha')); + } elseif ($action == 'setemail_from') { + $object->email_from = trim(GETPOST('email_from', 'none')); // Must allow 'name ' + } elseif ($action == 'setemail_replyto') { + $object->email_replyto = trim(GETPOST('email_replyto', 'none')); // Must allow 'name ' + } elseif ($action == 'setemail_errorsto') { + $object->email_errorsto = trim(GETPOST('email_errorsto', 'none')); // Must allow 'name ' + } elseif ($action == 'settitle' && empty($object->title)) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle")); } elseif ($action == 'setfrom' && empty($object->email_from)) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailFrom")); } - if (!$mesg) - { - if ($object->update($user) >= 0) - { + if (!$mesg) { + if ($object->update($user) >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } @@ -527,8 +525,7 @@ if (empty($reshook)) /* * Add file in email form */ - if (!empty($_POST['addfile'])) - { + if (!empty($_POST['addfile'])) { $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -540,8 +537,7 @@ if (empty($reshook)) } // Action of file remove - if (!empty($_POST["removedfile"])) - { + if (!empty($_POST["removedfile"])) { $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -552,20 +548,18 @@ if (empty($reshook)) } // Action of emailing update - if ($action == 'update' && empty($_POST["removedfile"]) && empty($_POST["cancel"])) - { + if ($action == 'update' && empty($_POST["removedfile"]) && empty($_POST["cancel"])) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $isupload = 0; - if (!$isupload) - { + if (!$isupload) { $mesgs = array(); - $object->sujet = GETPOST("sujet"); - $object->body = GETPOST("bodyemail", 'restricthtml'); - $object->bgcolor = GETPOST("bgcolor"); - $object->bgimage = GETPOST("bgimage"); + $object->sujet = (string) GETPOST("sujet"); + $object->body = (string) GETPOST("bodyemail", 'restricthtml'); + $object->bgcolor = (string) GETPOST("bgcolor"); + $object->bgimage = (string) GETPOST("bgimage"); if (!$object->sujet) { $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTopic")); @@ -574,10 +568,8 @@ if (empty($reshook)) $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage")); } - if (!count($mesgs)) - { - if ($object->update($user) >= 0) - { + if (!count($mesgs)) { + if ($object->update($user) >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } @@ -592,10 +584,8 @@ if (empty($reshook)) } // Action of validation confirmation - if ($action == 'confirm_valid' && $confirm == 'yes') - { - if ($object->id > 0) - { + if ($action == 'confirm_valid' && $confirm == 'yes') { + if ($object->id > 0) { $object->valid($user); setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); @@ -606,13 +596,10 @@ if (empty($reshook)) } // Action of validation confirmation - if ($action == 'confirm_settodraft' && $confirm == 'yes') - { - if ($object->id > 0) - { + if ($action == 'confirm_settodraft' && $confirm == 'yes') { + if ($object->id > 0) { $result = $object->setStatut(0); - if ($result > 0) - { + if ($result > 0) { //setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs'); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; @@ -625,20 +612,16 @@ if (empty($reshook)) } // Resend - if ($action == 'confirm_reset' && $confirm == 'yes') - { - if ($object->id > 0) - { + if ($action == 'confirm_reset' && $confirm == 'yes') { + if ($object->id > 0) { $db->begin(); $result = $object->valid($user); - if ($result > 0) - { + if ($result > 0) { $result = $object->reset_targets_status($user); } - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; @@ -652,18 +635,15 @@ if (empty($reshook)) } // Action of delete confirmation - if ($action == 'confirm_delete' && $confirm == 'yes') - { - if ($object->delete($object->id)) - { + if ($action == 'confirm_delete' && $confirm == 'yes') { + if ($object->delete($object->id)) { $url = (!empty($urlfrom) ? $urlfrom : 'list.php'); header("Location: ".$url); exit; } } - if (!empty($_POST["cancel"])) - { + if (!empty($_POST["cancel"])) { $action = ''; } } @@ -677,24 +657,30 @@ $form = new Form($db); $htmlother = new FormOther($db); $help_url = 'EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'; -llxHeader('', $langs->trans("Mailing"), $help_url, '', 0, 0, +llxHeader( + '', + $langs->trans("Mailing"), + $help_url, + '', + 0, + 0, array( - '/includes/ace/src/ace.js', - '/includes/ace/src/ext-statusbar.js', - '/includes/ace/src/ext-language_tools.js', - //'/includes/ace/src/ext-chromevox.js' - ), array()); + '/includes/ace/src/ace.js', + '/includes/ace/src/ext-statusbar.js', + '/includes/ace/src/ext-language_tools.js', + //'/includes/ace/src/ext-chromevox.js' + ), + array() +); -if ($action == 'create') -{ +if ($action == 'create') { // EMailing in creation mode print '
'."\n"; print ''; print ''; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach ($object->substitutionarray as $key => $val) - { + foreach ($object->substitutionarray as $key => $val) { $htmltext .= $key.' = '.$langs->trans($val).'
'; } $htmltext .= '
'; @@ -718,8 +704,7 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -747,78 +732,80 @@ if ($action == 'create') print ''; } else { - if ($object->id > 0) - { + if ($object->id > 0) { $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing'); $head = emailing_prepare_head($object); - // Confirmation back to draft - if ($action == 'settodraft') - { + if ($action == 'settodraft') { + // Confirmation back to draft print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("SetToDraft"), $langs->trans("ConfirmUnvalidateEmailing"), "confirm_settodraft", '', '', 1); - } - // Confirmation of mailing validation - if ($action == 'valid') - { + } elseif ($action == 'valid') { + // Confirmation of mailing validation print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ValidMailing"), $langs->trans("ConfirmValidMailing"), "confirm_valid", '', '', 1); - } // Confirm reset - elseif ($action == 'reset') - { + } elseif ($action == 'reset') { + // Confirm reset print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ResetMailing"), $langs->trans("ConfirmResetMailing", $object->ref), "confirm_reset", '', '', 2); - } // Confirm delete - elseif ($action == 'delete') - { + } elseif ($action == 'delete') { + // Confirm delete print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id.(!empty($urlfrom) ? '&urlfrom='.urlencode($urlfrom) : ''), $langs->trans("DeleteAMailing"), $langs->trans("ConfirmDeleteMailing"), "confirm_delete", '', '', 1); } - - if ($action != 'edit' && $action != 'edithtml') - { + if ($action != 'edit' && $action != 'edithtml') { print dol_get_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email'); /* * View mode mailing */ - if ($action == 'sendall') - { + if ($action == 'sendall') { // Define message to recommand from command line $sendingmode = $conf->global->EMAILING_MAIL_SENDMODE; - if (empty($sendingmode)) $sendingmode = $conf->global->MAIN_MAIL_SENDMODE; - if (empty($sendingmode)) $sendingmode = 'mail'; // If not defined, we use php mail function + if (empty($sendingmode)) { + $sendingmode = $conf->global->MAIN_MAIL_SENDMODE; + } + if (empty($sendingmode)) { + $sendingmode = 'mail'; // If not defined, we use php mail function + } // MAILING_NO_USING_PHPMAIL may be defined or not. // MAILING_LIMIT_SENDBYWEB is always defined to something != 0 (-1=forbidden). // MAILING_LIMIT_SENDBYCLI may be defined ot not (-1=forbidden, 0 or undefined=no limit). - if (!empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') - { + if (!empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') { // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. // You ensure that every user is using its own SMTP server when using the mass emailing module. $linktoadminemailbefore = ''; $linktoadminemailend = ''; setEventMessages($langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]), null, 'warnings'); setEventMessages($langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']), null, 'warnings'); - if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) setEventMessages($langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS), null, 'warnings'); + if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) { + setEventMessages($langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS), null, 'warnings'); + } $_GET["action"] = ''; } elseif ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) { - if (!empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings'); - if (!empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings'); + if (!empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') { + setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings'); + } + if (!empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') { + setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings'); + } // The feature is forbidden from GUI, we show just message to use from command line. setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings'); setEventMessages('', null, 'warnings'); - if ($conf->file->mailing_limit_sendbyweb != '-1') // MAILING_LIMIT_SENDBYWEB was set to -1 in database, but it is allowed ot increase it. - { + if ($conf->file->mailing_limit_sendbyweb != '-1') { // MAILING_LIMIT_SENDBYWEB was set to -1 in database, but it is allowed ot increase it. setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings'); // You can send online with constant... } $_GET["action"] = ''; } else { - if (!empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings'); - if (!empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings'); + if (!empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') { + setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings'); + } + if (!empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') { + setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings'); + } $text = ''; - if (!isset($conf->global->MAILING_LIMIT_SENDBYCLI) || $conf->global->MAILING_LIMIT_SENDBYCLI >= 0) - { + if (!isset($conf->global->MAILING_LIMIT_SENDBYCLI) || $conf->global->MAILING_LIMIT_SENDBYCLI >= 0) { $text .= $langs->trans("MailingNeedCommand"); $text .= '
'; $text .= '

'; @@ -833,13 +820,14 @@ if ($action == 'create') $morehtmlright = ''; $nbtry = $nbok = 0; - if ($object->statut == 2 || $object->statut == 3) - { + if ($object->statut == 2 || $object->statut == 3) { $nbtry = $object->countNbOfTargets('alreadysent'); $nbko = $object->countNbOfTargets('alreadysentko'); $morehtmlright .= ' ('.$nbtry.'/'.$object->nbemail; - if ($nbko) $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); + if ($nbko) { + $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); + } $morehtmlright .= ')   '; } @@ -893,21 +881,19 @@ if ($action == 'create') print $langs->trans("TotalNbOfDistinctRecipients"); print '
';*/ + print $htmlother->selectColor($object->bgcolor,'bgcolor','',0); + print '';*/ print '
'; - $entry .= ''.$categstatic->getNomUrl(1, '', 60).''; + $entry .= ''.$li.''; $entry .= ''.$counter.''; - $entry .= ''.img_view().''; + $entry .= ''.img_view().''; + $entry .= ''; + $entry .= ''.img_edit().''; + $entry .= ''; + $entry .= ''.img_delete().''; $entry .= '
'; print $langs->trans('CustomerCode').''; print $object->code_client; - if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; + $tmpcheck = $object->check_codeclient(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' ('.$langs->trans("WrongCustomerCode").')'; + } print '
'; $nbemail = ($object->nbemail ? $object->nbemail : 0); - if (is_numeric($nbemail)) - { + if (is_numeric($nbemail)) { $text = ''; - if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) - { - if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) - { + if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail))) { + if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) { $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); } else { $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); } } - if (empty($nbemail)) $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; - if ($text) - { + if (empty($nbemail)) { + $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; + } + if ($text) { print $form->textwithpicto($nbemail, $text, 1, 'warning'); } else { print $nbemail; @@ -926,8 +912,7 @@ if ($action == 'create') // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { // Create an array for form $formquestion = array( 'text' => $langs->trans("ConfirmClone"), @@ -942,81 +927,67 @@ if ($action == 'create') * Actions Buttons */ - if (GETPOST('cancel', 'alpha') || $confirm == 'no' || $action == '' || in_array($action, array('settodraft', 'valid', 'delete', 'sendall', 'clone', 'test'))) - { + if (GETPOST('cancel', 'alpha') || $confirm == 'no' || $action == '' || in_array($action, array('settodraft', 'valid', 'delete', 'sendall', 'clone', 'test'))) { print "\n\n
\n"; - if (($object->statut == 1) && ($user->rights->mailing->valider || $object->fk_user_valid == $user->id)) - { + if (($object->statut == 1) && ($user->rights->mailing->valider || $object->fk_user_valid == $user->id)) { print ''.$langs->trans("SetToDraft").''; } - if (($object->statut == 0 || $object->statut == 1 || $object->statut == 2) && $user->rights->mailing->creer) - { - if (!empty($conf->fckeditor->enabled) && !empty($conf->global->FCKEDITOR_ENABLE_MAILING)) - { + if (($object->statut == 0 || $object->statut == 1 || $object->statut == 2) && $user->rights->mailing->creer) { + if (!empty($conf->fckeditor->enabled) && !empty($conf->global->FCKEDITOR_ENABLE_MAILING)) { print ''.$langs->trans("EditWithEditor").''; } else { print ''.$langs->trans("EditWithTextEditor").''; } - if (!empty($conf->use_javascript_ajax)) print ''.$langs->trans("EditHTMLSource").''; + if (!empty($conf->use_javascript_ajax)) { + print ''.$langs->trans("EditHTMLSource").''; + } } //print ''.$langs->trans("PreviewMailing").''; - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) - { + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("TestMailing").''; } else { print ''.$langs->trans("TestMailing").''; } - if ($object->statut == 0) - { - if ($object->nbemail <= 0) - { + if ($object->statut == 0) { + if ($object->nbemail <= 0) { print ''.$langs->trans("ValidMailing").''; - } elseif (empty($user->rights->mailing->valider)) - { + } elseif (empty($user->rights->mailing->valider)) { print ''.$langs->trans("ValidMailing").''; } else { print ''.$langs->trans("ValidMailing").''; } } - if (($object->statut == 1 || $object->statut == 2) && $object->nbemail > 0 && $user->rights->mailing->valider) - { - if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) - { + if (($object->statut == 1 || $object->statut == 2) && $object->nbemail > 0 && $user->rights->mailing->valider) { + if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) { print ''.$langs->trans("SendMailing").''; - } elseif (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) - { + } elseif (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("SendMailing").''; } else { print ''.$langs->trans("SendMailing").''; } } - if ($user->rights->mailing->creer) - { + if ($user->rights->mailing->creer) { print ''.$langs->trans("ToClone").''; } - if (($object->statut == 2 || $object->statut == 3) && $user->rights->mailing->valider) - { - if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) - { + if (($object->statut == 2 || $object->statut == 3) && $user->rights->mailing->valider) { + if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->send) { print ''.$langs->trans("ResetMailing").''; } else { print ''.$langs->trans("ResetMailing").''; } } - if (($object->statut <= 1 && $user->rights->mailing->creer) || $user->rights->mailing->supprimer) - { - if ($object->statut > 0 && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->delete)) - { + if (($object->statut <= 1 && $user->rights->mailing->creer) || $user->rights->mailing->supprimer) { + if ($object->statut > 0 && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->rights->mailing->mailing_advance->delete)) { print ''.$langs->trans("DeleteMailing").''; } else { print ''.$langs->trans("DeleteMailing").''; @@ -1027,8 +998,7 @@ if ($action == 'create') } // Display of the TEST form - if ($action == 'test') - { + if ($action == 'test') { print '
'; print load_fiche_titre($langs->trans("TestMailing")); @@ -1070,8 +1040,7 @@ if ($action == 'create') $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach ($object->substitutionarray as $key => $val) - { + foreach ($object->substitutionarray as $key => $val) { $htmltext .= $key.' = '.$langs->trans($val).'
'; } $htmltext .= '
'; @@ -1090,10 +1059,8 @@ if ($action == 'create') print '
'.$langs->trans("MailFile").''; // List of files $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0); - if (count($listofpaths)) - { - foreach ($listofpaths as $key => $val) - { + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { print img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name']; print '
'; } @@ -1104,21 +1071,22 @@ if ($action == 'create') // Background color /*print '
'.$langs->trans("BackgroundColorByDefault").''; - print $htmlother->selectColor($object->bgcolor,'bgcolor','',0); - print '
'; // Message print '
'; - if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') // CKEditor does not apply the color of the div into its content area - { + if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') { // CKEditor does not apply the color of the div into its content area $readonly = 1; // wysiwyg editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', false, true, empty($conf->global->FCKEDITOR_ENABLE_MAILING) ? 0 : 1, 20, '90%', $readonly); $doleditor->Create(); - } else print dol_htmlentitiesbr($object->body); + } else { + print dol_htmlentitiesbr($object->body); + } print '
'; print dol_get_fiche_end(); @@ -1132,7 +1100,9 @@ if ($action == 'create') $linkback = ''.$langs->trans("BackToList").''; $morehtmlright = ''; - if ($object->statut == 2) $morehtmlright .= ' ('.$object->countNbOfTargets('alreadysent').'/'.$object->nbemail.') '; + if ($object->statut == 2) { + $morehtmlright .= ' ('.$object->countNbOfTargets('alreadysent').'/'.$object->nbemail.') '; + } dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', '', '', 0, '', $morehtmlright); @@ -1160,21 +1130,19 @@ if ($action == 'create') print $langs->trans("TotalNbOfDistinctRecipients"); print ''; $nbemail = ($object->nbemail ? $object->nbemail : 0); - if (is_numeric($nbemail)) - { + if (is_numeric($nbemail)) { $text = ''; - if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || $object->statut == 2)) - { - if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) - { + if ((!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || $object->statut == 2)) { + if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0) { $text .= $langs->trans('LimitSendingEmailing', $conf->global->MAILING_LIMIT_SENDBYWEB); } else { $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed'); } } - if (empty($nbemail)) $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; - if ($text) - { + if (empty($nbemail)) { + $nbemail .= ' '.img_warning('').' '.$langs->trans("NoTargetYet").''; + } + if ($text) { print $form->textwithpicto($nbemail, $text, 1, 'warning'); } else { print $nbemail; @@ -1186,8 +1154,7 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } @@ -1206,8 +1173,7 @@ if ($action == 'create') print ''; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach ($object->substitutionarray as $key => $val) - { + foreach ($object->substitutionarray as $key => $val) { $htmltext .= $key.' = '.$langs->trans($val).'
'; } $htmltext .= '
'; @@ -1241,10 +1207,8 @@ if ($action == 'create') $out .= ' });'; $out .= '})'; $out .= ''."\n"; - if (count($listofpaths)) - { - foreach ($listofpaths as $key => $val) - { + if (count($listofpaths)) { + foreach ($listofpaths as $key => $val) { $out .= '
'; $out .= img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name']; $out .= ' '; @@ -1270,15 +1234,13 @@ if ($action == 'create') // Message print '
'; - if ($action == 'edit') - { + if ($action == 'edit') { // wysiwyg editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); $doleditor->Create(); } - if ($action == 'edithtml') - { + if ($action == 'edithtml') { // HTML source editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, 'ace', 20, '90%'); diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 0d621dfa186..81f64ef6016 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -463,24 +463,51 @@ if ($object->fetch($id) >= 0) $sql .= " mc.source_url, mc.source_id, mc.source_type, mc.error_text"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql .= " WHERE mc.fk_mailing=".$object->id; - if ($search_lastname) $sql .= natural_search("mc.lastname", $search_lastname); - if ($search_firstname) $sql .= natural_search("mc.firstname", $search_firstname); - if ($search_email) $sql .= natural_search("mc.email", $search_email); - if ($search_other) $sql .= natural_search("mc.other", $search_other); - if ($search_dest_status != '' && $search_dest_status >= -1) $sql .= " AND mc.statut=".$db->escape($search_dest_status)." "; + $asearchcriteriahasbeenset = 0; + if ($search_lastname) { + $sql .= natural_search("mc.lastname", $search_lastname); + $asearchcriteriahasbeenset++; + } + if ($search_firstname) { + $sql .= natural_search("mc.firstname", $search_firstname); + $asearchcriteriahasbeenset++; + } + if ($search_email) { + $sql .= natural_search("mc.email", $search_email); + $asearchcriteriahasbeenset++; + } + if ($search_other) { + $sql .= natural_search("mc.other", $search_other); + $asearchcriteriahasbeenset++; + } + if ($search_dest_status != '' && $search_dest_status >= -1) { + $sql .= " AND mc.statut=".$db->escape($search_dest_status)." "; + $asearchcriteriahasbeenset++; + } $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } + + // Fix/update nbemail on emailing record if it differs (may happen if user edit lines from database directly) + if (empty($asearchcriteriahasbeenset)) { + if ($nbtotalofrecords != $object->email) { + dol_syslog("We found a difference in nb of record in target table and the property ->nbemail, we fix ->nbemail"); + //print "nbemail=".$object->nbemail." nbtotalofrecords=".$nbtotalofrecords; + $resultrefresh = $object->refreshNbOfTargets(); + if ($resultrefresh < 0) { + dol_print_error($db, $object->error, $object->errors); + } + } + } } //$nbtotalofrecords=$object->nbemail; // nbemail is a denormalized field storing nb of targets diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php index 2f2b16bd119..2961218f148 100644 --- a/htdocs/comm/mailing/class/mailing.class.php +++ b/htdocs/comm/mailing/class/mailing.class.php @@ -118,36 +118,48 @@ class Mailing extends CommonObject /** * @var int id of user create - * @deprecated */ public $user_creation; /** * @var int id of user create + * @deprecated */ public $user_creat; /** * @var int id of user validate - * @deprecated */ public $user_validation; /** * @var int id of user validate + * @deprecated */ public $user_valid; /** * @var integer|string date_creation + * @deprecated */ public $date_creat; + /** + * @var integer|string date_creation + */ + public $date_creation; + /** * @var int date validate + * @deprecated */ public $date_valid; + /** + * @var int date validate + */ + public $date_validation; + /** * @var array extraparams */ @@ -314,10 +326,14 @@ class Mailing extends CommonObject $this->email_errorsto = $obj->email_errorsto; $this->user_creat = $obj->fk_user_creat; + $this->user_creation = $obj->fk_user_creat; $this->user_valid = $obj->fk_user_valid; + $this->user_validation = $obj->fk_user_valid; $this->date_creat = $this->db->jdate($obj->date_creat); + $this->date_creation = $this->db->jdate($obj->date_creat); $this->date_valid = $this->db->jdate($obj->date_valid); + $this->date_validation = $this->db->jdate($obj->date_valid); $this->date_envoi = $this->db->jdate($obj->date_envoi); $this->extraparams = (array) json_decode($obj->extraparams, true); @@ -510,6 +526,8 @@ class Mailing extends CommonObject dol_syslog("Mailing::delete_targets", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { + $this->refreshNbOfTargets(); + return 1; } else { $this->error = $this->db->lasterror(); @@ -577,6 +595,38 @@ class Mailing extends CommonObject return 0; } + /** + * Refresh denormalized value ->nbemail into emailing record + * Note: There is also the method update_nb into modules_mailings that is used for this. + * + * @return int <0 if KO, >0 if OK + */ + public function refreshNbOfTargets() + { + $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_cibles"; + $sql .= " WHERE fk_mailing = ".$this->id; + + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $nbforupdate = $obj->nb; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.'mailing SET nbemail = '.((int) $nbforupdate); + $sql .= ' WHERE rowid = '.$this->id; + + $resqlupdate = $this->db->query($sql); + if (! $resqlupdate) { + $this->error = $this->db->lasterror(); + return -1; + } + } + } else { + $this->error = $this->db->lasterror(); + return -1; + } + return 1; + } /** * Return a link to the object card (with optionally the picto) diff --git a/htdocs/comm/mailing/info.php b/htdocs/comm/mailing/info.php index 199a5caad8b..4bd39309701 100644 --- a/htdocs/comm/mailing/info.php +++ b/htdocs/comm/mailing/info.php @@ -33,8 +33,9 @@ $id = GETPOST('id', 'int'); $langs->load("mails"); // Security check -if (!$user->rights->mailing->lire || $user->socid > 0) -accessforbidden(); +if (!$user->rights->mailing->lire || $user->socid > 0) { + accessforbidden(); +} @@ -48,8 +49,7 @@ $form = new Form($db); $object = new Mailing($db); -if ($object->fetch($id) >= 0) -{ +if ($object->fetch($id) >= 0) { $head = emailing_prepare_head($object); print dol_get_fiche_head($head, 'info', $langs->trans("Mailing"), -1, 'email'); @@ -58,13 +58,14 @@ if ($object->fetch($id) >= 0) $morehtmlright = ''; $nbtry = $nbok = 0; - if ($object->statut == 2 || $object->statut == 3) - { + if ($object->statut == 2 || $object->statut == 3) { $nbtry = $object->countNbOfTargets('alreadysent'); $nbko = $object->countNbOfTargets('alreadysentko'); $morehtmlright .= ' ('.$nbtry.'/'.$object->nbemail; - if ($nbko) $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); + if ($nbko) { + $morehtmlright .= ' - '.$nbko.' '.$langs->trans("Error"); + } $morehtmlright .= ')   '; } @@ -73,10 +74,6 @@ if ($object->fetch($id) >= 0) print '

'; //print '
'; - $object->user_creation = $object->user_creat; - $object->date_creation = $object->date_creat; - $object->user_validation = $object->user_valid; - $object->date_validation = $object->date_valid; dol_print_object_info($object, 0); //print '
'; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 12146179db0..f6a63ba9a48 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1660,7 +1660,7 @@ if ($action == 'create') print ''.$langs->trans('NotePublic').''; print ''; $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc) ? $objectsrc->note_public : null)); - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // Private note @@ -1670,7 +1670,7 @@ if ($action == 'create') print ''.$langs->trans('NotePrivate').''; print ''; $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc)) ? $objectsrc->note_private : null)); - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // print ' print ''; diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 274c04b0698..f572f6110bf 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -598,6 +598,7 @@ class Propal extends CommonObject $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code + $reg = array(); $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 213819b0915..3a4cfde8057 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1736,7 +1736,7 @@ if ($action == 'create' && $usercancreate) print ''.$langs->trans('NotePublic').''; print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // print ''; print ''; @@ -1747,7 +1747,7 @@ if ($action == 'create' && $usercancreate) print ''.$langs->trans('NotePrivate').''; print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // print ''; print ''; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 9ea05a13065..d8fdb51141e 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -492,26 +492,21 @@ class Commande extends CommonOrder $error++; } - if (!$error) - { + if (!$error) { // If stock is incremented on validate order, we must increment it - if ($result >= 0 && !empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) - { + if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrement stock of product (and sub-products) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr", $num)); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $mouvP->error; } @@ -521,16 +516,14 @@ class Commande extends CommonOrder } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_VALIDATE', $user); if ($result < 0) $error++; // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref @@ -631,7 +624,7 @@ class Commande extends CommonOrder } // If stock is decremented on validate order, we must reincrement it - if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { $result = 0; @@ -817,7 +810,7 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { // If stock is decremented on validate order, we must reincrement it - if (!empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -3166,8 +3159,8 @@ class Commande extends CommonOrder $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]; + $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]; $this->line->remise_percent = $remise_percent; $this->line->subprice = $subprice; $this->line->info_bits = $info_bits; diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 72a5e179f25..5fa4a3adfaa 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -675,7 +675,7 @@ if ($resql) if (!empty($arrayfields['s.nom']['checked'])) { print ''; - print ''; + print ''; print ''; } // Town diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index cc9abb8d594..734d21b1c87 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -529,7 +529,7 @@ print ''.$langs->trans("ExportAccountingSourceDocHel print '
'; print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_start', 0, 0, 0, "", 1, 1, 0); -print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; +print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; // Export is for current company only if (!empty($conf->multicompany->enabled) && is_object($mc)) @@ -560,7 +560,7 @@ $listofchoices = array( ); foreach ($listofchoices as $choice => $val) { $checked = (((!GETPOSTISSET('search') && $action != 'searchfiles') || GETPOST($choice)) ? ' checked="checked"' : ''); - print '
'.$langs->trans($val['label']).'
'; + print '
'; } print ''; diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 902a96ec16c..63021eb3b07 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -155,14 +155,8 @@ $arrayfields = array( 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), ); // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); @@ -496,7 +490,7 @@ if (dol_strlen($search_dv_end) > 0) $sql .= " AND b.datev <= '".$db->idate($sear if ($search_ref) $sql .= natural_search("b.rowid", $search_ref, 1); if ($search_req_nb) $sql .= natural_search("b.num_chq", $search_req_nb); if ($search_num_releve) $sql .= natural_search("b.num_releve", $search_num_releve); -if ($search_conciliated != '' && $search_conciliated != '-1') $sql .= " AND b.rappro = ".$search_conciliated; +if ($search_conciliated != '' && $search_conciliated != '-1') $sql .= " AND b.rappro = ".urlencode($search_conciliated); if ($search_thirdparty) $sql .= natural_search("s.nom", $search_thirdparty); if ($search_description) { @@ -861,6 +855,10 @@ if ($resql) $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + // When action is 'reconcile', we force to have the column num_releve always enabled (otherwise we can't make reconciliation). + if ($action == 'reconcile') { + $arrayfields['b.num_releve']['checked'] = 1; + } print '
'; print ''."\n"; @@ -993,9 +991,8 @@ if ($resql) while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); - // If we are in a situation where we need/can show balance, we calculate the start of balance - if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) + if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && ($mode_balance_ok || $search_conciliated === '0')) { if (!$search_account) { @@ -1016,11 +1013,9 @@ if ($resql) $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; $resqlforbalance = $db->query($sqlforbalance); //print $sqlforbalance; - if ($resqlforbalance) - { + if ($resqlforbalance) { $objforbalance = $db->fetch_object($resqlforbalance); - if ($objforbalance) - { + if ($objforbalance) { // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') { @@ -1081,24 +1076,30 @@ if ($resql) if (!empty($arrayfields['balancebefore']['checked'])) { print ''; } if (!empty($arrayfields['balance']['checked'])) { print ''; + } + if (!empty($arrayfields['b.num_releve']['checked'])) + { + print ''; } - - print ''; print ''; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index e93491ceee4..b2d499c5f34 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -1741,13 +1741,6 @@ class AccountLine extends CommonObject public $amount; - /** - * @var string bank transaction lines label - */ - public $label; - - public $note; - /** * @var int ID */ @@ -1763,11 +1756,6 @@ class AccountLine extends CommonObject */ public $fk_type; - public $rappro; // Is it conciliated - public $num_releve; // If conciliated, what is bank statement - public $num_chq; // Num of cheque - public $bank_chq; // Bank of cheque - /** * @var int ID of cheque receipt */ @@ -1778,16 +1766,40 @@ class AccountLine extends CommonObject */ public $fk_account; + /** + * @var string Ref of bank account + */ + public $bank_account_ref; + /** * @var string Label of bank account */ public $bank_account_label; + /** + * @var string Bank account numero + */ + public $numero_compte; + /** * @var string Name of check issuer */ public $emetteur; + public $rappro; // Is it conciliated + public $num_releve; // If conciliated, what is bank statement + public $num_chq; // Num of cheque + public $bank_chq; // Bank of cheque + + /** + * @var string bank transaction lines label + */ + public $label; + + public $note; + + + /** * Constructor * diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 5c8031f2702..6c2e12ba500 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -93,7 +93,18 @@ class PaymentVarious extends CommonObject public $fk_project; /** - * @var int ID + * @var int Bank account ID + */ + public $fk_account; + + /** + * @var int Bank account ID + * @deprecated See fk_account + */ + public $accountid; + + /** + * @var int ID record into llx_bank */ public $fk_bank; @@ -102,11 +113,6 @@ class PaymentVarious extends CommonObject */ public $categorie_transaction; - /** - * @var int Account ID - */ - public $accountid; - /** * @var int ID */ @@ -397,6 +403,10 @@ class PaymentVarious extends CommonObject $this->fk_bank = (int) $this->fk_bank; $this->fk_user_author = (int) $this->fk_user_author; $this->fk_user_modif = (int) $this->fk_user_modif; + $this->fk_account = (int) $this->fk_account; + if (empty($this->fk_account) && isset($this->accountid)) { // For compatibility + $this->fk_account = $this->accountid; + } // Check parameters if (!$this->label) @@ -409,9 +419,9 @@ class PaymentVarious extends CommonObject $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); return -5; } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) + if (!empty($conf->banque->enabled) && (empty($this->fk_account) || $this->fk_account <= 0)) { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("BankAccount")); return -6; } if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) @@ -454,7 +464,7 @@ class PaymentVarious extends CommonObject $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 0); $sql .= ", ".$user->id; $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", NULL"; + $sql .= ", NULL"; // Filled later $sql .= ", ".$conf->entity; $sql .= ")"; @@ -473,7 +483,7 @@ class PaymentVarious extends CommonObject require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); - $result = $acc->fetch($this->accountid); + $result = $acc->fetch($this->fk_account); if ($result <= 0) dol_print_error($this->db); // Insert payment into llx_bank @@ -495,7 +505,7 @@ class PaymentVarious extends CommonObject $this->datev ); - // Update fk_bank into llx_paiement. + // Update fk_bank into llx_payment_various // So we know the payment which has generate the banking ecriture if ($bank_line_id > 0) { $this->update_fk_bank($bank_line_id); diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 87c8380ebda..f3efea15235 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -106,14 +106,8 @@ $arrayfields = array( 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1010), ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index db539e060d2..dfdad0b589b 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -491,7 +491,7 @@ if ($id) ); $formquestion[] = array('type' => 'date', 'tdclass'=>'fieldrequired', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1); $formquestion[] = array('type' => 'date', 'name' => 'clone_date_value', 'label' => $langs->trans("DateValue"), 'value' => -1); - $formquestion[] = array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($accountid, "accountid", 0, '', 1)); + $formquestion[] = array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($accountid, "accountid", 0, '', 1, '', 0, 'minwidth200', 1)); print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 300); } diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index 48da6483152..9c936c1d943 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -466,14 +466,18 @@ if ($result) // Project if ($arrayfields['project']['checked']) { - $proj->fetch($obj->fk_project); - print ''; + print ''; if (!$i) $totalarray['nbfield']++; } // Bank account if ($arrayfields['bank']['checked']) { - print '\n"; - $posconciliatecol = 0; - // Loop on each record $sign = 1; $cash = $bank = $cheque = $other = 0; @@ -263,7 +262,7 @@ if ($resql) { print "
'; - print price(price2num($balance, 'MT'), 1, $langs); + if ($search_conciliated !== '0') { + print price(price2num($balance, 'MT'), 1, $langs); + } print ''; - print price(price2num($balance, 'MT'), 1, $langs); + if ($search_conciliated !== '0') { + print price(price2num($balance, 'MT'), 1, $langs); + } + print ''; + print ''; + print ' '; print ''; - print ''; - print ' '; - print ''; print ' '; print ''.$proj->getNomUrl(1).''; + if ($obj->fk_project > 0) { + $proj->fetch($obj->fk_project); + print $proj->getNomUrl(1); + } + print ''; + print ''; if ($obj->bid > 0) { $accountstatic->id = $obj->bid; diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index fdc3e57bdba..c6431143a98 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -120,14 +120,8 @@ foreach ($object->fields as $key => $val) if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { - if (!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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index 515067900e3..04cdea52f7f 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -133,7 +133,8 @@ if ($resql) { print "

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

"; + print "
".$langs->trans("DateCreationShort").": ".dol_print_date($cashcontrol->date_creation, 'dayhour'); + print ""; $invoicetmp = new Facture($db); @@ -156,8 +157,6 @@ if ($resql) { print_liste_field_titre($arrayfields['b.credit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, 'right '); print "
"; //$cash = $amountpertype['LIQ'] + $cashcontrol->opening; - $cash = $cash + $cashcontrol->opening; + $cash = price2num($cash + $cashcontrol->opening, 'MT'); print "

"; print $langs->trans("Cash").": ".price($cash); diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 0a18d68b5db..f1e34e99985 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -252,7 +252,7 @@ if ($action == 'create') print ''.$langs->trans('NotePublic').''; print ''; - $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_8, '90%'); print $doleditor->Create(1); print ''; @@ -264,7 +264,7 @@ if ($action == 'create') print ''.$langs->trans('NotePrivate').''; print ''; - $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_8, '90%'); print $doleditor->Create(1); print ''; @@ -349,7 +349,7 @@ if ($action == 'create') print ''.$langs->trans("NotePublic").''; print ''; - $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_8, '90%'); print $doleditor->Create(1); print ""; @@ -360,7 +360,7 @@ if ($action == 'create') print ''.$langs->trans("NotePrivate").''; print ''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_8, '90%'); print $doleditor->Create(1); print ""; diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index 11dec142a17..d0089b0323e 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -156,7 +156,7 @@ if (empty($reshook)) // Create predefined invoice if ($action == 'add') { - if (!GETPOST('titre', 'nohtml')) + if (!GETPOST('title', 'alphanohtml')) { setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("Title")), null, 'errors'); $action = "create"; @@ -289,7 +289,7 @@ if (empty($reshook)) elseif ($action == 'setref' && $user->rights->facture->creer) { //var_dump(GETPOST('ref', 'alpha'));exit; - $result = $object->setValueFrom('titre', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY'); + $result = $object->setValueFrom('title', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY'); if ($result > 0) { $object->titre = GETPOST('ref', 'alpha'); // deprecated @@ -967,7 +967,7 @@ if ($action == 'create') // Title print ''.$langs->trans("Title").''; - print ''; + print ''; print ''; // Third party @@ -1008,7 +1008,7 @@ if ($action == 'create') print $form->textwithpicto($langs->trans('NotePublic'), $htmltext, 1, 'help', '', 0, 2, 'notepublic'); print ''; print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // Private note @@ -1019,7 +1019,7 @@ if ($action == 'create') print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); print ''; print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // print ' print ''; @@ -1237,7 +1237,7 @@ if ($action == 'create') } $morehtmlref .= '

'; - dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); + dol_banner_tab($object, 'ref', $linkback, 1, 'title', 'none', $morehtmlref, '', 0, '', $morehtmlright); print '
'; print '
'; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 4451f13bd77..e16d07f084f 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2433,22 +2433,22 @@ if (empty($reshook)) { $object->fetch($id, '', '', '', true); - if ($object->statut == Facture::STATUS_VALIDATED - && $object->type == Facture::TYPE_SITUATION - && $usercancreate - && !$objectidnext - && $object->is_last_in_cycle() - && $usercanunvalidate - ) - { - $outingError = 0; - $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle - if ($newCycle > 1) - { - // Search credit notes - $lastCycle = $object->situation_cycle_ref; - $lastSituationCounter = $object->situation_counter; - $linkedCreditNotesList = array(); + if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) + && $object->type == Facture::TYPE_SITUATION + && $usercancreate + && !$objectidnext + && $object->is_last_in_cycle() + && $usercanunvalidate + ) + { + $outingError = 0; + $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle + if ($newCycle > 1) + { + // Search credit notes + $lastCycle = $object->situation_cycle_ref; + $lastSituationCounter = $object->situation_counter; + $linkedCreditNotesList = array(); if (count($object->tab_next_situation_invoice) > 0) { foreach ($object->tab_next_situation_invoice as $next_invoice) { @@ -3534,7 +3534,7 @@ if ($action == 'create') print $form->textwithpicto($langs->trans('NotePublic'), $htmltext); print ''; print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // Private note @@ -3545,7 +3545,7 @@ if ($action == 'create') print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext); print ''; print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); // print ' print ''; @@ -3764,18 +3764,18 @@ if ($action == 'create') // Confirmation to remove invoice from cycle if ($action == 'situationout') { - $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref); - $label = $langs->trans("ConfirmOuting"); - $formquestion = array(); - // remove situation from cycle - if ($object->statut == Facture::STATUS_VALIDATED - && $usercancreate - && !$objectidnext - && $object->is_last_in_cycle() - && $usercanunvalidate - ) - { - $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1); + $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref); + $label = $langs->trans("ConfirmOuting"); + $formquestion = array(); + // remove situation from cycle + if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) + && $usercancreate + && !$objectidnext + && $object->is_last_in_cycle() + && $usercanunvalidate + ) + { + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1); } } @@ -5278,12 +5278,12 @@ if ($action == 'create') } // Remove situation from cycle - if ($object->statut > Facture::STATUS_DRAFT - && $object->type == Facture::TYPE_SITUATION - && $usercancreate - && !$objectidnext - && $object->situation_counter > 1 - && $object->is_last_in_cycle() + if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) + && $object->type == Facture::TYPE_SITUATION + && $usercancreate + && !$objectidnext + && $object->situation_counter > 1 + && $object->is_last_in_cycle() && $usercanunvalidate ) { diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 48e2ad574ed..9c0d191f0cf 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -215,7 +215,7 @@ class FactureRec extends CommonInvoice $now = dol_now(); // Clean parameters - $this->titre = trim($this->titre); // deprecated + $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated $this->title = trim($this->title); $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice; if (empty($this->suspended)) $this->suspended = 0; @@ -366,7 +366,7 @@ class FactureRec extends CommonInvoice } // Add object linked - if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects)) + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { foreach ($this->linked_objects as $origin => $tmp_origin_id) { @@ -702,7 +702,7 @@ class FactureRec extends CommonInvoice $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; $line->total_ttc = $objp->total_ttc; - $line->code_ventilation = $objp->fk_code_ventilation; + //$line->code_ventilation = $objp->fk_code_ventilation; $line->fk_fournprice = $objp->fk_fournprice; $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); $line->pa_ht = $marginInfos[0]; @@ -935,9 +935,9 @@ class FactureRec extends CommonInvoice $sql .= ", ".price2num($txtva); $sql .= ", '".$this->db->escape($vat_src_code)."'"; $sql .= ", ".price2num($txlocaltax1); - $sql .= ", '".$this->db->escape($localtaxes_type[0])."'"; + $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'"; $sql .= ", ".price2num($txlocaltax2); - $sql .= ", '".$this->db->escape($localtaxes_type[2])."'"; + $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'"; $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null"); $sql .= ", ".$product_type; $sql .= ", ".price2num($remise_percent); @@ -1996,7 +1996,7 @@ class FactureLigneRec extends CommonInvoiceLine $this->localtax1_type = $objp->localtax1_type; $this->localtax2_type = $objp->localtax2_type; $this->remise_percent = $objp->remise_percent; - $this->fk_remise_except = $objp->fk_remise_except; + //$this->fk_remise_except = $objp->fk_remise_except; $this->fk_product = $objp->fk_product; $this->date_start_fill = $objp->date_start_fill; $this->date_end_fill = $objp->date_end_fill; @@ -2004,7 +2004,7 @@ class FactureLigneRec extends CommonInvoiceLine $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; $this->total_ttc = $objp->total_ttc; - $this->code_ventilation = $objp->fk_code_ventilation; + //$this->code_ventilation = $objp->fk_code_ventilation; $this->rang = $objp->rang; $this->special_code = $objp->special_code; $this->fk_unit = $objp->fk_unit; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 5f7bf4fcf77..ac1270ed550 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -868,7 +868,7 @@ class Facture extends CommonInvoice $line->situation_percent, $line->fk_prev_id, $line->fk_unit, - $line->pu_ht_devise, + $line->multicurrency_subprice, $line->ref_ext ); if ($result < 0) @@ -968,7 +968,7 @@ class Facture extends CommonInvoice $_facrec->lines[$i]->situation_percent, '', $_facrec->lines[$i]->fk_unit, - $_facrec->lines[$i]->pu_ht_devise + $_facrec->lines[$i]->multicurrency_subprice ); if ($result_insert < 0) @@ -2971,7 +2971,7 @@ class Facture extends CommonInvoice * @param int $situation_percent Situation advance percentage * @param int $fk_prev_id Previous situation line id reference * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param double $pu_ht_devise Unit price in currency + * @param double $pu_ht_devise Unit price in foreign currency * @param string $ref_ext External reference of the line * @return int <0 if KO, Id of line if OK */ @@ -3136,8 +3136,8 @@ class Facture extends CommonInvoice $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 = isset($localtaxes_type[0]) ? $localtaxes_type[0] : ''; - $this->line->localtax2_type = isset($localtaxes_type[2]) ? $localtaxes_type[2] : ''; + $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]; + $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]; $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative @@ -3375,8 +3375,8 @@ class Facture extends CommonInvoice $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; - $this->line->localtax1_type = $localtaxes_type[0]; - $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0]; + $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2]; $this->line->remise_percent = $remise_percent; $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index c0abc5a6028..6beb5caa1e2 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -135,14 +135,8 @@ $arrayfields = array( 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 7e852846d5c..d50813cbea4 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -213,7 +213,7 @@ if ($object->id > 0) $head = facture_prepare_head($object); } - print dol_get_fiche_head($head, 'standingorders', $title, -1, 'bill'); + print dol_get_fiche_head($head, 'standingorders', $title, -1, ($type == 'bank-transfer' ? 'supplier_invoice' : 'bill')); // Invoice content if ($type == 'bank-transfer') { diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 8a1655cdefb..3072dcdee2b 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -229,6 +229,8 @@ if ($modecompta == 'BOOKKEEPING') print "\n"; +$total_ht_outcome = $total_ttc_outcome = $total_ht_income = $total_ttc_income = 0; + if ($modecompta == 'BOOKKEEPING') { @@ -438,16 +440,97 @@ if ($modecompta == 'BOOKKEEPING') if ($total_ttc == 0) { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } + $total_ht_income += $total_ht; + $total_ttc_income += $total_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price($total_ht).''; print ''.price($total_ttc).''; print ''; + /* + * Donations + */ + + if (!empty($conf->don->enabled)) + { + print ''.$langs->trans("Donations").''; + + if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') + { + if ($modecompta == 'CREANCES-DETTES') + { + $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql .= " WHERE p.entity IN (".getEntity('donation').")"; + $sql .= " AND fk_statut in (1,2)"; + } else { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql .= " WHERE p.entity IN (".getEntity('donation').")"; + $sql .= " AND fk_statut >= 2"; + } + if (!empty($date_start) && !empty($date_end)) + $sql .= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; + } + $sql .= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + $newsortfield = $sortfield; + if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.societe, p.firstname, p.lastname, dm'; + if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; + if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; + $sql .= $db->order($newsortfield, $sortorder); + + dol_syslog("get dunning"); + $result = $db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $total_ht += $obj->amount; + $total_ttc += $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + print ' '; + + print "".$langs->trans("Donation")." name."&search_name=".$obj->firstname." ".$obj->lastname."\">".$obj->name." ".$obj->firstname." ".$obj->lastname."\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''.price($obj->amount).''; + print ''.price($obj->amount).''; + print ''; + $i++; + } + } else { + print ' '; + print ''.$langs->trans("None").''; + print ''; + } + } else { + dol_print_error($db); + } + + $total_ht_income += $subtotal_ht; + $total_ttc_income += $subtotal_ttc; + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''.price($subtotal_ht).''; + print ''.price($subtotal_ttc).''; + print ''; + } /* * Suppliers invoices @@ -515,7 +598,7 @@ if ($modecompta == 'BOOKKEEPING') } } else { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } @@ -523,6 +606,9 @@ if ($modecompta == 'BOOKKEEPING') } else { dol_print_error($db); } + + $total_ht_outcome += $subtotal_ht; + $total_ttc_outcome += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price(-$subtotal_ht).''; @@ -530,7 +616,6 @@ if ($modecompta == 'BOOKKEEPING') print ''; - /* * Charges sociales non deductibles */ @@ -592,12 +677,15 @@ if ($modecompta == 'BOOKKEEPING') } } else { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } } else { dol_print_error($db); } + + $total_ht_outcome += $subtotal_ht; + $total_ttc_outcome += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price(-$subtotal_ht).''; @@ -667,36 +755,21 @@ if ($modecompta == 'BOOKKEEPING') } } else { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } } else { dol_print_error($db); } + + $total_ht_outcome += $subtotal_ht; + $total_ttc_outcome += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price(-$subtotal_ht).''; print ''.price(-$subtotal_ttc).''; print ''; - if ($mysoc->tva_assuj == 'franchise') // Non assujetti - { - // Total - print ''; - print ' '; - print ''; - - print ''.$langs->trans("Profit").''; - if ($modecompta == 'CREANCES-DETTES') - print ''.price($total_ht).''; - print ''.price($total_ttc).''; - print ''; - - print ''; - print ' '; - print ''; - } - /* * Salaries @@ -759,12 +832,15 @@ if ($modecompta == 'BOOKKEEPING') } } else { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } } else { dol_print_error($db); } + + $total_ht_outcome += $subtotal_ht; + $total_ttc_outcome += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price(-$subtotal_ht).''; @@ -841,98 +917,26 @@ if ($modecompta == 'BOOKKEEPING') } } else { print ' '; - print ''.$langs->trans("None").''; + print ''.$langs->trans("None").''; print ''; } } else { dol_print_error($db); } + + $total_ht_outcome += $subtotal_ht; + $total_ttc_outcome += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price(-$subtotal_ht).''; print ''.price(-$subtotal_ttc).''; print ''; } - /* - * Donations - */ - - if (!empty($conf->don->enabled)) - { - print ''.$langs->trans("Donations").''; - - if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') - { - if ($modecompta == 'CREANCES-DETTES') - { - $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql .= " WHERE p.entity IN (".getEntity('donation').")"; - $sql .= " AND fk_statut in (1,2)"; - } else { - $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; - $sql .= " WHERE p.entity IN (".getEntity('donation').")"; - $sql .= " AND fk_statut >= 2"; - } - if (!empty($date_start) && !empty($date_end)) - $sql .= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; - } - $sql .= " GROUP BY p.societe, p.firstname, p.lastname, dm"; - $newsortfield = $sortfield; - if ($newsortfield == 's.nom, s.rowid') $newsortfield = 'p.societe, p.firstname, p.lastname, dm'; - if ($newsortfield == 'amount_ht') $newsortfield = 'amount'; - if ($newsortfield == 'amount_ttc') $newsortfield = 'amount'; - $sql .= $db->order($newsortfield, $sortorder); - - dol_syslog("get dunning"); - $result = $db->query($sql); - $subtotal_ht = 0; - $subtotal_ttc = 0; - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($result); - - $total_ht += $obj->amount; - $total_ttc += $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; - - print ' '; - - print "".$langs->trans("Donation")." name."&search_name=".$obj->firstname." ".$obj->lastname."\">".$obj->name." ".$obj->firstname." ".$obj->lastname."\n"; - - if ($modecompta == 'CREANCES-DETTES') print ''.price($obj->amount).''; - print ''.price($obj->amount).''; - print ''; - $i++; - } - } else { - print ' '; - print ''.$langs->trans("None").''; - print ''; - } - } else { - dol_print_error($db); - } - print ''; - if ($modecompta == 'CREANCES-DETTES') - print ''.price($subtotal_ht).''; - print ''.price($subtotal_ttc).''; - print ''; - } /* * Various Payments */ + //$conf->global->ACCOUNTING_REPORTS_INCLUDE_VARPAY = 1; if (!empty($conf->global->ACCOUNTING_REPORTS_INCLUDE_VARPAY) && !empty($conf->banque->enabled) && ($modecompta == 'CREANCES-DETTES' || $modecompta == "RECETTES-DEPENSES")) { @@ -953,12 +957,14 @@ if ($modecompta == 'BOOKKEEPING') $result = $db->query($sql); if ($result) { - // Debit + // Debit (payment of suppliers for example) $obj = $db->fetch_object($result); if (isset($obj->amount)) { $subtotal_ht += -$obj->amount; $subtotal_ttc += -$obj->amount; + $total_ht_outcome += $obj->amount; + $total_ttc_outcome += $obj->amount; } print ' '; print "".$langs->trans("Debit")."\n"; @@ -966,12 +972,14 @@ if ($modecompta == 'BOOKKEEPING') print ''.price(-$obj->amount)."\n"; print "\n"; - // Credit + // Credit (payment received from customer for example) $obj = $db->fetch_object($result); if (isset($obj->amount)) { $subtotal_ht += $obj->amount; $subtotal_ttc += $obj->amount; + $total_ht_income += $obj->amount; + $total_ttc_income += $obj->amount; } print ' '; print "".$langs->trans("Credit")."\n"; @@ -1030,6 +1038,8 @@ if ($modecompta == 'BOOKKEEPING') } $total_ht += $subtotal_ht; $total_ttc += $subtotal_ttc; + $total_ht_income += $subtotal_ht; + $total_ttc_income += $subtotal_ttc; print ''; if ($modecompta == 'CREANCES-DETTES') print ''.price($subtotal_ht).''; @@ -1050,7 +1060,7 @@ if ($modecompta == 'BOOKKEEPING') { if ($modecompta == 'CREANCES-DETTES') { - // TVA a payer + // VAT to pay $amount = 0; $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.tva) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; @@ -1091,13 +1101,15 @@ if ($modecompta == 'BOOKKEEPING') } else { dol_print_error($db); } + $total_ht_outcome -= 0; + $total_ttc_outcome -= $amount; print ' '; print "".$langs->trans("VATToPay")."\n"; print ' '."\n"; print ''.price($amount)."\n"; print "\n"; - // TVA a recuperer + // VAT to retreive $amount = 0; $sql = "SELECT date_format(f.datef,'%Y-%m') as dm, sum(f.total_tva) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; @@ -1139,6 +1151,9 @@ if ($modecompta == 'BOOKKEEPING') } else { dol_print_error($db); } + $total_ht_income += 0; + $total_ttc_income += $amount; + print ' '; print ''.$langs->trans("VATToCollect")."\n"; print ' '."\n"; @@ -1182,10 +1197,12 @@ if ($modecompta == 'BOOKKEEPING') } else { dol_print_error($db); } + $total_ht_outcome -= 0; + $total_ttc_outcome -= $amount; print ' '; print "".$langs->trans("VATPaid")."\n"; if ($modecompta == 'CREANCES-DETTES') - print ''.price($amount)."\n"; + print ''."\n"; print ''.price($amount)."\n"; print "\n"; @@ -1226,16 +1243,18 @@ if ($modecompta == 'BOOKKEEPING') } else { dol_print_error($db); } + $total_ht_income += 0; + $total_ttc_income += $amount; print ' '; print "".$langs->trans("VATCollected")."\n"; if ($modecompta == 'CREANCES-DETTES') - print ''.price($amount)."\n"; + print ''."\n"; print ''.price($amount)."\n"; print "\n"; } } - if ($mysoc->tva_assuj != 'franchise') // Assujetti + if ($mysoc->tva_assuj != '0') // Assujetti { print ''; if ($modecompta == 'CREANCES-DETTES') @@ -1250,25 +1269,31 @@ $object = array(&$total_ht, &$total_ttc); $parameters["mode"] = $modecompta; $parameters["date_start"] = $date_start; $parameters["date_end"] = $date_end; -$parameters["bc"] = $bc; // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('externalbalance')); $reshook = $hookmanager->executeHooks('addBalanceLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks print $hookmanager->resPrint; -if ($mysoc->tva_assuj != 'franchise') // Assujetti -{ - // Total - print ''; - print ' '; - print ''; +// Total +print ''; +print ' '; +print ''; - print ''.$langs->trans("Profit").''; - if ($modecompta == 'CREANCES-DETTES') - print ''.price(price2num($total_ht, 'MT')).''; - print ''.price(price2num($total_ttc, 'MT')).''; - print ''; -} +print ''.$langs->trans("Outcome").''; +if ($modecompta == 'CREANCES-DETTES') + print ''.price(price2num(-$total_ht_outcome, 'MT')).''; +print ''.price(price2num(-$total_ttc_outcome, 'MT')).''; +print ''; +print ''.$langs->trans("Income").''; +if ($modecompta == 'CREANCES-DETTES') + print ''.price(price2num($total_ht_income, 'MT')).''; +print ''.price(price2num($total_ttc_income, 'MT')).''; +print ''; +print ''.$langs->trans("Profit").''; +if ($modecompta == 'CREANCES-DETTES') + print ''.price(price2num($total_ht, 'MT')).''; +print ''.price(price2num($total_ttc, 'MT')).''; +print ''; print ""; print '
'; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 2ea2497efbb..ffb2d04e155 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -512,13 +512,13 @@ class ChargeSociales extends CommonObject * Return a link to the object card (with optionaly the picto) * * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param int $maxlen Max length of label + * @param string $option On what the link point to ('nolink', ...) * @param int $notooltip 1=Disable tooltip * @param int $short 1=Return just URL * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string String with link */ - public function getNomUrl($withpicto = 0, $maxlen = 0, $notooltip = 0, $short = 0, $save_lastsearch_value = -1) + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $short = 0, $save_lastsearch_value = -1) { global $langs, $conf, $user, $form; @@ -569,7 +569,7 @@ class ChargeSociales extends CommonObject $result .= $linkstart; if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref); + if ($withpicto != 2) $result .= $this->ref; $result .= $linkend; return $result; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 752bdc4d642..23297438e19 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -1129,13 +1129,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Note Public print ''; - $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); print ''; // Note Private print ''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); print ''; diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 2e692dc25c4..3ed21f03873 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -1174,14 +1174,14 @@ if ($action == 'create') } print ''.$langs->trans("NotePublic").''; - $doleditor = new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); print ''; if (empty($user->socid)) { print ''.$langs->trans("NotePrivate").''; - $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); print ''; } diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index bd5b39f717b..72a8ec2974d 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -131,14 +131,8 @@ $arrayfields = array( 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); @@ -208,7 +202,7 @@ $contracttmp = new Contrat($db); $sql = 'SELECT'; $sql .= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; -$sql .= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql .= ' s.rowid as socid, s.nom as name, s.name_alias, s.email, s.town, s.zip, s.fk_pays as country_id, s.client, s.code_client, s.status as company_status, s.logo as company_logo,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") as lower_planned_end_date,"; @@ -263,7 +257,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; -$sql .= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; +$sql .= ' s.rowid, s.nom, s.name_alias, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, s.status, s.logo,'; $sql .= " typent.code,"; $sql .= " state.code_departement, state.nom"; // Add fields from extrafields @@ -341,7 +335,7 @@ if ($socid > 0) $param = ''; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($sall != '') $param .= '&sall='.urlencode($sall); if ($search_contract != '') $param .= '&search_contract='.urlencode($search_contract); if ($search_name != '') $param .= '&search_name='.urlencode($search_name); @@ -596,6 +590,10 @@ if (!empty($arrayfields['status']['checked'])) { print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; +$totalarray = array(); +$typenArray = array(); +$cacheCountryIDCode = array(); + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -608,6 +606,24 @@ while ($i < min($num, $limit)) if ($obj->socid > 0) { $result = $socstatic->fetch($obj->socid); } + /*$socstatic->id = $obj->socid; + $socstatic->name = $obj->name; + $socstatic->name_alias = $obj->name_alias; + $socstatic->email = $obj->email; + $socstatic->status = $obj->company_status; + $socstatic->logo = $obj->logo; + $socstatic->country_id = $obj->country_id; + $socstatic->country_code = ''; + $socstatic->country = '';*/ + if ($obj->country_id > 0) { + if (!isset($cacheCountryIDCode[$obj->country_id]['code'])) { + $tmparray = getCountry($obj->country_id, 'all'); + $cacheCountryIDCode[$obj->country_id] = array('code'=> empty($tmparray['code']) ? '' : $tmparray['code'], 'label' => empty($tmparray['label']) ? '' : $tmparray['label']); + } + $socstatic->country_code = $cacheCountryIDCode[$obj->country_id]['code']; + $socstatic->country = $cacheCountryIDCode[$obj->country_id]['label']; + } + print ''; @@ -643,9 +659,8 @@ while ($i < min($num, $limit)) if (!empty($arrayfields['s.nom']['checked'])) { print ''; - //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { + // TODO Use a cache for this string print $socstatic->getNomUrl(1, ''); } print ''; @@ -680,8 +695,7 @@ while ($i < min($num, $limit)) if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - $tmparray = getCountry($obj->fk_pays, 'all'); - print $tmparray['label']; + print $socstatic->country; print ''; if (!$i) $totalarray['nbfield']++; } diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 67b605d657f..4de651a24f9 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -130,14 +130,8 @@ $arrayfields = array( 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) ); // 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])); - } -} +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 5a93a6ded0b..1c874fd2418 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -261,7 +261,7 @@ if ($action == 'confirm_delete' && !empty($permissiontodelete)) // Remove a line if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) { - if (method_exists('deleteline', $object)) { + if (method_exists($object, 'deleteline')) { $result = $object->deleteline($user, $lineid); // For backward compatibility } else { $result = $object->deleteLine($user, $lineid); diff --git a/htdocs/core/boxes/box_funnel_of_prospection.php b/htdocs/core/boxes/box_funnel_of_prospection.php index 6ffce6d781b..5b6130d8eb2 100644 --- a/htdocs/core/boxes/box_funnel_of_prospection.php +++ b/htdocs/core/boxes/box_funnel_of_prospection.php @@ -61,9 +61,9 @@ class box_funnel_of_prospection extends ModeleBoxes $this->db = $db; - $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL >= 1); // Not enabled by default, still need some work + $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL >= 1 ? 1 : 0); // Not enabled by default, still need some work - $this->hidden = !($user->rights->projet->lire); + $this->hidden = empty($user->rights->projet->lire); } /** diff --git a/htdocs/core/boxes/box_scheduled_jobs.php b/htdocs/core/boxes/box_scheduled_jobs.php index 81e73f4e0c1..2ac81c80d16 100644 --- a/htdocs/core/boxes/box_scheduled_jobs.php +++ b/htdocs/core/boxes/box_scheduled_jobs.php @@ -71,7 +71,7 @@ class box_scheduled_jobs extends ModeleBoxes */ public function loadBox($max = 5) { - global $user, $langs, $conf; + global $user, $langs, $conf, $form; $langs->load("cron"); $this->info_box_head = array('text' => $langs->trans("BoxScheduledJobs", $max)); @@ -117,7 +117,7 @@ class box_scheduled_jobs extends ModeleBoxes $cronstatic->getNomUrl(1), $cronstatic->datelastrun, $cronstatic->status, - $cronstatic->getLibStatut(2) + $cronstatic->getLibStatut(3) ); $line++; } @@ -135,37 +135,37 @@ class box_scheduled_jobs extends ModeleBoxes $cronstatic->getNomUrl(1), $cronstatic->datenextrun, $cronstatic->status, - $cronstatic->getLibStatut(2) + $cronstatic->getLibStatut(3) ); } foreach ($resultarray as $line => $value) { $this->info_box_contents[$line][] = array( - 'td' => 'class="left"', + 'td' => 'class="tdoverflowmax200"', 'text' => $resultarray[$line][0] ); $this->info_box_contents[$line][] = array( - 'td' => 'class="left"', + 'td' => 'class="nowraponall"', 'textnoformat' => $resultarray[$line][1] ); $this->info_box_contents[$line][] = array( 'td' => 'class="right"', - 'textnoformat' => dol_print_date($resultarray[$line][2], "dayhoursec") + 'textnoformat' => (empty($resultarray[$line][2]) ? '' : $form->textwithpicto(dol_print_date($resultarray[$line][2], "dayhoursec"), $langs->trans("CurrentTimeZone"))) ); $this->info_box_contents[$line][] = array( - 'td' => 'class="right" ', + 'td' => 'class="center" ', 'textnoformat' => $resultarray[$line][4] ); $line++; } $this->info_box_contents[$line][] = array( - 'td' => 'class="left" colspan="2"', + 'td' => 'class="tdoverflowmax300" colspan="3"', 'text' => $langs->trans("NumberScheduledJobError") ); $this->info_box_contents[$line][] = array( - 'td' => 'class="right" colspan="2"', - 'textnoformat' => ($nbjobsinerror ? ''.$nbjobsinerror.''.img_error() : ''.$langs->trans("None").'') + 'td' => 'class="center"', + 'textnoformat' => ($nbjobsinerror ? '
'.$nbjobsinerror.'
' : '
0
') ); } else { $this->info_box_contents[0][0] = array( diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 1e32a28f25c..9faf45932e2 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -56,7 +56,7 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box /** * @var boolean Condition to have widget visible (in most cases, permissions) */ - public $hidden = 0; + public $hidden = false; /** * @var int Box definition database ID diff --git a/htdocs/core/class/ccountry.class.php b/htdocs/core/class/ccountry.class.php index d19e6d00a36..561d0527796 100644 --- a/htdocs/core/class/ccountry.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -162,9 +162,9 @@ class Ccountry // extends CommonObject $sql .= " t.label,"; $sql .= " t.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_country as t"; - if ($id) $sql .= " WHERE t.rowid = ".$id; - elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'"; - elseif ($code_iso) $sql .= " WHERE t.code_iso = '".$this->db->escape($code_iso)."'"; + if ($id) $sql .= " WHERE t.rowid = ".((int) $id); + elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape(strtoupper($code))."'"; + elseif ($code_iso) $sql .= " WHERE t.code_iso = '".$this->db->escape(strtoupper($code_iso))."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -174,11 +174,13 @@ class Ccountry // extends CommonObject { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->code = $obj->code; - $this->code_iso = $obj->code_iso; - $this->label = $obj->label; - $this->active = $obj->active; + if ($obj) { + $this->id = $obj->rowid; + $this->code = $obj->code; + $this->code_iso = $obj->code_iso; + $this->label = $obj->label; + $this->active = $obj->active; + } $this->db->free($resql); return 1; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index b095712d972..de4f2bc367c 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -210,6 +210,11 @@ abstract class CommonObject */ public $ref_next; + /** + * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object + */ + public $newref; + /** * @var int The object's status * @see setStatut() @@ -350,7 +355,7 @@ abstract class CommonObject public $last_main_doc; /** - * @var int Bank account ID + * @var int Bank account ID sometimes, ID of record into llx_bank sometimes * @deprecated * @see $fk_account */ @@ -2949,18 +2954,25 @@ abstract class CommonObject // Special cas if ($this->table_element == 'product' && $newsuffix == '_private') $newsuffix = ''; - + if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) { + $fieldusermod = "fk_user_mod"; + } elseif ($this->table_element == 'ecm_files') { + $fieldusermod = "fk_user_m"; + } else { + $fieldusermod = "fk_user_modif"; + } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL"); - $sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id; + $sql .= " ,".$fieldusermod." = ".$user->id; $sql .= " WHERE rowid =".$this->id; dol_syslog(get_class($this)."::update_note", LOG_DEBUG); - if ($this->db->query($sql)) - { - if ($suffix == '_public') $this->note_public = $note; - elseif ($suffix == '_private') $this->note_private = $note; - else { + if ($this->db->query($sql)) { + if ($suffix == '_public') { + $this->note_public = $note; + } elseif ($suffix == '_private') { + $this->note_private = $note; + } else { $this->note = $note; // deprecated $this->note_private = $note; } @@ -3287,7 +3299,7 @@ abstract class CommonObject /** * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into - * this->linkedObjectsIds array and + * this->linkedObjectsIds array + * this->linkedObjects array if $loadalsoobjects = 1 * Possible usage for parameters: * - all parameters empty -> we look all link to current object (current object can be source or target) @@ -3400,6 +3412,7 @@ abstract class CommonObject { // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) $module = $element = $subelement = $objecttype; + $regs = array(); if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) { @@ -7154,20 +7167,20 @@ abstract class CommonObject $dir = $sdir.'/'; $pdir = '/'; - $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; - $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; + $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart); + $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart); // For backward compatibility - if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - { - $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; - $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; + if ($modulepart == 'product') { + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { + $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; + $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/"; + } } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; - if ($dir) - { + if ($dir) { $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir); $relativedir = preg_replace('/^[\\/]/', '', $relativedir); $relativedir = preg_replace('/[\\/]$/', '', $relativedir); @@ -7189,23 +7202,19 @@ abstract class CommonObject completeFileArrayWithDatabaseInfo($filearray, $relativedir); - if (count($filearray)) - { - if ($sortfield && $sortorder) - { + if (count($filearray)) { + if ($sortfield && $sortorder) { $filearray = dol_sort_array($filearray, $sortfield, $sortorder); } - foreach ($filearray as $key => $val) - { + foreach ($filearray as $key => $val) { $photo = ''; $file = $val['name']; //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) - if (image_format_supported($file) >= 0) - { + if (image_format_supported($file) >= 0) { $nbphoto++; $photo = $file; $viewfilename = $file; @@ -7242,12 +7251,9 @@ abstract class CommonObject $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height']; if ($notitle) $alt = ''; - if ($usesharelink) - { - if ($val['share']) - { - if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) - { + if ($usesharelink) { + if ($val['share']) { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) { $return .= ''; $return .= ''; } else { @@ -7259,10 +7265,9 @@ abstract class CommonObject $return .= ''; } } else { - if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) - { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) { $return .= ''; - $return .= ''; + $return .= ''; } else { $return .= ''; $return .= ''; diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 09f2b0a44ae..a1800e03980 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -52,9 +52,11 @@ class Conf public $disable_compute; //! Used to store current currency (ISO code like 'USD', 'EUR', ...) public $currency; + //! Used to store current css (from theme) public $theme; // Contains current theme ("eldy", "auguria", ...) public $css; // Contains full path of css page ("/theme/eldy/style.css.php", ...) + //! Used to store current menu handler public $standard_menu; // List of activated modules @@ -98,6 +100,8 @@ class Conf public $dol_no_mouse_hover; // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url + public $liste_limit; + /** * Constructor diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 36638be33c1..5fcc7b00c91 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -891,7 +891,6 @@ class DolGraph $color1 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[0], $this->bgcolorgrid[2]); $color2 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]); $this->stringtoshow .= ', grid: { hoverable: true, backgroundColor: { colors: ["#' . $color1 . '", "#' . $color2 . '"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor : \'#e6e6e6\' }' . "\n"; - //$this->stringtoshow.=', shadowSize: 20'."\n"; TODO Uncommet this $this->stringtoshow .= '});' . "\n"; $this->stringtoshow .= '}' . "\n"; } @@ -1215,6 +1214,7 @@ class DolGraph } else { $textoflegend = $this->Legend[$i]; } + if ($usecolorvariantforgroupby) { $newcolor = $this->datacolor[$arrayofgroupslegend[$i]['stacknum']]; // If we change the stack @@ -1243,6 +1243,7 @@ class DolGraph $bordercolor = 'rgb(' . $newcolor[0] . ', ' . $newcolor[1] . ', ' . $newcolor[2] . ')'; } else { // We do not use a 'group by' if ($isfunnel) { + $bordercolor == 'null'; if (is_array($this->datacolor[$i])) { $color = 'rgb(' . $this->datacolor[$i][0] . ', ' . $this->datacolor[$i][1] . ', ' . $this->datacolor[$i][2] . ', 0.9)'; // If datacolor is array(R, G, B) } else { @@ -1262,9 +1263,9 @@ class DolGraph if (strpos($tmp, '-') !== false) $bordercolor = '#' . str_replace('-', '', $tmp); // If $val is '-123' else $bordercolor = 'null'; // If $val is '123' or '#123' } - $bordercolor == 'null' ? "'rgba(0,0,0,0.2)'" : "'" . $bordercolor . "'"; } } + $bordercolor == 'null' ? "'rgba(0,0,0,0.2)'" : "'" . $bordercolor . "'"; } else { $color = 'rgb('.$this->datacolor[$i][0].', '.$this->datacolor[$i][1].', '.$this->datacolor[$i][2].', 0.9)'; $bordercolor = $color; diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index d041aba45f4..2daf4c835e9 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -991,32 +991,23 @@ class ExtraFields else return ''; } - if (empty($morecss)) - { - if ($type == 'date') - { + if (empty($morecss)) { + if ($type == 'date') { $morecss = 'minwidth100imp'; - } elseif ($type == 'datetime' || $type == 'link') - { + } elseif ($type == 'datetime' || $type == 'link') { $morecss = 'minwidth200imp'; - } elseif (in_array($type, array('int', 'integer', 'double', 'price'))) - { + } elseif (in_array($type, array('int', 'integer', 'double', 'price'))) { $morecss = 'maxwidth75'; - } elseif ($type == 'password') - { + } elseif ($type == 'password') { $morecss = 'maxwidth100'; - } elseif ($type == 'url') - { + } elseif ($type == 'url') { $morecss = 'minwidth400'; - } elseif ($type == 'boolean') - { + } elseif ($type == 'boolean') { $morecss = ''; } else { - if (round($size) < 12) - { + if (empty($size) || round($size) < 12) { $morecss = 'minwidth100'; - } elseif (round($size) <= 48) - { + } elseif (round($size) <= 48) { $morecss = 'minwidth200'; } else { $morecss = 'minwidth400'; @@ -1024,8 +1015,7 @@ class ExtraFields } } - if (in_array($type, array('date', 'datetime'))) - { + if (in_array($type, array('date', 'datetime'))) { $tmp = explode(',', $size); $newsize = $tmp[0]; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index fdcdc89e53e..492a4899376 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -3611,15 +3611,14 @@ class Form * * @param string $selected Id pre-selectionne * @param string $htmlname Nom de la zone select + * @param string $addjscombo Add js combo * @return string Code of HTML select to chose tax or not */ - public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type') + public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0) { global $langs; - $return = ''; - - $return .= ''; $options = array( 'HT'=>$langs->trans("HT"), 'TTC'=>$langs->trans("TTC") @@ -3635,6 +3634,7 @@ class Form $return .= ''; } $return .= ''; + if ($addjscombo) $return .= ajax_combobox('select_'.$htmlname); return $return; } @@ -3939,13 +3939,16 @@ class Form * @param string $moreattrib To add more attribute on select * @param int $showcurrency Show currency in label * @param string $morecss More CSS + * @param int $nooutput 1=Return string, do not send to output * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...) */ - public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '') + public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0) { // phpcs:enable global $langs, $conf; + $out = ''; + $langs->load("admin"); $num = 0; @@ -3964,10 +3967,10 @@ class Form $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { - print ''; + $out .= ''; } while ($i < $num) @@ -3975,26 +3978,30 @@ class Form $obj = $this->db->fetch_object($result); if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) { - print ''; + $out .= trim($obj->label); + if ($showcurrency) $out .= ' ('.$obj->currency_code.')'; + if ($status == 2 && $obj->status == 1) $out .= ' ('.$langs->trans("Closed").')'; + $out .= ''; $i++; } - print ""; - print ajax_combobox('select'.$htmlname); + $out .= ""; + $out .= ajax_combobox('select'.$htmlname); } else { - if ($status == 0) print ''.$langs->trans("NoActiveBankAccountDefined").''; - else print ''.$langs->trans("NoBankAccountFound").''; + if ($status == 0) $out .= ''.$langs->trans("NoActiveBankAccountDefined").''; + else $out .= ''.$langs->trans("NoBankAccountFound").''; } } else { dol_print_error($this->db); } + // Output or return + if (empty($nooutput)) print $out; + else return $out; + return $num; } @@ -4709,7 +4716,7 @@ class Form $ret .= ''; $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0); $ret .= ''; - $ret .= ''; + $ret .= ''; $ret .= ''; } else { if ($displayhour) $ret .= dol_print_date($selected, 'dayhour'); @@ -6259,12 +6266,6 @@ class Form $resql = $this->db->query($sql); if ($resql) { - if (!$forcecombo) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode); - } - // Construct $out and $outarray $out .= ''."\n"; + + if (!$forcecombo) { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode); + } } else { dol_print_error($this->db); } diff --git a/htdocs/core/class/html.formcompany.class.php b/htdocs/core/class/html.formcompany.class.php index 0b4c4e499e3..26e184eb614 100644 --- a/htdocs/core/class/html.formcompany.class.php +++ b/htdocs/core/class/html.formcompany.class.php @@ -1008,4 +1008,44 @@ class FormCompany extends Form return $out; } + + /** + * Output html select to select third-party type + * + * @param string $page Page + * @param string $selected Id preselected + * @param string $htmlname Name of HTML select + * @param string $filter optional filters criteras + * @param int $nooutput No print output. Return it only. + * @return void|string + */ + public function formThirdpartyType($page, $selected = '', $htmlname = 'socid', $filter = '', $nooutput = 0) + { + // phpcs:enable + global $langs; + + $out = ''; + if ($htmlname != "none") + { + $out .= '
'; + $out .= ''; + $out .= ''; + $sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. + $out .= $this->selectarray($htmlname, $this->typent_array(0, $filter), $selected, 0, 0, 0, '', 0, 0, 0, $sortparam, '', 1); + $out .= ''; + $out .= '
'; + } else { + if ($selected) + { + $arr = $this->typent_array(0); + $typent = $arr[$selected]; + $out .= $typent; + } else { + $out .= " "; + } + } + + if ($nooutput) return $out; + else print $out; + } } diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 437cef27afc..6836b70fe2d 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -1254,7 +1254,7 @@ class FormFile } else { print ''; } - print ''; + print ''; print ''; } else print ' '; print ''; @@ -1779,7 +1779,7 @@ class FormFile print ''."\n"; // Show list of associated links - print load_fiche_titre($langs->trans("LinkedFiles"), '', 'external-link-square-alt', 0, '', 'table-list-of-links'); + print load_fiche_titre($langs->trans("LinkedFiles"), '', 'link', 0, '', 'table-list-of-links'); print '
'; print ''; @@ -1913,11 +1913,12 @@ class FormFile { $out .= ''; //$out.= ''; - if (empty($ruleforpicto)) - { + if (empty($ruleforpicto)) { //$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); $out .= ''; - } else $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); + } else { + $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); + } $out .= ''; } } diff --git a/htdocs/core/class/html.formwebsite.class.php b/htdocs/core/class/html.formwebsite.class.php index 0f3e9a357b8..8cbb7967415 100644 --- a/htdocs/core/class/html.formwebsite.class.php +++ b/htdocs/core/class/html.formwebsite.class.php @@ -107,9 +107,10 @@ class FormWebsite * @param string $selected Selected value * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. * @param string $moreattrib More attributes on HTML select tag + * @param int $addjscombo Add js combo * @return void */ - public function selectTypeOfContainer($htmlname, $selected = '', $useempty = 0, $moreattrib = '') + public function selectTypeOfContainer($htmlname, $selected = '', $useempty = 0, $moreattrib = '', $addjscombo = 0) { global $langs, $conf, $user; @@ -128,7 +129,7 @@ class FormWebsite $i = 0; if ($num) { - print ''; if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; @@ -149,6 +150,10 @@ class FormWebsite } print ""; if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + + if ($addjscombo) { + print ajax_combobox('select'.$htmlname); + } } else { print $langs->trans("NoTypeOfPagePleaseEditDictionary"); } @@ -165,9 +170,10 @@ class FormWebsite * @param string $selected Selected value * @param int $useempty 1=Add an empty value in list * @param string $moreattrib More attributes on HTML select tag + * @param int $addjscombo Add js combo * @return string HTML select component with list of type of containers */ - public function selectSampleOfContainer($htmlname, $selected = '', $useempty = 0, $moreattrib = '') + public function selectSampleOfContainer($htmlname, $selected = '', $useempty = 0, $moreattrib = '', $addjscombo = 0) { global $langs, $conf, $user; @@ -190,7 +196,7 @@ class FormWebsite } $out = ''; - $out .= ''; if ($useempty == 1 || $useempty == 2) { @@ -210,6 +216,10 @@ class FormWebsite } $out .= ""; + if ($addjscombo) { + $out .= ajax_combobox('select'.$htmlname); + } + return $out; } diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index 7cc51bfecb9..f9f1c3b99ef 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -112,26 +112,40 @@ class Notify $listofnotiftodo = $this->getNotificationsArray($action, $socid, $object, 0); + $texte = ''; $nb = -1; - if (is_array($listofnotiftodo)) $nb = count($listofnotiftodo); - if ($nb < 0) $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ErrorFailedToGetListOfNotificationsToSend"); - if ($nb == 0) $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("NoNotificationsWillBeSent"); - if ($nb == 1) $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ANotificationsWillBeSent"); - if ($nb >= 2) $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("SomeNotificationsWillBeSent", $nb); + if (is_array($listofnotiftodo)) { + $nb = count($listofnotiftodo); + } + if ($nb < 0) { + $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ErrorFailedToGetListOfNotificationsToSend"); + } elseif ($nb == 0) { + $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("NoNotificationsWillBeSent"); + } elseif ($nb == 1) { + $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ANotificationsWillBeSent"); + } elseif ($nb >= 2) { + $texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("SomeNotificationsWillBeSent", $nb); + } - if (is_array($listofnotiftodo)) - { + if (is_array($listofnotiftodo)) { $i = 0; - foreach ($listofnotiftodo as $key => $val) - { - if ($i) $texte .= ', '; - else $texte .= ' ('; - if ($val['isemailvalid']) $texte .= $val['email']; - else $texte .= $val['emaildesc']; + foreach ($listofnotiftodo as $key => $val) { + if ($i) { + $texte .= ', '; + } else { + $texte .= ' ('; + } + if ($val['isemailvalid']) { + $texte .= $val['email']; + } else { + $texte .= $val['emaildesc']; + } $i++; } - if ($i) $texte .= ')'; - } + if ($i) { + $texte .= ')'; + } + } return $texte; } @@ -154,12 +168,21 @@ class Notify $resarray = array(); $valueforthreshold = 0; - if (is_object($object)) $valueforthreshold = $object->total_ht; + if (is_object($object)) { + $valueforthreshold = $object->total_ht; + } - if (!$error) - { - if ($socid >= 0 && in_array('thirdparty', $scope)) - { + $sqlnotifcode = ''; + if ($notifcode) { + if (is_numeric($notifcode)) { + $sqlnotifcode = " AND n.fk_action = ".$notifcode; // Old usage + } else { + $sqlnotifcode = " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage + } + } + + if (!$error) { + if ($socid >= 0 && in_array('thirdparty', $scope)) { $sql = "SELECT a.code, c.email, c.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; $sql .= " ".MAIN_DB_PREFIX."socpeople as c,"; @@ -168,29 +191,26 @@ class Notify $sql .= " WHERE n.fk_contact = c.rowid"; $sql .= " AND a.rowid = n.fk_action"; $sql .= " AND n.fk_soc = s.rowid"; - if ($notifcode) - { - if (is_numeric($notifcode)) $sql .= " AND n.fk_action = ".$notifcode; // Old usage - else $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage - } + $sql .= $sqlnotifcode; $sql .= " AND s.entity IN (".getEntity('societe').")"; - if ($socid > 0) $sql .= " AND s.rowid = ".$socid; + if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; + } dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $newval2 = trim($obj->email); $isvalid = isValidEmail($newval2); - if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'tocontact', 'code'=>trim($obj->code), 'emaildesc'=>'Contact id '.$obj->rowid, 'email'=>$newval2, 'contactid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + if (empty($resarray[$newval2])) { + $resarray[$newval2] = array('type'=> 'tocontact', 'code'=>trim($obj->code), 'emaildesc'=>'Contact id '.$obj->rowid, 'email'=>$newval2, 'contactid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + } } $i++; } @@ -201,39 +221,34 @@ class Notify } } - if (!$error) - { - if ($userid >= 0 && in_array('user', $scope)) - { + if (!$error) { + if ($userid >= 0 && in_array('user', $scope)) { $sql = "SELECT a.code, c.email, c.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; $sql .= " ".MAIN_DB_PREFIX."user as c,"; $sql .= " ".MAIN_DB_PREFIX."c_action_trigger as a"; $sql .= " WHERE n.fk_user = c.rowid"; $sql .= " AND a.rowid = n.fk_action"; - if ($notifcode) - { - if (is_numeric($notifcode)) $sql .= " AND n.fk_action = ".$notifcode; // Old usage - else $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage - } + $sql .= $sqlnotifcode; $sql .= " AND c.entity IN (".getEntity('user').")"; - if ($userid > 0) $sql .= " AND c.rowid = ".$userid; + if ($userid > 0) { + $sql .= " AND c.rowid = ".$userid; + } dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $newval2 = trim($obj->email); $isvalid = isValidEmail($newval2); - if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'touser', 'code'=>trim($obj->code), 'emaildesc'=>'User id '.$obj->rowid, 'email'=>$newval2, 'userid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + if (empty($resarray[$newval2])) { + $resarray[$newval2] = array('type'=> 'touser', 'code'=>trim($obj->code), 'emaildesc'=>'User id '.$obj->rowid, 'email'=>$newval2, 'userid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + } } $i++; } @@ -244,48 +259,55 @@ class Notify } } - if (!$error) - { - if (in_array('global', $scope)) - { + if (!$error) { + if (in_array('global', $scope)) { // List of notifications enabled for fixed email - foreach ($conf->global as $key => $val) - { - if ($notifcode) - { - if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + foreach ($conf->global as $key => $val) { + if ($notifcode) { + if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) { + continue; + } } else { - if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_.*_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_.*_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) { + continue; + } } $threshold = (float) $reg[1]; - if ($valueforthreshold < $threshold) continue; + if ($valueforthreshold < $threshold) { + continue; + } $tmpemail = explode(',', $val); - foreach ($tmpemail as $key2 => $val2) - { + foreach ($tmpemail as $key2 => $val2) { $newval2 = trim($val2); - if ($newval2 == '__SUPERVISOREMAIL__') - { - if ($user->fk_user > 0) - { + if ($newval2 == '__SUPERVISOREMAIL__') { + if ($user->fk_user > 0) { $tmpuser = new User($this->db); $tmpuser->fetch($user->fk_user); - if ($tmpuser->email) $newval2 = trim($tmpuser->email); - else $newval2 = ''; - } else $newval2 = ''; + if ($tmpuser->email) { + $newval2 = trim($tmpuser->email); + } else { + $newval2 = ''; + } + } else { + $newval2 = ''; + } } - if ($newval2) - { + if ($newval2) { $isvalid = isValidEmail($newval2, 0); - if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'tofixedemail', 'code'=>trim($key), 'emaildesc'=>trim($val2), 'email'=>$newval2, 'isemailvalid'=>$isvalid); + if (empty($resarray[$newval2])) { + $resarray[$newval2] = array('type'=> 'tofixedemail', 'code'=>trim($key), 'emaildesc'=>trim($val2), 'email'=>$newval2, 'isemailvalid'=>$isvalid); + } } } } } } - if ($error) return -1; + if ($error) { + return -1; + } //var_dump($resarray); return $resarray; @@ -309,11 +331,12 @@ class Notify global $dolibarr_main_url_root; global $action; - if (!in_array($notifcode, $this->arrayofnotifsupported)) return 0; + if (!in_array($notifcode, $this->arrayofnotifsupported)) { + return 0; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (!is_object($hookmanager)) - { + if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } @@ -330,7 +353,9 @@ class Notify // Define some vars $application = 'Dolibarr'; - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $application = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $application = $conf->global->MAIN_APPLICATION_TITLE; + } $replyto = $conf->notification->email_from; $object_type = ''; $link = ''; @@ -343,8 +368,7 @@ class Notify $sql = ''; // Check notification per third party - if (!empty($object->socid) && $object->socid > 0) - { + if (!empty($object->socid) && $object->socid > 0) { $sql .= "SELECT 'tocontactid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.default_lang,"; $sql .= " a.rowid as adid, a.label, a.code, n.rowid, n.type"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c,"; @@ -354,8 +378,11 @@ class Notify $sql .= " WHERE n.fk_contact = c.rowid AND a.rowid = n.fk_action"; $sql .= " AND n.fk_soc = s.rowid"; $sql .= " AND c.statut = 1"; - if (is_numeric($notifcode)) $sql .= " AND n.fk_action = ".$notifcode; // Old usage - else $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage + if (is_numeric($notifcode)) { + $sql .= " AND n.fk_action = ".$notifcode; // Old usage + } else { + $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage + } $sql .= " AND s.rowid = ".$object->socid; $sql .= "\nUNION\n"; @@ -369,41 +396,42 @@ class Notify $sql .= " ".MAIN_DB_PREFIX."notify_def as n"; $sql .= " WHERE n.fk_user = c.rowid AND a.rowid = n.fk_action"; $sql .= " AND c.statut = 1"; - if (is_numeric($notifcode)) $sql .= " AND n.fk_action = ".$notifcode; // Old usage - else $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage + if (is_numeric($notifcode)) { + $sql .= " AND n.fk_action = ".$notifcode; // Old usage + } else { + $sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage + } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $projtitle = ''; - if (!empty($object->fk_project)) - { + if (!empty($object->fk_project)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $proj = new Project($this->db); $proj->fetch($object->fk_project); $projtitle = '('.$proj->title.')'; } - if ($num > 0) - { + if ($num > 0) { $i = 0; - while ($i < $num && !$error) // For each notification couple defined (third party/actioncode) - { + while ($i < $num && !$error) { // For each notification couple defined (third party/actioncode) $obj = $this->db->fetch_object($result); $sendto = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">"; $notifcodedefid = $obj->adid; $trackid = ''; - if ($obj->type_target == 'tocontactid') $trackid = 'con'.$obj->id; - if ($obj->type_target == 'touserid') $trackid = 'use'.$obj->id; + if ($obj->type_target == 'tocontactid') { + $trackid = 'con'.$obj->id; + } + if ($obj->type_target == 'touserid') { + $trackid = 'use'.$obj->id; + } - if (dol_strlen($obj->email)) - { + if (dol_strlen($obj->email)) { // Set output language $outputlangs = $langs; - if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) - { + if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) { $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($obj->default_lang); $outputlangs->loadLangs(array("main", "other")); @@ -511,8 +539,7 @@ class Notify } $ref = dol_sanitizeFileName($newref); $pdf_path = $dir_output."/".$ref."/".$ref.".pdf"; - if (!dol_is_file($pdf_path)) - { + if (!dol_is_file($pdf_path)) { // We can't add PDF as it is not generated yet. $filepdf = ''; } else { @@ -525,13 +552,18 @@ class Notify $message .= $mesg; $parameters = array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$filename_list, 'mimefile'=>$mimetype_list, 'filename'=>$mimefilename_list); - if (!isset($action)) $action = ''; + if (!isset($action)) { + $action = ''; + } $reshook = $hookmanager->executeHooks('formatNotificationMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (!empty($hookmanager->resArray['subject'])) $subject .= $hookmanager->resArray['subject']; - if (!empty($hookmanager->resArray['message'])) $message .= $hookmanager->resArray['message']; + if (empty($reshook)) { + if (!empty($hookmanager->resArray['subject'])) { + $subject .= $hookmanager->resArray['subject']; + } + if (!empty($hookmanager->resArray['message'])) { + $message .= $hookmanager->resArray['message']; + } } $mailfile = new CMailFile( @@ -553,17 +585,15 @@ class Notify 'notification' ); - if ($mailfile->sendfile()) - { + if ($mailfile->sendfile()) { if ($obj->type_target == 'touserid') { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_user, type, objet_type, type_target, objet_id, email)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_user, type, objet_type, type_target, objet_id, email)"; $sql .= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid ? $object->socid : 'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; } else { $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, type_target, objet_id, email)"; $sql .= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid ? $object->socid : 'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; } - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { dol_print_error($this->db); } } else { @@ -579,23 +609,22 @@ class Notify dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = ".(empty($object->socid) ? '' : $object->socid)); } } else { - $error++; + $error++; $this->errors[] = $this->db->lasterror(); dol_syslog("Failed to get list of notification to send ".$this->db->lasterror(), LOG_ERR); - return -1; + return -1; } // Check notification using fixed email - if (!$error) - { - foreach ($conf->global as $key => $val) - { + if (!$error) { + foreach ($conf->global as $key => $val) { $reg = array(); - if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) { + continue; + } $threshold = (float) $reg[1]; - if (!empty($object->total_ht) && $object->total_ht <= $threshold) - { + if (!empty($object->total_ht) && $object->total_ht <= $threshold) { dol_syslog("A notification is requested for notifcode = ".$notifcode." but amount = ".$object->total_ht." so lower than threshold = ".$threshold.". We discard this notification"); continue; } @@ -604,7 +633,9 @@ class Notify $sendto = $conf->global->$param; $notifcodedefid = dol_getIdFromCode($this->db, $notifcode, 'c_action_trigger', 'code', 'rowid'); - if ($notifcodedefid <= 0) dol_print_error($this->db, 'Failed to get id from code'); + if ($notifcodedefid <= 0) { + dol_print_error($this->db, 'Failed to get id from code'); + } $trackid = ''; $object_type = ''; @@ -721,8 +752,7 @@ class Notify } $ref = dol_sanitizeFileName($newref); $pdf_path = $dir_output."/".$ref."/".$ref.".pdf"; - if (!dol_is_file($pdf_path)) - { + if (!dol_is_file($pdf_path)) { // We can't add PDF as it is not generated yet. $filepdf = ''; } else { @@ -736,14 +766,14 @@ class Notify $message = nl2br($message); // Replace keyword __SUPERVISOREMAIL__ - if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) - { + if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) { $newval = ''; - if ($user->fk_user > 0) - { + if ($user->fk_user > 0) { $supervisoruser = new User($this->db); $supervisoruser->fetch($user->fk_user); - if ($supervisoruser->email) $newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); + if ($supervisoruser->email) { + $newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); + } } dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval); $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto); @@ -752,14 +782,16 @@ class Notify $sendto = preg_replace('/[\s,]+$/', '', $sendto); // Clean end of string } - if ($sendto) - { + if ($sendto) { $parameters = array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$filename_list, 'mimefile'=>$mimetype_list, 'filename'=>$mimefilename_list); $reshook = $hookmanager->executeHooks('formatNotificationMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (!empty($hookmanager->resArray['subject'])) $subject .= $hookmanager->resArray['subject']; - if (!empty($hookmanager->resArray['message'])) $message .= $hookmanager->resArray['message']; + if (empty($reshook)) { + if (!empty($hookmanager->resArray['subject'])) { + $subject .= $hookmanager->resArray['subject']; + } + if (!empty($hookmanager->resArray['message'])) { + $message .= $hookmanager->resArray['message']; + } } $mailfile = new CMailFile( $subject, @@ -780,12 +812,10 @@ class Notify 'notification' ); - if ($mailfile->sendfile()) - { + if ($mailfile->sendfile()) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, type_target, objet_type, objet_id, email)"; $sql .= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid ? $object->socid : 'null').", null, 'email', 'tofixedemail', '".$object_type."', ".$object->id.", '".$this->db->escape($conf->global->$param)."')"; - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { dol_print_error($this->db); } } else { @@ -796,7 +826,10 @@ class Notify } } - if (!$error) return $num; - else return -1 * $error; + if (!$error) { + return $num; + } else { + return -1 * $error; + } } } diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php index 3436a6d3c4f..07b67e30062 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -50,11 +50,11 @@ class Utils * Purge files into directory of data files. * CAN BE A CRON TASK * - * @param string $choice Choice of purge mode ('tempfiles', '' or 'tempfilesold' to purge temp older than $nbsecondsold seconds, 'allfiles', 'logfile') + * @param string $choices Choice of purge mode ('tempfiles', '' or 'tempfilesold' to purge temp older than $nbsecondsold seconds, 'allfiles', 'logfile') * @param int $nbsecondsold Nb of seconds old to accept deletion of a directory if $choice is 'tempfilesold' * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) */ - public function purgeFiles($choice = 'tempfilesold', $nbsecondsold = 86400) + public function purgeFiles($choices = 'tempfilesold,logfile', $nbsecondsold = 86400) { global $conf, $langs, $dolibarr_main_data_root; @@ -62,112 +62,117 @@ class Utils require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $filesarray = array(); - if (empty($choice)) $choice = 'tempfilesold'; + if (empty($choices)) $choices = 'tempfilesold,logfile'; - dol_syslog("Utils::purgeFiles choice=".$choice, LOG_DEBUG); - - if ($choice == 'tempfiles' || $choice == 'tempfilesold') - { - // Delete temporary files - if ($dolibarr_main_data_root) - { - $filesarray = dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1); // Do not follow symlinks - - if ($choice == 'tempfilesold') - { - $now = dol_now(); - foreach ($filesarray as $key => $val) - { - if ($val['date'] > ($now - ($nbsecondsold))) unset($filesarray[$key]); // Discard temp dir not older than $nbsecondsold - } - } - } - } - - if ($choice == 'allfiles') - { - // Delete all files (except install.lock, do not follow symbolic links) - if ($dolibarr_main_data_root) - { - $filesarray = dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); - } - } - - if ($choice == 'logfile') - { - // Define files log - if ($dolibarr_main_data_root) - { - $filesarray = dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); - } - - $filelog = ''; - if (!empty($conf->syslog->enabled)) - { - $filelog = $conf->global->SYSLOG_FILE; - $filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog); - - $alreadyincluded = false; - foreach ($filesarray as $tmpcursor) - { - if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded = true; } - } - if (!$alreadyincluded) $filesarray[] = array('fullname'=>$filelog, 'type'=>'file'); - } - } + dol_syslog("Utils::purgeFiles choice=".$choices, LOG_DEBUG); $count = 0; $countdeleted = 0; $counterror = 0; - if (count($filesarray)) - { - foreach ($filesarray as $key => $value) - { - //print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."
\n"; - if ($filesarray[$key]['type'] == 'dir') - { - $startcount = 0; - $tmpcountdeleted = 0; - $result = dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted); - $count += $result; - $countdeleted += $tmpcountdeleted; - } elseif ($filesarray[$key]['type'] == 'file') + $choicesarray = explode(',', $choices); + foreach ($choicesarray as $choice) { + $filesarray = array(); + + if ($choice == 'tempfiles' || $choice == 'tempfilesold') + { + // Delete temporary files + if ($dolibarr_main_data_root) { - // If (file that is not logfile) or (if mode is logfile) - if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile') + $filesarray = dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1); // Do not follow symlinks + + if ($choice == 'tempfilesold') { - $result = dol_delete_file($filesarray[$key]['fullname'], 1, 1); - if ($result) + $now = dol_now(); + foreach ($filesarray as $key => $val) { - $count++; - $countdeleted++; - } else { - $counterror++; + if ($val['date'] > ($now - ($nbsecondsold))) unset($filesarray[$key]); // Discard temp dir not older than $nbsecondsold } } } } - // Update cachenbofdoc - if (!empty($conf->ecm->enabled) && $choice == 'allfiles') + if ($choice == 'allfiles') { - require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; - $ecmdirstatic = new EcmDirectory($this->db); - $result = $ecmdirstatic->refreshcachenboffile(1); + // Delete all files (except install.lock, do not follow symbolic links) + if ($dolibarr_main_data_root) + { + $filesarray = dol_dir_list($dolibarr_main_data_root, "all", 0, '', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); + } + } + + if ($choice == 'logfile') + { + // Define files log + if ($dolibarr_main_data_root) + { + $filesarray = dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', 'install\.lock$', 'name', SORT_ASC, 0, 0, '', 1); + } + + $filelog = ''; + if (!empty($conf->syslog->enabled)) + { + $filelog = $conf->global->SYSLOG_FILE; + $filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog); + + $alreadyincluded = false; + foreach ($filesarray as $tmpcursor) + { + if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded = true; } + } + if (!$alreadyincluded) $filesarray[] = array('fullname'=>$filelog, 'type'=>'file'); + } + } + + if (is_array($filesarray) && count($filesarray)) { + foreach ($filesarray as $key => $value) + { + //print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."
\n"; + if ($filesarray[$key]['type'] == 'dir') { + $startcount = 0; + $tmpcountdeleted = 0; + + $result = dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted); + + if (!in_array($filesarray[$key]['fullname'], array($conf->api->dir_temp, $conf->user->dir_temp))) { // The 2 directories $conf->api->dir_temp and $conf->user->dir_temp are recreated at end, so we do not count them + $count += $result; + $countdeleted += $tmpcountdeleted; + } + } elseif ($filesarray[$key]['type'] == 'file') { + // If (file that is not logfile) or (if mode is logfile) + if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile') + { + $result = dol_delete_file($filesarray[$key]['fullname'], 1, 1); + if ($result) + { + $count++; + $countdeleted++; + } else { + $counterror++; + } + } + } + } + + // Update cachenbofdoc + if (!empty($conf->ecm->enabled) && $choice == 'allfiles') + { + require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; + $ecmdirstatic = new EcmDirectory($this->db); + $result = $ecmdirstatic->refreshcachenboffile(1); + } } } - if ($count > 0) - { + if ($count > 0) { $this->output = $langs->trans("PurgeNDirectoriesDeleted", $countdeleted); if ($count > $countdeleted) $this->output .= '
'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted)); - } else $this->output = $langs->trans("PurgeNothingToDelete").($choice == 'tempfilesold' ? ' (older than 24h)' : ''); + } else { + $this->output = $langs->trans("PurgeNothingToDelete").(in_array('tempfilesold', $choicesarray) ? ' (older than 24h for temp files)' : ''); + } // Recreate temp dir that are not automatically recreated by core code for performance purpose, we need them - if (!empty($conf->api->enabled)) - { + if (!empty($conf->api->enabled)) { dol_mkdir($conf->api->dir_temp); } dol_mkdir($conf->user->dir_temp); diff --git a/htdocs/core/lib/categories.lib.php b/htdocs/core/lib/categories.lib.php index e900e6ff424..f6942cb5265 100644 --- a/htdocs/core/lib/categories.lib.php +++ b/htdocs/core/lib/categories.lib.php @@ -57,7 +57,7 @@ function categories_prepare_head(Categorie $object, $type) $h++; } - $head[$h][0] = DOL_URL_ROOT.'/categories/info.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/categories/info.php?id='.$object->id.'&type='.$type; $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++; diff --git a/htdocs/core/lib/ecm.lib.php b/htdocs/core/lib/ecm.lib.php index 1f22e464358..2c1edc5e675 100644 --- a/htdocs/core/lib/ecm.lib.php +++ b/htdocs/core/lib/ecm.lib.php @@ -111,6 +111,16 @@ function ecm_file_prepare_head($object) $head[$h][2] = 'card'; $h++; + // Notes + $head[$h][0] = DOL_URL_ROOT.'/ecm/file_note.php?section='.$object->section_id.'&urlfile='.urlencode($object->label); + $head[$h][1] = $langs->trans("Notes"); + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + return $head; } diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index 0be1cfbc3bc..6a590b44368 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -2231,7 +2231,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, // Fix modulepart if ($modulepart == 'users') $modulepart = 'user'; - dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity); + dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity); // We define $accessallowed and $sqlprotectagainstexternals $accessallowed = 0; @@ -2260,6 +2260,11 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $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 == 'doctemplates' && !empty($dolibarr_main_data_root)) + { + $accessallowed = $user->admin; + $original_file = $dolibarr_main_data_root.'/doctemplates/'.$original_file; + } // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) { $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file))); @@ -2642,7 +2647,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, } $original_file = $conf->accounting->dir_output.'/'.$original_file; } // Wrapping pour les expedition - elseif ($modulepart == 'expedition' && !empty($conf->expedition->dir_output)) + elseif (($modulepart == 'expedition' || $modulepart == 'shipment') && !empty($conf->expedition->dir_output)) { if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) { @@ -2650,7 +2655,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, } $original_file = $conf->expedition->dir_output."/sending/".$original_file; } // Delivery Note Wrapping - elseif ($modulepart == 'delivery' && !empty($conf->expedition->dir_output)) + elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) { if ($fuser->rights->expedition->delivery->{$lire} || preg_match('/^specimen/i', $original_file)) { diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 4fd44ee6ba3..884d8eac496 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1620,6 +1620,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref); $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2); if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; + if ($showimage) { $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0); @@ -1636,8 +1637,11 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $nophoto = ''; $morehtmlleft .= '
'; } else { // Show no photo link - $nophoto = '/public/theme/common/nophoto.png'; - $morehtmlleft .= '
No photo
'; + $nophoto = img_picto('No photo', 'object_ticket'); + $morehtmlleft .= ''; + $morehtmlleft .= '
'; + $morehtmlleft .= $nophoto; + $morehtmlleft .= '
'; } } } else { @@ -2883,16 +2887,40 @@ function getUserRemoteIP() { if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) { if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) { - $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); + if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) { + $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been forged by client + } else { + $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client + } } else { - $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here + $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy } } else { - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy } return $ip; } +/** + * Return if we are using a HTTPS connexion + * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy) + * Take HTTP_X_FORWARDED_PROTO (defined when using proxy) + * Then HTTP_X_FORWARDED_SSL + * + * @return boolean True if user is using HTTPS + */ +function getIsHTTPS() +{ + $isSecure = false; + if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { + $isSecure = true; + } + elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') { + $isSecure = true; + } + return $isSecure; +} + /** * Return a country code from IP. Empty string if not found. * @@ -3210,10 +3238,10 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected', 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'building', 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cron', 'cubes', - 'delete', 'dolly', 'dollyrevert', 'donation', 'edit', 'ellipsis-h', 'email', 'eraser', 'external-link-alt', 'external-link-square-alt', + 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'edit', 'ellipsis-h', 'email', 'eraser', 'external-link-alt', 'external-link-square-alt', 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'group', 'help', 'holiday', - 'intervention', 'label', 'language', 'list', 'listlight', 'lot', + 'intervention', 'label', 'language', 'link', 'list', 'listlight', 'lot', 'map-marker-alt', 'member', 'money-bill-alt', 'mrp', 'note', 'next', 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom', 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder', @@ -4195,17 +4223,18 @@ function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = * @param string $sortorder Current sort order * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag. * @param string $tooltip Tooltip + * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style * @return void */ -function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "") +function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0) { - print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip); + print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle); } /** * Get title line of an array * - * @param string $name Translation key of field + * @param string $name Translation key of field to show or complete HTML string to show * @param int $thead 0=To use with standard table format, 1=To use inside , 2=To use with
* @param string $file Url used when we click on sort picto * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def" @@ -4217,9 +4246,10 @@ function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $m * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '. * @param string $disablesortlink 1=Disable sort link * @param string $tooltip Tooltip + * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style * @return string */ -function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '') +function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0) { global $conf, $langs, $form; //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder
\n"; @@ -4238,9 +4268,10 @@ function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin $tmpfield = explode(',', $field); $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep' - if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) { + if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) { $prefix = 'wrapcolumntitle '.$prefix; } + //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1); // If field is used as sort criteria we use a specific css class liste_titre_sel // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom") @@ -4250,7 +4281,7 @@ function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin } $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib; //$out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : ''); - $out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : ''); + $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : ''; $out .= '>'; if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field @@ -4430,7 +4461,7 @@ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $savlimit = $limit; $savtotalnboflines = $totalnboflines; - $totalnboflines = abs($totalnboflines); + $totalnboflines = abs((int) $totalnboflines); if ($picto == 'setup') $picto = 'title_setup.png'; if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif'; @@ -4846,7 +4877,7 @@ function price2num($amount, $rounding = '', $option = 0) elseif ($rounding == 'CR') $nbofdectoround = 8; elseif (is_numeric($rounding)) $nbofdectoround = $rounding; //print "RR".$amount.' - '.$nbofdectoround.'
'; - if (dol_strlen($nbofdectoround)) $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0. + if (dol_strlen($nbofdectoround)) $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0. else return 'ErrorBadParameterProvidedToFunction'; //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'
'; @@ -4946,8 +4977,7 @@ function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_sell $vatratecleaned = $vatrate; $reg = array(); - if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" - { + if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)" $vatratecleaned = trim($reg[1]); $vatratecode = $reg[2]; } @@ -4958,25 +4988,20 @@ function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_sell }*/ // Some test to guess with no need to make database access - if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax - { - if ($local == 1) - { + if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax + if ($local == 1) { if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0; - if ($thirdparty_seller->id == $mysoc->id) - { + if ($thirdparty_seller->id == $mysoc->id) { if (!$thirdparty_buyer->localtax1_assuj) return 0; } else { if (!$thirdparty_seller->localtax1_assuj) return 0; } } - if ($local == 2) - { + if ($local == 2) { //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0; if (!$mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0. - if ($thirdparty_seller->id == $mysoc->id) - { + if ($thirdparty_seller->id == $mysoc->id) { if (!$thirdparty_buyer->localtax2_assuj) return 0; } else { if (!$thirdparty_seller->localtax2_assuj) return 0; @@ -4988,43 +5013,34 @@ function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_sell } // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on. - if (in_array($mysoc->country_code, array('ES'))) - { + if (in_array($mysoc->country_code, array('ES'))) { $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1; } // Search local taxes if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) { - if ($local == 1) - { - if ($thirdparty_seller != $mysoc) - { + if ($local == 1) { + if ($thirdparty_seller != $mysoc) { if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate { return $thirdparty_seller->localtax1_value; } - } else // i am the seller - { - if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat. - { + } else { // i am the seller + if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1; } } } - if ($local == 2) - { - if ($thirdparty_seller != $mysoc) - { + if ($local == 2) { + if ($thirdparty_seller != $mysoc) { if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate // TODO We should also return value defined on thirdparty only if defined { return $thirdparty_seller->localtax2_value; } - } else // i am the seller - { - if (in_array($mysoc->country_code, array('ES'))) - { + } else { // i am the seller + if (in_array($mysoc->country_code, array('ES'))) { return $thirdparty_buyer->localtax2_value; } else { return $conf->global->MAIN_INFO_VALUE_LOCALTAX2; @@ -5046,8 +5062,10 @@ function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_sell if ($resql) { $obj = $db->fetch_object($resql); - if ($local == 1) return $obj->localtax1; - elseif ($local == 2) return $obj->localtax2; + if ($obj) { + if ($local == 1) return $obj->localtax1; + elseif ($local == 2) return $obj->localtax2; + } } return 0; @@ -5068,8 +5086,7 @@ function isOnlyOneLocalTax($local) $valors = explode(":", $tax); - if (count($valors) > 1) - { + if (count($valors) > 1) { return false; } else { return true; @@ -5105,8 +5122,8 @@ function get_localtax_by_third($local) /** - * Get vat main information from Id. - * You can call getLocalTaxesFromRate after to get other fields. + * Get tax (VAT) main information from Id. + * You can also call getLocalTaxesFromRate() after to get only localtax fields. * * @param int|string $vatrate VAT ID or Rate. Value can be value or the string with code into parenthesis or rowid if $firstparamisid is 1. Example: '8.5' or '8.5 (8.5NPR)' or 123. * @param Societe $buyer Company object @@ -5122,12 +5139,15 @@ function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid dol_syslog("getTaxesFromId vat id or rate = ".$vatrate); // Search local taxes - $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy"; + $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,"; + $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type"; $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t"; - if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate; - else { + if ($firstparamisid) { + $sql .= " WHERE t.rowid = ".(int) $vatrate; + } else { $vatratecleaned = $vatrate; $vatratecode = ''; + $reg = array(); if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" { $vatratecleaned = $reg[1]; @@ -5143,10 +5163,20 @@ function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy); + if ($obj) return array( + 'rowid'=>$obj->rowid, + 'code'=>$obj->code, + 'rate'=>$obj->rate, + 'localtax1'=>$obj->localtax1, + 'localtax1_type'=>$obj->localtax1_type, + 'localtax2'=>$obj->localtax2, + 'localtax2_type'=>$obj->localtax2_type, + 'npr'=>$obj->npr, + 'accountancy_code_sell'=>$obj->accountancy_code_sell, + 'accountancy_code_buy'=>$obj->accountancy_code_buy + ); else return array(); } else dol_print_error($db); @@ -5191,7 +5221,7 @@ function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisi $sql .= ", ".MAIN_DB_PREFIX."c_country as c"; if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ?? - else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'"; + else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'"; $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1"; if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'"; } @@ -5213,7 +5243,7 @@ function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisi } } - return 0; + return array(); } /** @@ -5591,12 +5621,10 @@ function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = ' if ($level == 3) $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1); } else { // We will enhance here a common way of forging path for document storage. - // In a future, we may distribut directories on several levels depending on setup and object. + // In a future, we may distribute directories on several levels depending on setup and object. // Here, $object->id, $object->ref and $modulepart are required. //var_dump($modulepart); - if (!in_array($modulepart, array('product'))) { // Test to remove - $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref); - } + $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref); } if (empty($withoutslash) && !empty($path)) $path .= '/'; @@ -8534,7 +8562,7 @@ function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = ' * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name * @param int $displayMode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto * @param string $url The url for link - * @param array $params Various params. Example: array('tooltip'=>'...', 'badgeParams'=>...) + * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...) * @return string Html status string */ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array()) @@ -8603,7 +8631,7 @@ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $st $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort); $dolGetBadgeParams['attr']['class'] = 'badge-status'; - $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : $params['tooltip']; + $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : ''); if ($displayMode == 3) { $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams); @@ -8713,7 +8741,7 @@ function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $u } $class = 'btnTitle'; - if ($iconClass == 'fa fa-plus-circle') $class .= ' btnTitlePlus'; + if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) $class .= ' btnTitlePlus'; $useclassfortooltip = 1; if (!empty($params['morecss'])) $class .= ' '.$params['morecss']; diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 7d00fee0773..8391c6aab06 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -759,7 +759,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits'; // Extract value for third party mask counter - $regClient = array(); + $regClientRef = array(); if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { $maskrefclient = $regClientRef[1].$regClientRef[2]; @@ -791,8 +791,8 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } // Extract value for user - if (preg_match('/\{(u+)\}/i', $mask, $regType)) - { + $regType = array(); + if (preg_match('/\{(u+)\}/i', $mask, $regType)) { $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; if (is_object($objuser)) $lastname = $objuser->lastname; @@ -931,12 +931,10 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp1)."'"; $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') "; $sqlwhere .= ')'; - } elseif ($resetEveryMonth) - { + } elseif ($resetEveryMonth) { $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'"; $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')"; - } else // reset is done on january - { + } else { // reset is done on january $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$db->escape($yearcomp)."')"; } } @@ -1040,8 +1038,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } else dol_print_error($db); $numFinal = $ref; - } elseif ($mode == 'next') - { + } elseif ($mode == 'next') { $counter++; // If value for $counter has a length higher than $maskcounter chars @@ -1184,8 +1181,7 @@ function check_value($mask, $value) $hasglobalcounter = false; // Extract value for mask counter, mask raz and mask offset $reg = array(); - if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) - { + if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) { $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : ''); $maskcounter = $reg[1]; $hasglobalcounter = true; @@ -1253,31 +1249,25 @@ function check_value($mask, $value) 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"; + //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."
\n"; - // Check we have a number in ($posnumstart+1).', '.dol_strlen($maskcounter) - // + if (function_exists('mb_strrpos')) { + $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8'); + } + else { + $posnumstart = strrpos($maskwithnocode, $maskcounter); + } // Pos of counter in final string (from 0 to ...) + if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; - // Check length - $len = dol_strlen($maskwithnocode); - if (dol_strlen($value) != $len) $result = -1; + // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter) + // TODO - // Define $maskLike - /* seems not used - $maskLike = dol_string_nospecial($mask); - $maskLike = str_replace("%","_",$maskLike); - // Replace protected special codes with matching number of _ as wild card caracter - $maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskLike); - $maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskLike); - $maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskLike); - $maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskLike); - $maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskLike); - $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike); - if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike); - */ + // Check length + $len = dol_strlen($maskwithnocode); + if (dol_strlen($value) != $len) $result = -1; - dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); - return $result; + dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); + return $result; } /** diff --git a/htdocs/core/lib/geturl.lib.php b/htdocs/core/lib/geturl.lib.php index 8cfc08222cd..7e93623f3c1 100644 --- a/htdocs/core/lib/geturl.lib.php +++ b/htdocs/core/lib/geturl.lib.php @@ -33,7 +33,7 @@ * @param string[] $addheaders Array of string to add into header. Example: ('Accept: application/xrds+xml', ....) * @param string[] $allowedschemes List of schemes that are allowed ('http' + 'https' only by default) * @param int $localurl 0=Only external URL are possible, 1=Only local URL, 2=Both external and local URL are allowed. - * @return array Returns an associative array containing the response from the server array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + * @return array Returns an associative array containing the response from the server array('content'=>response, 'curl_error_no'=>errno, 'curl_error_msg'=>errmsg...) */ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = 1, $addheaders = array(), $allowedschemes = array('http', 'https'), $localurl = 0) { diff --git a/htdocs/core/lib/price.lib.php b/htdocs/core/lib/price.lib.php index ce14295b4b2..98311d093cd 100644 --- a/htdocs/core/lib/price.lib.php +++ b/htdocs/core/lib/price.lib.php @@ -104,7 +104,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt //var_dump($seller->country_id);exit; } if (empty($localtaxes_array) || !is_array($localtaxes_array)) { - dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing", LOG_WARNING); + dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter localtaxes_array that is missing or empty", LOG_WARNING); } if (!is_numeric($txtva)) { dol_syslog("Price.lib::calcul_price_total Warning: function was called with a parameter vat rate that is not a real numeric value. There is surely a bug.", LOG_ERR); @@ -129,7 +129,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $localtax1_type = 0; $localtax2_type = 0; - if (is_array($localtaxes_array)) { + if (is_array($localtaxes_array) && count($localtaxes_array)) { $localtax1_type = $localtaxes_array[0]; $localtax1_rate = $localtaxes_array[1]; $localtax2_type = $localtaxes_array[2]; diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index 909e51dc6d7..9ce8d84d7e3 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -546,16 +546,17 @@ function show_stats_for_company($product, $socid) * Return translation label of a unit key. * Function kept for backward compatibility. * - * @param string $scale Scale of unit: '0', '-3', '6', ... - * @param string $measuring_style Style of unit: weight, volume,... - * @param int $unit ID of unit (rowid in llx_c_units table) - * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. - * @return string Unit string + * @param string $scale Scale of unit: '0', '-3', '6', ... + * @param string $measuring_style Style of unit: weight, volume,... + * @param int $unit ID of unit (rowid in llx_c_units table) + * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. + * @param Translate $outputlangs Language object + * @return string Unit string * @see measuringUnitString() formproduct->selectMeasuringUnits() */ -function measuring_units_string($scale = '', $measuring_style = '', $unit = 0, $use_short_label = 0) +function measuring_units_string($scale = '', $measuring_style = '', $unit = 0, $use_short_label = 0, $outputlangs = null) { - return measuringUnitString($unit, $measuring_style, $scale, $use_short_label); + return measuringUnitString($unit, $measuring_style, $scale, $use_short_label, $outputlangs); } /** @@ -565,14 +566,19 @@ function measuring_units_string($scale = '', $measuring_style = '', $unit = 0, $ * @param string $measuring_style Style of unit: 'weight', 'volume', ..., '' = 'net_measure' for option PRODUCT_ADD_NET_MEASURE * @param string $scale Scale of unit: '0', '-3', '6', ... * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated. + * @param Translate $outputlangs Language object * @return string Unit string * @see formproduct->selectMeasuringUnits() */ -function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_short_label = 0) +function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_short_label = 0, $outputlangs = null) { global $langs, $db; global $measuring_unit_cache; + if (empty($outputlangs)) { + $outputlangs = $langs; + } + if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) { require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php'; @@ -605,7 +611,7 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho } else { if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) { if ($use_short_label) $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label; - else $labeltoreturn = $langs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); + else $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); } else { $labeltoreturn = ''; } diff --git a/htdocs/core/lib/salaries.lib.php b/htdocs/core/lib/salaries.lib.php index c11e37b7aaa..f4662f43991 100644 --- a/htdocs/core/lib/salaries.lib.php +++ b/htdocs/core/lib/salaries.lib.php @@ -50,7 +50,7 @@ function salaries_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/salaries/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/ticket.lib.php b/htdocs/core/lib/ticket.lib.php index dc7766dbdfa..92fdfa21aff 100644 --- a/htdocs/core/lib/ticket.lib.php +++ b/htdocs/core/lib/ticket.lib.php @@ -562,16 +562,15 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n"; //$out.=''; - $out .= ''.$langs->trans("Search").' : '; + $out .= ''.$langs->trans("Search").' : '; if ($donetodo) { $out .= ''; } $out .= ''.$langs->trans("Type").' '; - $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1); + $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp'); $out .= ''; $out .= ''; - $out .= $langs->trans("Label").' '; - $out .= ''; + $out .= ''; $out .= ''; $out .= ''; @@ -857,7 +856,7 @@ function getTicketTimelineIcon($actionstatic, &$histo, $key) if ($actionstatic->code == 'AC_TICKET_CREATE') { $iconClass = 'fa fa-ticket'; } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') { - $iconClass = 'fa fa-pencil'; + $iconClass = 'fa fa-pencilxxx'; } elseif ($actionstatic->code == 'TICKET_MSG') { $iconClass = 'fa fa-comments'; } elseif ($actionstatic->code == 'TICKET_MSG_PRIVATE') { diff --git a/htdocs/core/lib/website2.lib.php b/htdocs/core/lib/website2.lib.php index 1ed80ece372..3462212ee25 100644 --- a/htdocs/core/lib/website2.lib.php +++ b/htdocs/core/lib/website2.lib.php @@ -129,6 +129,7 @@ function dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage) $shortlangcode = ''; if ($objectpage->lang) $shortlangcode = substr($objectpage->lang, 0, 2); // en_US or en-US -> en + if (empty($shortlangcode)) $shortlangcode = substr($object->lang, 0, 2); // en_US or en-US -> en $tplcontent = ''; $tplcontent .= "id > 0) { $tmpshortlangcode = ''; if ($tmppage->lang) $tmpshortlangcode = preg_replace('/[_-].*$/', '', $tmppage->lang); // en_US or en-US -> en + if (empty($tmpshortlangcode)) $tmpshortlangcode = preg_replace('/[_-].*$/', '', $object->lang); // en_US or en-US -> en if ($tmpshortlangcode != $shortlangcode) { $tplcontent .= ''."\n"; } diff --git a/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php b/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php index b5e1fc80a1d..18f2d405acf 100644 --- a/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php +++ b/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php @@ -162,10 +162,10 @@ class doc_generic_bom_odt extends ModelePDFBom if ($nbofiles) { - $texte .= '